The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
feat(server): let a trip owner switch trip addons for one trip
Maurice3f38621024fb
diff --git a/server/scripts/repository-owners.json b/server/scripts/repository-owners.jsonindex 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.jsonindex 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.jsonindex 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.tsindex 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<TripAddonOverrides>(this);}export const AddonsSchema = defineEntity({@@ -30,5 +32,6 @@ export const AddonsSchema = defineEntity({enabled: p.type(IntegerFlagType).nullable().default(false),config: p.json<AddonConfig>().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.tsnew file mode 100644index 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<Trips>;+ trip_id!: number;+ addon!: Ref<Addons>;+ 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.tsindex 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<TodoCategoryAssignees>(this);todo_items_collection = new Collection<TodoItems>(this);tour_drafts_collection = new Collection<TourDrafts>(this);+ trip_addon_overrides_collection = new Collection<TripAddonOverrides>(this);trip_album_links_collection = new Collection<TripAlbumLinks>(this);trip_document_links_collection = new Collection<TripDocumentLinks>(this);trip_files_collection = new Collection<TripFiles>(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.tsindex 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.tsnew file mode 100644index 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<string | null>;+}diff --git a/server/src/db/kysely/db.ts b/server/src/db/kysely/db.tsindex 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.tsnew file mode 100644index 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.tsnew file mode 100644index 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<DB, 'trip_addon_overrides'>;+type OverridesAccessKyselyDB = Pick<DB, 'trip_addon_overrides' | 'trips' | 'trip_members'>;++/**+ * `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<TripAddonOverrides> {+ /** Every override the trip holds, in addon id order. */+ async listForTrip(trip_id: number): Promise<TripAddonOverrideRow[]> {+ const rows = await this.kysely<OverridesKyselyDB>()+ .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<boolean | null> {+ const row = await this.kysely<OverridesKyselyDB>()+ .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<Array<{ trip_id: number; enabled: boolean }>> {+ if (trip_ids.length === 0) return [];+ const rows = await this.kysely<OverridesKyselyDB>()+ .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<void> {+ const value = enabled ? 1 : 0;+ const at = dbNow();+ await this.kysely<OverridesKyselyDB>()+ .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<void> {+ await this.kysely<OverridesKyselyDB>()+ .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<void> {+ await this.kysely<OverridesKyselyDB>()+ .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<boolean> {+ const row = await this.kysely<OverridesAccessKyselyDB>()+ .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.tsindex 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<Promise<unknown>>(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.tsindex 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.tsindex 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.tsindex 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 intodiff --git a/server/src/nest-rpc/plugin-guards.service.ts b/server/src/nest-rpc/plugin-guards.service.tsindex 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<T>(params: Record<string, unknown>, ctx: PluginRpcContext, read: (userId: number) => T): Promise<T> {+ async tripRead<T>(+ params: Record<string, unknown>,+ ctx: PluginRpcContext,+ read: (userId: number) => T,+ addon?: RpcAddon,+ ): Promise<T> {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<void> {+ /**+ * 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<void> {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<void> {- 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<void> {+ 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<number[]> {+ 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.tsindex 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<boolean> => 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<boolean>) & {+ 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<boolean>,+): 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<boolean> {+ 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'): 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 collabFeatureGate(feature: 'chat' | 'notes' | 'polls' | 'links') {- return async (_ctx: McpContext, self: HasAddons): Promise<boolean> =>- (await self.addons.isAddonEnabled(ADDON_IDS.COLLAB)) && (await self.addons.getCollabFeatures())[feature];+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.tsindex 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<Request & { user?: User | null }>().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.tsnew file mode 100644index 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 `<Label> addon is not enabled`, the 404 a switched-off+ * addon answers with, as the REST routes have always spelled it.+ */+const ADDON_LABELS: Readonly<Record<AddonId, string>> = {+ [ADDON_IDS.MCP]: 'MCP',+ [ADDON_IDS.PACKING]: 'Packing',+ [ADDON_IDS.BUDGET]: 'Costs',+ [ADDON_IDS.DOCUMENTS]: 'Documents',+ [ADDON_IDS.VACAY]: 'Vacay',+ [ADDON_IDS.ATLAS]: 'Atlas',+ [ADDON_IDS.COLLAB]: 'Collab',+ [ADDON_IDS.JOURNEY]: 'Journey',+ [ADDON_IDS.AIRTRAIL]: 'AirTrail',+ [ADDON_IDS.DAWARICH]: 'Dawarich',+ [ADDON_IDS.LLM_PARSING]: 'AI parsing',+ [ADDON_IDS.COLLECTIONS]: 'Collections',+ [ADDON_IDS.ROADTRIP]: 'Road trip',+ [ADDON_IDS.TOURS]: 'Tours',+ [ADDON_IDS.AI_ASSISTANT]: 'AI assistant',+};++/**+ * The addons a trip can switch for itself. The seeder gives them type `trip`;+ * this is the same set spelled out for the places that gate a surface before+ * any row is read (the MCP tool gate, the plugin event fan-out).+ */+export const TRIP_ADDON_IDS: ReadonlySet<string> = new Set<string>([+ ADDON_IDS.PACKING,+ ADDON_IDS.BUDGET,+ ADDON_IDS.DOCUMENTS,+ ADDON_IDS.COLLAB,+ ADDON_IDS.ROADTRIP,+ ADDON_IDS.TOURS,+]);++/** `<Label> addon is not enabled` for one addon id; an id without a label leads with the id. */+export function addonOffMessage(addonId: string): string {+ const label = (ADDON_LABELS as Readonly<Record<string, string>>)[addonId] ?? addonId;+ return `${label} addon is not enabled`;+}++/**+ * The photo addon an old migration seeded as a trip addon. It stands for the+ * photo providers, is never switched on as such and has no trip surface, so+ * it is no addon a trip can switch.+ */+const LEGACY_PHOTO_ADDON = 'memories';++type TripAddonRow = AddonRow & { id: string };++/** A row a trip can switch for itself: a trip addon, the legacy photo row aside. */+export function isTripAddonRow(row: AddonRow | null): row is TripAddonRow {+ return !!row?.id && row.type === 'trip' && row.id !== LEGACY_PHOTO_ADDON;+}diff --git a/server/src/nest/addons/addons.module.ts b/server/src/nest/addons/addons.module.tsindex c5b8d34b1..8bb95260b 100644--- a/server/src/nest/addons/addons.module.ts+++ b/server/src/nest/addons/addons.module.ts@@ -2,11 +2,19 @@ import { Addons } from '../../db/entities/Addons.entity';import { AppSettings } from '../../db/entities/AppSettings.entity';import { PhotoProviderFields } from '../../db/entities/PhotoProviderFields.entity';import { PhotoProviders } from '../../db/entities/PhotoProviders.entity';+import { TripAddonOverrides } from '../../db/entities/TripAddonOverrides.entity';import { Users } from '../../db/entities/Users.entity';+import { PermissionsModule } from '../permissions/permissions.module';+import { RealtimeModule } from '../realtime/realtime.module';+import { TripMembershipModule } from '../trip-membership/trip-membership.module';import { AddonGuard } from './addon.guard';import { AddonsController } from './addons.controller';import { AddonsMcp } from './addons.mcp';import { AddonsService } from './addons.service';+import { TripAddonGuard } from './trip-addon.guard';+import { TripAddonsController } from './trip-addons.controller';+import { TripAddonsMcp } from './trip-addons.mcp';+import { TripAddonsService } from './trip-addons.service';import { MikroOrmModule } from '@mikro-orm/nestjs';import { Module } from '@nestjs/common';@@ -32,11 +40,27 @@ import { Module } from '@nestjs/common';* added by Task 5: `googleKeySource` passes `UsersRepository` explicitly to* `instance-api-keys.ts`'s resolveApiKey now, instead of that file resolving* one off the ambient request context.+ *+ * TripAddonsService answers whether a trip addon applies to one trip (the+ * owner's override, else the instance switch) and owns the per-trip overrides+ * behind GET/PUT /api/trips/:tripId/addons and their MCP tools. It asks+ * TripMembershipModule, a leaf, whether the caller may see the trip; its+ * routes take TripAccessGuard and TripOwnerGuard from PermissionsModule, and+ * RealtimeModule is named so a hand-built test module that imports this one+ * resolves the broadcast without listing it.+ *+ * TripAddonGuard is the trip-scoped twin of AddonGuard: it answers @RequireAddon+ * with AddonsService.isEnabledForTrip after TripAccessGuard parked the trip.*/@Module({- imports: [MikroOrmModule.forFeature([Addons, PhotoProviders, PhotoProviderFields, AppSettings, Users])],- controllers: [AddonsController],- providers: [AddonsService, AddonGuard, AddonsMcp],- exports: [AddonsService, AddonGuard],+ imports: [+ MikroOrmModule.forFeature([Addons, PhotoProviders, PhotoProviderFields, AppSettings, Users, TripAddonOverrides]),+ PermissionsModule,+ RealtimeModule,+ TripMembershipModule,+ ],+ controllers: [AddonsController, TripAddonsController],+ providers: [AddonsService, AddonGuard, TripAddonGuard, AddonsMcp, TripAddonsService, TripAddonsMcp],+ exports: [AddonsService, AddonGuard, TripAddonGuard, TripAddonsService],})export class AddonsModule {}diff --git a/server/src/nest/addons/addons.service.ts b/server/src/nest/addons/addons.service.tsindex 1982c3927..abd7832a9 100644--- a/server/src/nest/addons/addons.service.ts+++ b/server/src/nest/addons/addons.service.ts@@ -4,6 +4,7 @@ import { Addons } from '../../db/entities/Addons.entity';import { AppSettings } from '../../db/entities/AppSettings.entity';import { PhotoProviderFields } from '../../db/entities/PhotoProviderFields.entity';import { PhotoProviders } from '../../db/entities/PhotoProviders.entity';+import { TripAddonOverrides } from '../../db/entities/TripAddonOverrides.entity';import { Users } from '../../db/entities/Users.entity';import type { AddonsRepository } from '../../db/repositories/Addons.repository';import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';@@ -12,12 +13,14 @@ import type {PhotoProviderFieldRow,} from '../../db/repositories/PhotoProviderFields.repository';import type { PhotoProvidersRepository, PhotoProviderRow } from '../../db/repositories/PhotoProviders.repository';+import type { TripAddonOverridesRepository } from '../../db/repositories/TripAddonOverrides.repository';import type { UsersRepository } from '../../db/repositories/Users.repository';import { readAppSetting } from '../common/app-settings.registry';import { getPhotoProviderConfig } from '../common/photo-provider-config';import { readTransitProvider, writeTransitProvider } from '../common/transit-provider';import { UnitOfWork } from '../database/unit-of-work';import { resolveApiKey, type ApiKeySource } from '../settings/instance-api-keys';+import { isTripAddonRow } from './addons.constants';import { InjectRepository } from '@mikro-orm/nestjs';import { Injectable } from '@nestjs/common';import type { TransitProvider } from '@trek/shared';@@ -51,12 +54,62 @@ export class AddonsService {@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,@InjectRepository(Users) private readonly users: UsersRepository,private readonly uow: UnitOfWork,+ @InjectRepository(TripAddonOverrides) private readonly tripOverrides: TripAddonOverridesRepository,) {}+ /** The instance switch alone. A trip-scoped surface asks isEnabledForTrip instead. */async isAddonEnabled(addonId: string): Promise<boolean> {return this.addons.isEnabled(addonId);}+ /**+ * Whether an addon applies to one trip: the trip owner's choice for the trip+ * when there is one, else the instance switch. Only addons of type `trip`+ * can be chosen per trip; any other addon answers with the instance switch,+ * and an unknown id is off. The caller has checked the trip is the user's.+ */+ async isEnabledForTrip(tripId: number, addonId: string): Promise<boolean> {+ const addon = await this.addons.findById(addonId);+ if (!addon) return false;+ const instanceEnabled = !!addon.enabled;+ if (!isTripAddonRow(addon)) return instanceEnabled;+ return (await this.tripOverrides.findForTrip(tripId, addon.id)) ?? instanceEnabled;+ }++ /**+ * The trips among `tripIds` the addon applies to, in their order: each+ * trip's own choice, else the instance switch, as isEnabledForTrip answers+ * for one. A surface that reads across trips (the tour library, the Atlas+ * sums) narrows the user's trips with it, so a trip that switched the+ * addon off shows nothing there. Two reads, whatever the number of trips.+ */+ async tripsWithAddon(tripIds: readonly number[], addonId: string): Promise<number[]> {+ if (tripIds.length === 0) return [];+ const addon = await this.addons.findById(addonId);+ if (!addon) return [];+ const instanceEnabled = !!addon.enabled;+ if (!isTripAddonRow(addon)) return instanceEnabled ? [...tripIds] : [];+ const chosen = new Map(+ (await this.tripOverrides.listForTrips(tripIds, addon.id)).map((row) => [row.trip_id, row.enabled]),+ );+ return tripIds.filter((id) => chosen.get(id) ?? instanceEnabled);+ }++ /**+ * For a surface without a trip (a tour library, a search across trips, an+ * MCP tool list): open when the instance has the addon on, or when any trip+ * the user owns or belongs to switched it on for itself. A trip that+ * switched it off closes nothing here, the instance switch still holds for+ * the user's other trips.+ */+ async isEnabledForUserAnywhere(userId: number, addonId: string): Promise<boolean> {+ const addon = await this.addons.findById(addonId);+ if (!addon) return false;+ if (addon.enabled) return true;+ if (!isTripAddonRow(addon)) return false;+ return this.tripOverrides.anyEnabledForUser(userId, addon.id);+ }+async getBagTracking() {const value = await readAppSetting(this.appSettings, 'bag_tracking_enabled');return { enabled: value === 'true' };@@ -126,8 +179,17 @@ export class AddonsService {* there, so a value stored before the install became managed must not keep it on.*/async isWandererAvailable(): Promise<boolean> {+ return (await this.isWandererAllowed()) && (await this.isAddonEnabled(ADDON_IDS.TOURS));+ }++ /**+ * The wanderer sub-option alone: the admin allowed it under Tours and the install is not managed.+ * It stays instance-wide and applies wherever Tours is on, the instance switch or a trip's own,+ * so a route asks this beside AddonGuard or TripAddonGuard, which decide Tours.+ */+ async isWandererAllowed(): Promise<boolean> {if (readEnv().managed.enabled) return false;- return (await this.isAddonEnabled(ADDON_IDS.TOURS)) && (await this.getToursWanderer()).enabled;+ return (await this.getToursWanderer()).enabled;}/**@@ -212,6 +274,13 @@ export class AddonsService {toursWanderer: await this.isWandererAvailable(),toursHikingMap: (await this.isAddonEnabled(ADDON_IDS.TOURS)) && (await this.getToursHikingMap()).enabled,toursCycleMap: (await this.isAddonEnabled(ADDON_IDS.TOURS)) && (await this.getToursCycleMap()).enabled,+ // The same three options without the instance Tours switch: a trip may switch Tours on+ // for itself, and the planner of that trip offers them once Tours is on there.+ toursOptions: {+ wanderer: await this.isWandererAllowed(),+ hikingMap: (await this.getToursHikingMap()).enabled,+ cycleMap: (await this.getToursCycleMap()).enabled,+ },addons: [// The repository row carries every scalar column (description, config,// sort_order included); the legacy statement selected only these five,diff --git a/server/src/nest/addons/trip-addon-tool-gate.ts b/server/src/nest/addons/trip-addon-tool-gate.tsnew file mode 100644index 000000000..7fcb82a80--- /dev/null+++ b/server/src/nest/addons/trip-addon-tool-gate.ts@@ -0,0 +1,48 @@+import { errorResult, type McpToolGate } from '../../nest-mcp';+import { toRowId } from '../common/row-id';+import type { TripAccessService } from '../trip-membership/trip-access.service';+import { addonsOfGate } from './addon-gate';+import { addonOffMessage, TRIP_ADDON_IDS } from './addons.constants';+import type { AddonsService } from './addons.service';++/** The trip a call names in its `tripId` argument, or null for a call about no one trip. */+function tripIdOf(args: unknown): number | null {+ if (!args || typeof args !== 'object' || !('tripId' in args)) return null;+ return toRowId((args as { tripId: unknown }).tripId);+}++/**+ * The per-call half of the addon gates. A tool's `when:` gate (addonGate,+ * collabFeatureGate, ...) runs once, when a session attaches its tools, and+ * registers a tool while its addon is on anywhere for the user. This gate runs+ * on every call of such a tool and asks again for the trip the call names: a+ * trip that has the addon off refuses with `<Label> addon is not enabled`, the+ * text REST answers with, and a trip that switched it on although the+ * instance has it off lets the call through. A call that names no trip is+ * asked about the trip its session is pinned to (`ctx.tripId`, the+ * assistant's trip chat), else about the user's trips as a whole.+ *+ * A trip the caller cannot see is left to the tool, which answers with its own+ * "not found": answering for the addon would tell a stranger what a trip's+ * owner chose, and so that the trip exists.+ *+ * Only trip addons are asked per call; an instance-wide addon (journey, vacay,+ * collections) has no trip side, and switching one off tears the sessions+ * down. Collab's sub-features (chat, notes, polls, links) stay instance-wide,+ * so only the addon itself is asked here.+ */+export function trekTripAddonToolGate(addons: AddonsService, trips: TripAccessService): McpToolGate {+ return async (tool, ctx, args) => {+ const ids = addonsOfGate(tool.when).filter((id) => TRIP_ADDON_IDS.has(id));+ if (ids.length === 0) return undefined;+ const tripId = tripIdOf(args) ?? ctx.tripId ?? null;+ if (tripId !== null && !(await trips.findAccessible(tripId, ctx.userId))) return undefined;+ const on = await Promise.all(+ ids.map((id) =>+ tripId === null ? addons.isEnabledForUserAnywhere(ctx.userId, id) : addons.isEnabledForTrip(tripId, id),+ ),+ );+ const off = ids.find((_id, i) => !on[i]);+ return off === undefined ? undefined : errorResult(addonOffMessage(off));+ };+}diff --git a/server/src/nest/addons/trip-addon.guard.ts b/server/src/nest/addons/trip-addon.guard.tsnew file mode 100644index 000000000..e71afa707--- /dev/null+++ b/server/src/nest/addons/trip-addon.guard.ts@@ -0,0 +1,53 @@+import type { TripAccess } from '../../db/repositories/Trips.repository';+import { TRIP_REQUEST_KEY } from '../permissions/trip-access.guard';+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';++type TripRequest = Request & { [TRIP_REQUEST_KEY]?: TripAccess };++/**+ * Enforces @RequireAddon on a trip-scoped route against what applies to that+ * one trip: the owner's choice for the trip when there is one, else the+ * instance switch. A trip that switched an addon on answers although the admin+ * has it off, and one that switched it off answers 404 `<Label> addon is not+ * enabled`, the same body AddonGuard sends.+ *+ * It runs AFTER TripAccessGuard and reads the trip that guard parked on the+ * request, so a stranger still gets "Trip not found" and never learns from the+ * addon answer that the trip exists or what its owner chose:+ *+ * @UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)+ * @RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')+ *+ * A route without a parked trip is a wiring mistake and fails closed with a+ * 500 rather than answering as if the addon were on. Without the decorator the+ * guard is a no-op. Never put it on a multipart upload; such a handler asks+ * AddonsService.isEnabledForTrip itself.+ */+@Injectable()+export class TripAddonGuard implements CanActivate {+ constructor(+ private readonly addons: AddonsService,+ private readonly reflector: Reflector,+ ) {}++ async canActivate(context: ExecutionContext): Promise<boolean> {+ const meta = this.reflector.getAllAndOverride<RequireAddonMeta | undefined>(REQUIRE_ADDON, [+ context.getHandler(),+ context.getClass(),+ ]);+ if (!meta) return true;+ const trip = context.switchToHttp().getRequest<TripRequest>()[TRIP_REQUEST_KEY];+ if (!trip) throw new Error('TripAddonGuard needs TripAccessGuard ahead of it in the guard chain');+ const ids = typeof meta.addonId === 'string' ? [meta.addonId] : meta.addonId;+ const enabled = await Promise.all(ids.map((id) => this.addons.isEnabledForTrip(trip.id, id)));+ if (!enabled.includes(true)) {+ throw new HttpException({ error: `${meta.label} addon is not enabled` }, 404);+ }+ return true;+ }+}diff --git a/server/src/nest/addons/trip-addons.controller.ts b/server/src/nest/addons/trip-addons.controller.tsnew file mode 100644index 000000000..e0beb76f5--- /dev/null+++ b/server/src/nest/addons/trip-addons.controller.ts@@ -0,0 +1,53 @@+import type { TripAccess } from '../../db/repositories/Trips.repository';+import type { User } from '../../types';+import { CurrentUser } from '../auth-core/current-user.decorator';+import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';+import { ResponseContract } from '../common/response-contract';+import { TripAccessGuard } from '../permissions/trip-access.guard';+import { RequireTripOwner, TripOwnerGuard } from '../permissions/trip-owner.guard';+import { Trip } from '../permissions/trip.decorator';+import { TRIP_ADDON_OWNER_ONLY, TripAddonsService } from './trip-addons.service';+import { Body, Controller, Get, Headers, Param, Put, UseGuards } from '@nestjs/common';+import { tripAddonsResponseSchema, tripAddonUpdateRequestSchema, type TripAddonsResponse } from '@trek/shared';++import { createZodDto } from 'nestjs-zod';++export class TripAddonUpdateDto extends createZodDto(tripAddonUpdateRequestSchema) {}++/**+ * The trip addons of one trip, each on or off for it.+ *+ * Every member reads the list; only the owner changes it (TripOwnerGuard, which+ * an admin who does not own the trip does not pass). A trip the caller cannot+ * see is a 404 from TripAccessGuard before anything else is read.+ *+ * No AddonGuard here: the list is the place to switch an addon on for a trip+ * while it is off for the instance, so it has to answer whatever the+ * instance switches say.+ */+@Controller('api/trips/:tripId/addons')+@UseGuards(JwtAuthGuard, TripAccessGuard)+export class TripAddonsController {+ constructor(private readonly tripAddons: TripAddonsService) {}++ @Get()+ @ResponseContract(tripAddonsResponseSchema)+ async list(@Trip() trip: TripAccess): Promise<TripAddonsResponse> {+ return { tripId: trip.id, addons: await this.tripAddons.effectiveTripAddons(trip.id) };+ }++ @Put(':addonId')+ @UseGuards(TripOwnerGuard)+ @RequireTripOwner(TRIP_ADDON_OWNER_ONLY)+ @ResponseContract(tripAddonsResponseSchema)+ async update(+ @CurrentUser() user: User,+ @Trip() trip: TripAccess,+ @Param('addonId') addonId: string,+ @Body() body: TripAddonUpdateDto,+ @Headers('x-socket-id') socketId?: string,+ ): Promise<TripAddonsResponse> {+ const addons = await this.tripAddons.setTripOverride(trip.id, user.id, addonId, body.enabled, socketId);+ return { tripId: trip.id, addons };+ }+}diff --git a/server/src/nest/addons/trip-addons.mcp.ts b/server/src/nest/addons/trip-addons.mcp.tsnew file mode 100644index 000000000..845da7bf4--- /dev/null+++ b/server/src/nest/addons/trip-addons.mcp.ts@@ -0,0 +1,66 @@+import { noAccess } from '../../mcp/tools/_shared';+import {+ McpController,+ Tool,+ TOOL_ANNOTATIONS_READONLY,+ TOOL_ANNOTATIONS_WRITE,+ ok,+ type McpContext,+} from '../../nest-mcp';+import { TripAccessService } from '../trip-membership/trip-access.service';+import { TripAddonsService } from './trip-addons.service';+import { idSchema, tripAddonIdSchema, tripAddonUpdateRequestSchema } from '@trek/shared';++/**+ * The MCP side of GET and PUT /api/trips/:tripId/addons, over the same+ * TripAddonsService. The REST owner check is TripOwnerGuard; here the service+ * makes the same literal check, so a member or an admin who does not own the+ * trip is refused with the REST text.+ *+ * Neither tool has an addon gate: they are how a trip turns an addon on that+ * the instance has off, so they must be there whatever the instance says.+ */+@McpController()+export class TripAddonsMcp {+ constructor(+ private readonly tripAddons: TripAddonsService,+ private readonly trips: TripAccessService,+ ) {}++ @Tool({+ name: 'get_trip_addons',+ description:+ 'List the trip addons of one trip (lists, costs, files, collab, road trip, tours) and whether each applies to this trip. enabled is what applies here; instanceEnabled is the instance-wide setting; overridden is true when the trip owner chose enabled for this trip instead of following the instance. An addon that is off here has its tools refused for this trip, and its data is kept. Every member can read this.',+ inputSchema: { tripId: idSchema },+ annotations: TOOL_ANNOTATIONS_READONLY,+ access: { group: 'trips', mode: 'read' },+ })+ async list({ tripId }: { tripId: number }, ctx: McpContext) {+ const trip = await this.trips.findAccessible(tripId, ctx.userId);+ if (!trip) return noAccess();+ return ok({ tripId: trip.id, addons: await this.tripAddons.effectiveTripAddons(trip.id) });+ }++ @Tool({+ name: 'set_trip_addon',+ description:+ 'Switch one trip addon on or off for this trip only, whatever the instance-wide setting is, or pass enabled null to follow the instance setting again. Only the trip owner may do this. Turning an addon off hides it for every member of this trip and keeps its data; turning it on again brings everything back. addonId is an id from get_trip_addons, such as packing, budget, documents, collab, roadtrip or tours. Answers the trip addons as they stand afterwards.',+ inputSchema: {+ tripId: idSchema,+ addonId: tripAddonIdSchema,+ enabled: tripAddonUpdateRequestSchema.shape.enabled,+ },+ annotations: TOOL_ANNOTATIONS_WRITE,+ access: { group: 'trips', mode: 'write' },+ })+ async set(+ { tripId, addonId, enabled }: { tripId: number; addonId: string; enabled: boolean | null },+ ctx: McpContext,+ ) {+ const trip = await this.trips.findAccessible(tripId, ctx.userId);+ if (!trip) return noAccess();+ // The owner check and the addon check are the service's, so they read the same as on REST.+ const addons = await this.tripAddons.setTripOverride(trip.id, ctx.userId, addonId, enabled);+ return ok({ tripId: trip.id, addons });+ }+}diff --git a/server/src/nest/addons/trip-addons.service.ts b/server/src/nest/addons/trip-addons.service.tsnew file mode 100644index 000000000..70ce0ba4a--- /dev/null+++ b/server/src/nest/addons/trip-addons.service.ts@@ -0,0 +1,117 @@+import { Addons } from '../../db/entities/Addons.entity';+import { TripAddonOverrides } from '../../db/entities/TripAddonOverrides.entity';+import type { AddonsRepository } from '../../db/repositories/Addons.repository';+import type { TripAddonOverridesRepository } from '../../db/repositories/TripAddonOverrides.repository';+import { revokeUserSessions } from '../../mcp/sessionManager';+import { DomainError } from '../common/domain-error';+import { UnitOfWork } from '../database/unit-of-work';+import { RealtimeService } from '../realtime/realtime.service';+import { TripAccessService } from '../trip-membership/trip-access.service';+import { TripMembershipService } from '../trip-membership/trip-membership.service';+import { isTripAddonRow } from './addons.constants';+import { InjectRepository } from '@mikro-orm/nestjs';+import { Injectable } from '@nestjs/common';+import type { TripAddon } from '@trek/shared';++/** The refusal a member, an admin or anyone else but the owner gets for a change. */+export const TRIP_ADDON_OWNER_ONLY = 'Only the owner can change the addons of this trip';+/** The refusal for an id that names no trip addon (unknown, or a global or integration addon). */+export const TRIP_ADDON_NOT_FOUND = 'Addon not found';++/**+ * Whether a trip addon applies to one trip: the owner's choice for the trip+ * when there is one, else the instance switch.+ *+ * The trip owner may turn an addon on that the admin switched off, or off+ * where it is on everywhere else, and go back to the instance setting, which+ * drops the trip's row. Nothing of the addon's own data is touched, so a trip+ * that switches costs off and on again finds every expense where it was.+ *+ * Only the owner decides. The check is the literal `user_id` one of+ * TripOwnerGuard and not PermissionsService, which lets every admin through:+ * an admin who is no owner of the trip changes nothing here either.+ *+ * Whether an addon applies to a trip is AddonsService.isEnabledForTrip, the+ * one read every gate shares; this service owns the choice and its listing.+ */+@Injectable()+export class TripAddonsService {+ constructor(+ @InjectRepository(Addons) private readonly addons: AddonsRepository,+ @InjectRepository(TripAddonOverrides) private readonly overrides: TripAddonOverridesRepository,+ private readonly trips: TripAccessService,+ private readonly membership: TripMembershipService,+ private readonly realtime: RealtimeService,+ private readonly uow: UnitOfWork,+ ) {}++ /** Every trip addon as this trip sees it, in the admin's order. The caller has checked access. */+ async effectiveTripAddons(tripId: number): Promise<TripAddon[]> {+ const rows = (await this.addons.listAllOrdered()).filter(isTripAddonRow);+ const chosen = new Map((await this.overrides.listForTrip(tripId)).map((o) => [o.addon_id, o.enabled]));+ return rows.map((row) => {+ const instanceEnabled = !!row.enabled;+ const override = chosen.get(row.id);+ return {+ id: row.id,+ name: row.name,+ icon: row.icon ?? null,+ enabled: override ?? instanceEnabled,+ instanceEnabled,+ overridden: override !== undefined,+ };+ });+ }++ /**+ * The owner switches one trip addon for the trip: `true` on, `false` off,+ * `null` back to the instance setting. Answers the trip's whole list as it+ * stands after the change and sends it to every member of the trip, the+ * tab that made the change aside.+ *+ * A trip the caller cannot see is a 404 rather than a 403, so the answer+ * never confirms that the trip exists.+ */+ async setTripOverride(+ tripId: number,+ userId: number,+ addonId: string,+ enabled: boolean | null,+ socketId?: string,+ ): Promise<TripAddon[]> {+ const trip = await this.trips.findAccessible(tripId, userId);+ if (!trip) throw new DomainError(404, 'Trip not found');+ if (trip.user_id !== userId) throw new DomainError(403, TRIP_ADDON_OWNER_ONLY);+ const { addons, opened } = await this.uow.transactional(async () => {+ const addon = await this.addons.findById(addonId);+ if (!isTripAddonRow(addon)) throw new DomainError(404, TRIP_ADDON_NOT_FOUND);+ const wasOn = (await this.overrides.findForTrip(trip.id, addon.id)) ?? !!addon.enabled;+ if (enabled === null) await this.overrides.deleteOverride(trip.id, addon.id);+ else await this.overrides.upsertOverride(trip.id, addon.id, enabled);+ const after = await this.effectiveTripAddons(trip.id);+ const now = after.find((entry) => entry.id === addon.id);+ return { addons: after, opened: !wasOn && now !== undefined && now.enabled && !now.instanceEnabled };+ });+ this.realtime.broadcast(String(trip.id), 'tripAddons:changed', { addons }, socketId);+ if (opened) await this.reattachMcpSessions(trip.id);+ return addons;+ }++ /**+ * A trip switched on an addon the instance has off. A member's MCP session+ * attached its tools while the addon was off everywhere for them, and the+ * attach-time gate never runs again, so the session is ended and the client+ * starts a new one that offers the tools. Switching off needs nothing: the+ * per-call gate refuses for the trip at once.+ */+ private async reattachMcpSessions(tripId: number): Promise<void> {+ const ownerId = await this.membership.getOwnerId(tripId);+ const memberIds = await this.membership.listMemberUserIds(tripId);+ for (const userId of new Set([...(ownerId === null ? [] : [ownerId]), ...memberIds])) revokeUserSessions(userId);+ }++ /** A copied trip keeps the choices of the trip it came from. Runs inside the copy's transaction. */+ async copyOverrides(fromTripId: number, toTripId: number): Promise<void> {+ await this.overrides.copyForTrip(fromTripId, toTripId);+ }+}diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.tsindex 860a763ab..cda214fc9 100644--- a/server/src/nest/app.module.ts+++ b/server/src/nest/app.module.ts@@ -10,9 +10,11 @@ import {trekMcpValidateAccess,} from '../mcp/nest-mcp-policy';import mikroOrmConfig from '../mikro-orm.config';-import { McpModule } from '../nest-mcp';+import { combineToolGates, McpModule } from '../nest-mcp';import { AccommodationsModule } from './accommodations/accommodations.module';import { AddonsModule } from './addons/addons.module';+import { AddonsService } from './addons/addons.service';+import { trekTripAddonToolGate } from './addons/trip-addon-tool-gate';import { AdminModule } from './admin/admin.module';import { AiConnectionsModule } from './ai-connections/ai-connections.module';import { AirportsModule } from './airports/airports.module';@@ -105,6 +107,8 @@ import { TodoModule } from './todo/todo.module';import { ToursModule } from './tours/tours.module';import { TransitModule } from './transit/transit.module';import { TripInviteModule } from './trip-invite/trip-invite.module';+import { TripAccessService } from './trip-membership/trip-access.service';+import { TripMembershipModule } from './trip-membership/trip-membership.module';import { TripsModule } from './trips/trips.module';import { VacayModule } from './vacay/vacay.module';import { WalletPassModule } from './wallet-pass/wallet-pass.module';@@ -130,9 +134,16 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';McpModule.forRoot({accessPolicy: trekMcpAccessPolicy,validateAccess: trekMcpValidateAccess,+ // The demo write block first, then whether the addon of a tool applies+ // to the trip the call names (trekTripAddonToolGate).toolGate: {- inject: [DemoService],- useFactory: (demo: DemoService) => trekDemoToolGate((id) => demo.isDemoUserId(id)),+ imports: [AddonsModule, TripMembershipModule],+ inject: [DemoService, AddonsService, TripAccessService],+ useFactory: (demo: DemoService, addons: AddonsService, trips: TripAccessService) =>+ combineToolGates(+ trekDemoToolGate((id) => demo.isDemoUserId(id)),+ trekTripAddonToolGate(addons, trips),+ ),},errorMapper: trekMcpErrorMapper,inputMapper: trekMcpInputMapper,diff --git a/server/src/nest/assistant/assistant-attached-file.ts b/server/src/nest/assistant/assistant-attached-file.tsindex ddc807297..5de822699 100644--- a/server/src/nest/assistant/assistant-attached-file.ts+++ b/server/src/nest/assistant/assistant-attached-file.ts@@ -37,8 +37,8 @@ export interface AttachedFileReader {* (assistant-attach-answer.ts); no answer ends on the error then.*/readonly acknowledges: boolean;- /** Refuses a file nobody here can read, before a turn begins. */- ensureReadable(userId: number, file: Express.Multer.File): Promise<void>;+ /** Refuses a file nobody here can read for this trip, before a turn begins. */+ ensureReadable(userId: number, tripId: number, file: Express.Multer.File): Promise<void>;/** What the file holds, at most a step's worth. Persists nothing. */propose(userId: number, tripId: number, file: Express.Multer.File): Promise<FileRead>;}diff --git a/server/src/nest/assistant/assistant-attachment-tools.ts b/server/src/nest/assistant/assistant-attachment-tools.tsindex 2788a9659..c16f31dc9 100644--- a/server/src/nest/assistant/assistant-attachment-tools.ts+++ b/server/src/nest/assistant/assistant-attachment-tools.ts@@ -74,6 +74,8 @@ export interface AttachedTurn {attached: readonly AssistantAttachmentSummary[];/** The model and its host, as the consent card names them. */sentTo: string;+ /** Whether a file may go into the trip's Files: false while the trip has Documents off. */+ keeps: boolean;/** Reads a file the user let the model read already. */read(attachmentId: string): Promise<AgentToolRun>;}@@ -87,7 +89,8 @@ function attachmentOf(turn: AttachedTurn, args: ToolArgs): AssistantAttachmentSu/*** The turn's tools with the attached files' own: keep_attached_file where- * the thread holds an attachment, read_attached_file where one holds text.+ * the thread holds an attachment and the trip has Documents on,+ * read_attached_file where one holds text.* A file not yet shared is a write (held as the consent card), a shared one* a read; a keep is always held. A held call keeps the file's name (and* where its text goes) for the card, never the text.@@ -96,14 +99,18 @@ export function attachedPort(port: AgentToolPort, turn: AttachedTurn | null): Agif (!turn || turn.attached.length === 0) return port;const reads = turn.attached.some((row) => row.text_status === 'ok');return {- specs: () => [...port.specs(), ...(reads ? [READ_ATTACHED_FILE_SPEC] : []), KEEP_ATTACHED_FILE_SPEC],+ specs: () => [+ ...port.specs(),+ ...(reads ? [READ_ATTACHED_FILE_SPEC] : []),+ ...(turn.keeps ? [KEEP_ATTACHED_FILE_SPEC] : []),+ ],kindOf: (name, args) => {- if (name === KEEP_ATTACHED_FILE_TOOL) return 'write';+ if (name === KEEP_ATTACHED_FILE_TOOL && turn.keeps) return 'write';if (name !== READ_ATTACHED_FILE_TOOL || !reads) return port.kindOf(name, args);return attachmentOf(turn, args ?? {})?.shared_at ? 'read' : 'write';},pinArgs: (name, args) => {- if (name === KEEP_ATTACHED_FILE_TOOL) return keepArgs(turn, args);+ if (name === KEEP_ATTACHED_FILE_TOOL && turn.keeps) return keepArgs(turn, args);if (name !== READ_ATTACHED_FILE_TOOL || !reads) return port.pinArgs(name, args);const row = attachmentOf(turn, args);if (!row) return { error: NO_SUCH_ATTACHMENT };diff --git a/server/src/nest/assistant/assistant-attachments.service.ts b/server/src/nest/assistant/assistant-attachments.service.tsindex aefebc165..8430015f4 100644--- a/server/src/nest/assistant/assistant-attachments.service.ts+++ b/server/src/nest/assistant/assistant-attachments.service.ts@@ -183,9 +183,11 @@ export class AssistantAttachmentsService {const compact = connection.kind === 'custom';const { attached, texts } = await this.forTurn(threadId, userId, compact);const sentTo = `${connection.model} (${connection.host})`;+ // A thread's files all belong to its trip, so the first one names it.+ const keeps = attached.length > 0 && (await this.keeper.keepsOn(attached[0].trip_id));// Read while the turn streams, outside any request's context.const read = (id: string) => withRequestContext(this.orm, () => this.readShared(userId, threadId, id, compact));- return { texts, turn: { attached, sentTo, read } };+ return { texts, turn: { attached, sentTo, keeps, read } };}/** Whether a held change is one on an attachment, which `applyChange` runs. */diff --git a/server/src/nest/assistant/assistant-booking-import.service.ts b/server/src/nest/assistant/assistant-booking-import.service.tsindex de8a5bf28..130138550 100644--- a/server/src/nest/assistant/assistant-booking-import.service.ts+++ b/server/src/nest/assistant/assistant-booking-import.service.ts@@ -76,7 +76,7 @@ export class AssistantBookingImportService implements AttachedFileReader {* Refuses a file nobody here can read: no extractor and no AI parsing, or a* photo while the AI model reads no images (the extractor never reads one).*/- async ensureReadable(userId: number, file: Express.Multer.File): Promise<void> {+ async ensureReadable(userId: number, _tripId: number, file: Express.Multer.File): Promise<void> {const ai = await this.bookingImport.aiAvailable(userId);if (!ai && !this.bookingImport.isAvailable()) {throw aiRefusal('import_unavailable', 'Reading booking files is not available on this server');diff --git a/server/src/nest/assistant/assistant-keep-file.service.ts b/server/src/nest/assistant/assistant-keep-file.service.tsindex c78f11a6a..ff8d05d66 100644--- a/server/src/nest/assistant/assistant-keep-file.service.ts+++ b/server/src/nest/assistant/assistant-keep-file.service.ts@@ -1,5 +1,8 @@+import { ADDON_IDS } from '../../addons';import { AssistantAttachments } from '../../db/entities/AssistantAttachments.entity';import type { AssistantAttachmentsRepository } from '../../db/repositories/AssistantAttachments.repository';+import { addonOffMessage } from '../addons/addons.constants';+import { AddonsService } from '../addons/addons.service';import { logError } from '../audit/audit-log.logger';import { DemoService } from '../common/demo.service';import { UnitOfWork } from '../database/unit-of-work';@@ -70,6 +73,7 @@ export class AssistantKeepFileService {private readonly demo: DemoService,private readonly trips: TripAccessService,private readonly uow: UnitOfWork,+ private readonly addons: AddonsService,) {}/**@@ -122,10 +126,22 @@ export class AssistantKeepFileService {return { ok: true, value: { file: keptOf({ ...created, ...links }) } };}- /** Why the user may not keep this file here, or null: the demo, the trip, the Files rights. */+ /**+ * Whether files may go into the trip's Files at all: the trip's Documents+ * addon, which follows the instance unless the trip's owner chose for it.+ */+ keepsOn(tripId: number): Promise<boolean> {+ return this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS);+ }++ /**+ * Why the user may not keep this file here, or null: the demo, the trip, the+ * trip's Documents addon (answered as the Files routes answer it), the Files rights.+ */private async refusalOf(at: KeepAt, args: AssistantKeepFileArgs): Promise<string | null> {if (await this.demo.isDemoUserId(at.userId)) return NOT_ALLOWED;if (!(await this.trips.findAccessible(at.tripId, at.userId))) return NOT_ALLOWED;+ if (!(await this.keepsOn(at.tripId))) return addonOffMessage(ADDON_IDS.DOCUMENTS);if (!(await this.guards.hasTripPermission('file_upload', at.tripId, at.userId))) return NOT_ALLOWED;const linking = args.reservation_id ?? args.budget_item_id ?? args.place_id;if (linking && !(await this.guards.hasTripPermission('file_edit', at.tripId, at.userId))) {diff --git a/server/src/nest/assistant/assistant-share.service.ts b/server/src/nest/assistant/assistant-share.service.tsindex 253b0fa9b..b38978f82 100644--- a/server/src/nest/assistant/assistant-share.service.ts+++ b/server/src/nest/assistant/assistant-share.service.ts@@ -50,7 +50,7 @@ export class AssistantShareService {// The asking tab, which the route hands on; deliberately not skipped (see the class comment)._askingSocketId: string | undefined,) {- const collabOn = await this.addons.isAddonEnabled(ADDON_IDS.COLLAB);+ const collabOn = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.COLLAB);if (!collabOn || !(await this.addons.getCollabFeatures()).chat) throw aiRefusal('forbidden', 'Collab chat is off');if (!(await this.threads.findOwned(threadId, user.id, tripId))) {throw aiRefusal('not_found', 'Conversation not found');diff --git a/server/src/nest/assistant/assistant-tools.service.ts b/server/src/nest/assistant/assistant-tools.service.tsindex 59f6363f2..d964b309b 100644--- a/server/src/nest/assistant/assistant-tools.service.ts+++ b/server/src/nest/assistant/assistant-tools.service.ts@@ -592,10 +592,13 @@ export class AssistantToolsService implements OnApplicationBootstrap {traceEntry('mcp', `${info.kind} ${info.name} user=${userId} client=assistant`, () =>withRequestContext(this.orm, call),);+ // A trip chat is about its one trip: the addon gates ask that trip, so an+ // addon the owner switched off for it is never offered (see addon-gate.ts).+ const tripId = pin.arg === PINNED_ARG ? pin.id : undefined;await withRequestContext(this.orm, () =>this.registry.attach(server,- { userId, scopes: [...ASSISTANT_SCOPES], isStaticToken: false },+ { userId, scopes: [...ASSISTANT_SCOPES], isStaticToken: false, ...(tripId === undefined ? {} : { tripId }) },{ include: (kind, name) => kind === 'tool' && offer.include(name), around },),);diff --git a/server/src/nest/assistant/assistant-tour-file.service.ts b/server/src/nest/assistant/assistant-tour-file.service.tsindex 4fa459597..8693d9279 100644--- a/server/src/nest/assistant/assistant-tour-file.service.ts+++ b/server/src/nest/assistant/assistant-tour-file.service.ts@@ -47,9 +47,9 @@ export class AssistantTourFileService implements AttachedFileReader {private readonly addons: AddonsService,) {}- /** Refuses a route file where tours are off: nothing could take it in. */- async ensureReadable(_userId: number, _file: Express.Multer.File): Promise<void> {- if (!(await this.addons.isAddonEnabled(ADDON_IDS.TOURS))) {+ /** Refuses a route file where Tours is off for the trip: nothing could take it in. */+ async ensureReadable(_userId: number, tripId: number, _file: Express.Multer.File): Promise<void> {+ if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.TOURS))) {throw aiRefusal('import_unavailable', 'Tours are not enabled on this server');}}diff --git a/server/src/nest/assistant/assistant.service.ts b/server/src/nest/assistant/assistant.service.tsindex 40ce2a14f..93057a04d 100644--- a/server/src/nest/assistant/assistant.service.ts+++ b/server/src/nest/assistant/assistant.service.ts@@ -289,7 +289,7 @@ export class AssistantService {): Promise<void> {await this.admit(userId);const reader: AttachedFileReader = isAssistantTourFile(file.originalname) ? this.tourFiles : this.bookings;- await reader.ensureReadable(userId, file);+ await reader.ensureReadable(userId, tripId, file);const connection = await this.connections.resolveForUser(userId);await this.withinDailyLimit(userId, connection);await this.claimed(userId, channel.signal, async (signal) => {diff --git a/server/src/nest/booking-import/booking-import.service.ts b/server/src/nest/booking-import/booking-import.service.tsindex 089340dfe..a17cc007d 100644--- a/server/src/nest/booking-import/booking-import.service.ts+++ b/server/src/nest/booking-import/booking-import.service.ts@@ -6,6 +6,7 @@ import { ReservationsRepository } from '../../db/repositories/Reservations.reposimport { AddonsService } from '../addons/addons.service';import { BudgetService } from '../budget/budget.service';import { DomainError } from '../common/domain-error';+import { toRowId } from '../common/row-id';import { UnitOfWork } from '../database/unit-of-work';import { imageMimeType } from '../llm-parse/image-input';import { LlmParseService } from '../llm-parse/llm-parse.service';@@ -322,7 +323,8 @@ export class BookingImportService {tripId: string,item: BookingImportPreviewItem,): Promise<{ total_price: number; category: string; currency?: string | null; exchange_rate?: number } | undefined> {- if (!(await this.addons.isAddonEnabled(ADDON_IDS.BUDGET))) return undefined;+ const tid = toRowId(tripId);+ if (tid === null || !(await this.addons.isEnabledForTrip(tid, ADDON_IDS.BUDGET))) return undefined;const meta = item.metadata && typeof item.metadata === 'object' ? (item.metadata as Record<string, unknown>) : null;const price = meta && meta.price != null ? Number(meta.price) : Number.NaN;if (!Number.isFinite(price) || price <= 0) return undefined;diff --git a/server/src/nest/budget/budget.controller.ts b/server/src/nest/budget/budget.controller.tsindex ec9f5feb5..9727c55b4 100644--- a/server/src/nest/budget/budget.controller.ts+++ b/server/src/nest/budget/budget.controller.ts@@ -1,5 +1,8 @@+import { ADDON_IDS } from '../../addons';import type { TripAccess } from '../../db/repositories/Trips.repository';import type { User } from '../../types';+import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { toRowId } from '../common/row-id';@@ -55,8 +58,10 @@ import {@Controller('api/trips/:tripId/budget')// TripAccessGuard resolves :tripId and 404s a trip the user cannot reach; mutations// add @RequirePermission('budget_edit'), the same action string the service's canEdit-// passes, so the HTTP and MCP paths cannot demand different rights.-@UseGuards(JwtAuthGuard, TripAccessGuard)+// passes, so the HTTP and MCP paths cannot demand different rights. TripAddonGuard follows it:+// a trip that has Costs off answers 404 "Costs addon is not enabled", data kept.+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)+@RequireAddon(ADDON_IDS.BUDGET, 'Costs')export class BudgetController {constructor(private readonly budget: BudgetService,diff --git a/server/src/nest/budget/budget.mcp.ts b/server/src/nest/budget/budget.mcp.tsindex a8de6fdf1..1b1e93207 100644--- a/server/src/nest/budget/budget.mcp.ts+++ b/server/src/nest/budget/budget.mcp.ts@@ -16,7 +16,7 @@ import {errorResult,ok,} from '../../nest-mcp';-import { addonGate } from '../addons/addon-gate';+import { addonGate, addonOffResource } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { RuntimeEnvService } from '../app-config/runtime-env.service';import { DomainError } from '../common/domain-error';@@ -849,6 +849,7 @@ export class BudgetMcp {],};}+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.BUDGET))) return addonOffResource(uri, ADDON_IDS.BUDGET);const items = await this.budget.listBudgetItems(id);return {contents: [@@ -882,6 +883,7 @@ export class BudgetMcp {],};}+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.BUDGET))) return addonOffResource(uri, ADDON_IDS.BUDGET);// In the trip currency, each share at the rate its expense was booked at (#2525).const summary = await this.budget.perPersonSummary(id);return {@@ -916,6 +918,7 @@ export class BudgetMcp {],};}+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.BUDGET))) return addonOffResource(uri, ADDON_IDS.BUDGET);// Resolve the trip currency + live rates like get_settlement_summary — the// legacy resource called calculateSettlement(id) bare, silently netting a// non-EUR trip in EUR with no FX conversion.diff --git a/server/src/nest/budget/costs.rpc.ts b/server/src/nest/budget/costs.rpc.tsindex 9751e6a7a..9fcfde29c 100644--- a/server/src/nest/budget/costs.rpc.ts+++ b/server/src/nest/budget/costs.rpc.ts@@ -40,9 +40,10 @@ export class CostsRpc {@PluginMethod('costs.getByTrip', { permission: 'db:read:costs' })async getByTrip(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {- return await this.guards.tripRead(params, ctx, async () => {- await this.requireBudgetAddon();- return await this.budget.listBudgetItems(rowIdParam(params.tripId, 'tripId'));+ return await this.guards.tripRead(params, ctx, async (userId) => {+ const tripId = rowIdParam(params.tripId, 'tripId');+ await this.requireBudgetAddon(tripId, userId);+ return await this.budget.listBudgetItems(tripId);});}@@ -51,11 +52,14 @@ export class CostsRpc {// Cross-trip aggregate. The acting user is host-bound; a job or onLoad is refused// the same way tripRead refuses one.if (ctx.actingUserId === undefined) throw new ForbiddenResource('cost reads require an authenticated user context');- await this.requireBudgetAddon();// The leaf membership read, not TripsService.list: TripsModule imports this// one, so injecting TripsService here would close a cycle. Same id set,- // same newest-first order.- const tripIds = await this.membership.listAccessibleTripIds(ctx.actingUserId);+ // same newest-first order. A trip that has Costs off for itself is left out.+ const tripIds = await this.guards.tripsWithAddon(+ ADDON_IDS.BUDGET,+ 'costs',+ await this.membership.listAccessibleTripIds(ctx.actingUserId),+ );// Sequential, not Promise.all: the legacy flatMap read each trip's items one// after the other, in id order, and the output order is the contract here.const items: unknown[] = [];@@ -67,7 +71,7 @@ export class CostsRpc {async create(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {const tripId = rowIdParam(params.tripId, 'tripId');const actor = this.requireCostActor(ctx);- await this.requireBudgetAddon();+ await this.requireBudgetAddon(tripId, actor);const parsed = budgetCreateItemRequestSchema.safeParse(params.input);if (!parsed.success) throw new BadParams(`invalid cost: ${schemaMessage(parsed.error)}`);await this.requireCostEdit(tripId, actor);@@ -85,7 +89,7 @@ export class CostsRpc {const tripId = rowIdParam(params.tripId, 'tripId');const itemId = rowIdParam(params.itemId, 'itemId');const actor = this.requireCostActor(ctx);- await this.requireBudgetAddon();+ await this.requireBudgetAddon(tripId, actor);const parsed = budgetUpdateItemRequestSchema.safeParse(params.input);if (!parsed.success) throw new BadParams(`invalid cost: ${schemaMessage(parsed.error)}`);await this.requireCostEdit(tripId, actor);@@ -115,7 +119,7 @@ export class CostsRpc {const tripId = rowIdParam(params.tripId, 'tripId');const itemId = rowIdParam(params.itemId, 'itemId');const actor = this.requireCostActor(ctx);- await this.requireBudgetAddon();+ await this.requireBudgetAddon(tripId, actor);await this.requireCostEdit(tripId, actor);// Plan 4 Task 8b (U6) — same drop of itemId's String() wrapper as update above.if (!(await this.budget.remove(itemId, String(tripId)))) {@@ -133,8 +137,8 @@ export class CostsRpc {return ctx.actingUserId;}- private async requireBudgetAddon(): Promise<void> {- await this.guards.requireAddon(ADDON_IDS.BUDGET, 'costs');+ private async requireBudgetAddon(tripId: number, userId: number): Promise<void> {+ await this.guards.requireAddon(ADDON_IDS.BUDGET, 'costs', { tripId, userId });}/** Trip access plus budget_edit, with the cost-specific refusal message. */diff --git a/server/src/nest/collab/collab.controller.ts b/server/src/nest/collab/collab.controller.tsindex c046e4abd..c496f0924 100644--- a/server/src/nest/collab/collab.controller.ts+++ b/server/src/nest/collab/collab.controller.ts@@ -1,4 +1,9 @@+import { ADDON_IDS } from '../../addons';import type { User } from '../../types';+import { addonOffMessage } from '../addons/addons.constants';+import { AddonsService } from '../addons/addons.service';+import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { RuntimeEnvService } from '../app-config/runtime-env.service';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';@@ -128,13 +133,20 @@ export const collabNoteFileFilter: Options['fileFilter'] = (_req, file, cb) => {// route keeps its own check, because guards run before interceptors and a 404 sent// while the client is still streaming the multipart body destroys the socket (the// caller then sees ECONNRESET instead of the 404). Same as files.controller.ts.+//+// Collab is a trip addon: a trip it is off for answers 404 "Collab addon is not+// enabled" after the trip check, through TripAddonGuard beside TripAccessGuard+// and through requireTrip on the two upload routes. Notes, polls and messages+// stay where they are.@UseGuards(JwtAuthGuard)+@RequireAddon(ADDON_IDS.COLLAB, 'Collab')export class CollabController {constructor(private readonly collab: CollabService,private readonly storage: StorageService,// Whether DEMO_MODE is on, read on every upload: the demo account's are refused.private readonly env: RuntimeEnvService,+ private readonly addons: AddonsService,) {}private async requireTrip(tripId: string, user: User) {@@ -142,6 +154,9 @@ export class CollabController {if (!trip) {throw new HttpException({ error: 'Trip not found' }, 404);}+ if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.COLLAB))) {+ throw new HttpException({ error: addonOffMessage(ADDON_IDS.COLLAB) }, 404);+ }return trip;}@@ -155,14 +170,14 @@ export class CollabController {}// ── Notes ───────────────────────────────────────────────────────────────- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get('notes')@ResponseContract(collabNotesResponseSchema)async listNotes(@CurrentUser() user: User, @Param('tripId') tripId: string) {return { notes: await this.collab.listNotes(tripId) };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Post('notes')@ResponseContract(collabNoteResponseSchema)@@ -180,7 +195,7 @@ export class CollabController {return { note };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Put('notes/:id')@ResponseContract(collabNoteResponseSchema)@@ -206,7 +221,7 @@ export class CollabController {return { note };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Delete('notes/:id')@ResponseContract(successResponseSchema)@@ -281,7 +296,7 @@ export class CollabController {return result;}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Delete('notes/:id/files/:fileId')@ResponseContract(successResponseSchema)@@ -305,14 +320,14 @@ export class CollabController {}// ── Shared links ────────────────────────────────────────────────────────- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get('links')@ResponseContract(collabLinksResponseSchema)async listLinks(@CurrentUser() user: User, @Param('tripId') tripId: string) {return { links: await this.collab.listLinks(tripId) };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Post('links')@ResponseContract(collabLinkResponseSchema)@@ -331,7 +346,7 @@ export class CollabController {return { link };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Put('links/:id')@ResponseContract(collabLinkResponseSchema)@@ -352,7 +367,7 @@ export class CollabController {return { link };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Delete('links/:id')@ResponseContract(successResponseSchema)@@ -368,14 +383,14 @@ export class CollabController {}// ── Polls ───────────────────────────────────────────────────────────────- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get('polls')@ResponseContract(collabPollsResponseSchema)async listPolls(@CurrentUser() user: User, @Param('tripId') tripId: string) {return { polls: await this.collab.listPolls(tripId) };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Post('polls')@ResponseContract(collabPollResponseSchema)@@ -396,7 +411,7 @@ export class CollabController {return { poll };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Post('polls/:id/vote')@HttpCode(200)@@ -416,7 +431,7 @@ export class CollabController {return { poll: result.poll };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Put('polls/:id/close')@ResponseContract(collabPollResponseSchema)@@ -434,7 +449,7 @@ export class CollabController {return { poll };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Delete('polls/:id')@ResponseContract(successResponseSchema)@@ -452,7 +467,7 @@ export class CollabController {}// ── Messages ────────────────────────────────────────────────────────────- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get('messages')@ResponseContract(collabMessagesResponseSchema)async listMessages(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('before') before?: string) {@@ -559,7 +574,7 @@ export class CollabController {return { message: result.message };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Post('messages/:id/react')@HttpCode(200)@@ -584,7 +599,7 @@ export class CollabController {return { reactions: result.reactions };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@RequirePermission('collab_edit')@Delete('messages/:id')@ResponseContract(successResponseSchema)@@ -614,7 +629,7 @@ export class CollabController {// trip whose owner has narrowed that right, for people who may still read the// chat. What keeps the fetcher from being a free outbound proxy is the budget// inside the service, not a write permission.- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get('link-preview')@ResponseContract(collabLinkPreviewResponseSchema)async linkPreview(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('url') url?: string) {diff --git a/server/src/nest/collab/collab.mcp.ts b/server/src/nest/collab/collab.mcp.tsindex 2c09dbaf3..e3d27d1dd 100644--- a/server/src/nest/collab/collab.mcp.ts+++ b/server/src/nest/collab/collab.mcp.ts@@ -12,7 +12,7 @@ import {errorResult,ok,} from '../../nest-mcp';-import { collabFeatureGate } from '../addons/addon-gate';+import { addonOffResource, collabFeatureGate } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { uriRowId } from '../common/row-id';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';@@ -551,6 +551,7 @@ export class CollabMcp {async tripCollabNotesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {const id = uriRowId(tripId);if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href);+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.COLLAB))) return addonOffResource(uri, ADDON_IDS.COLLAB);const notes = await this.collab.listNotes(id);return jsonContent(uri.href, notes);}@@ -566,6 +567,7 @@ export class CollabMcp {async tripCollabPollsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {const id = uriRowId(tripId);if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href);+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.COLLAB))) return addonOffResource(uri, ADDON_IDS.COLLAB);const polls = await this.collab.listPolls(id);return jsonContent(uri.href, polls);}@@ -581,6 +583,7 @@ export class CollabMcp {async tripCollabMessagesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {const id = uriRowId(tripId);if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href);+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.COLLAB))) return addonOffResource(uri, ADDON_IDS.COLLAB);const messages = await this.collab.listMessages(id);return jsonContent(uri.href, messages);}diff --git a/server/src/nest/collab/collab.rpc.ts b/server/src/nest/collab/collab.rpc.tsindex 01fd9f3a7..d525f7ae3 100644--- a/server/src/nest/collab/collab.rpc.ts+++ b/server/src/nest/collab/collab.rpc.ts@@ -31,24 +31,24 @@ export class CollabRpc {@PluginMethod('collab.listNotes', { permission: 'db:read:collab' })listNotes(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {- return this.guards.tripRead(params, ctx, async () => {- await this.requireCollabAddon();+ return this.guards.tripRead(params, ctx, async (userId) => {+ await this.requireCollabAddon(rowIdParam(params.tripId, 'tripId'), userId);return (await this.collab.listNotes(rowIdParam(params.tripId, 'tripId'))) as unknown[];});}@PluginMethod('collab.listPolls', { permission: 'db:read:collab' })listPolls(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {- return this.guards.tripRead(params, ctx, async () => {- await this.requireCollabAddon();+ return this.guards.tripRead(params, ctx, async (userId) => {+ await this.requireCollabAddon(rowIdParam(params.tripId, 'tripId'), userId);return (await this.collab.listPolls(rowIdParam(params.tripId, 'tripId'))) as unknown[];});}@PluginMethod('collab.listMessages', { permission: 'db:read:collab' })listMessages(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {- return this.guards.tripRead(params, ctx, async () => {- await this.requireCollabAddon();+ return this.guards.tripRead(params, ctx, async (userId) => {+ await this.requireCollabAddon(rowIdParam(params.tripId, 'tripId'), userId);const before = params.before != null ? rowIdParam(params.before, 'before') : undefined;return (await this.collab.listMessages(rowIdParam(params.tripId, 'tripId'), before)) as unknown[];});@@ -61,7 +61,7 @@ export class CollabRpc {const input = asPayload(params.input);if (typeof input.title !== 'string' || input.title.trim() === '') throw new BadParams('note title is required');await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);- await this.requireCollabAddon();+ await this.requireCollabAddon(tripId, actor);const note = await this.collab.createNote(String(tripId), actor, input as never);this.realtime.broadcast(tripId, 'collab:note:created', { note }, undefined);return note;@@ -77,7 +77,7 @@ export class CollabRpc {if (!Array.isArray(input.options) || input.options.length < 2)throw new BadParams('a poll needs at least two options');await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);- await this.requireCollabAddon();+ await this.requireCollabAddon(tripId, actor);const poll = await this.collab.createPoll(String(tripId), actor, input as never);this.realtime.broadcast(tripId, 'collab:poll:created', { poll }, undefined);return poll;@@ -88,7 +88,7 @@ export class CollabRpc {const tripId = rowIdParam(params.tripId, 'tripId');const actor = this.guards.requireActor(ctx, 'collab poll');await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);- await this.requireCollabAddon();+ await this.requireCollabAddon(tripId, actor);const result = await this.collab.votePoll(String(tripId),String(rowIdParam(params.pollId, 'pollId')),@@ -109,7 +109,7 @@ export class CollabRpc {throw new BadParams('message text is required (max 4000 chars)');}await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);- await this.requireCollabAddon();+ await this.requireCollabAddon(tripId, actor);// Left out or null is no reply; anything else must be a message id.const replyTo = optionalRowIdParam(params.replyTo ?? undefined, 'replyTo') ?? null;const result = await this.collab.createMessage(String(tripId), actor, params.text, replyTo);@@ -118,7 +118,8 @@ export class CollabRpc {return result.message;}- private async requireCollabAddon(): Promise<void> {- await this.guards.requireAddon(ADDON_IDS.COLLAB, 'collab');+ /** Collab has to be on for the trip, the owner's choice or else the instance switch. */+ private async requireCollabAddon(tripId: number, userId: number): Promise<void> {+ await this.guards.requireAddon(ADDON_IDS.COLLAB, 'collab', { tripId, userId });}}diff --git a/server/src/nest/doc-sync/doc-sync.controller.ts b/server/src/nest/doc-sync/doc-sync.controller.tsindex 600316afc..c2fcbfe68 100644--- a/server/src/nest/doc-sync/doc-sync.controller.ts+++ b/server/src/nest/doc-sync/doc-sync.controller.ts@@ -2,6 +2,7 @@ import { ADDON_IDS } from '../../addons';import type { User } from '../../types';import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { rowId } from '../common/row-id.pipe';@@ -64,7 +65,10 @@ import type { Request } from 'express';* where their documents are going.*/@Controller('api/trips/:tripId/docsync')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+// AddonGuard first, on the instance switch alone: the document providers stay bound to it, so a trip+// cannot open doc-sync while the instance has Documents off. TripAddonGuard then refuses a trip+// whose owner switched Documents off for it.+@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.DOCUMENTS, 'Documents')export class DocSyncController {private readonly logger = new Logger(DocSyncController.name);diff --git a/server/src/nest/doc-sync/doc-sync.mcp.ts b/server/src/nest/doc-sync/doc-sync.mcp.tsindex ed65b42dd..014649948 100644--- a/server/src/nest/doc-sync/doc-sync.mcp.ts+++ b/server/src/nest/doc-sync/doc-sync.mcp.ts@@ -9,7 +9,7 @@ import {errorResult,ok,} from '../../nest-mcp';-import { addonGate } from '../addons/addon-gate';+import { instanceAddonGate } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { FilesService } from '../files/files.service';import { DocSyncConfigService } from './doc-sync-config.service';@@ -19,7 +19,9 @@ import { idSchema } from '@trek/shared';import { z } from 'zod';-const documentsAddonOn = addonGate(ADDON_IDS.DOCUMENTS);+// The document providers stay bound to the instance's Documents switch, so these tools follow it alone;+// each call still needs Documents on for the trip it names.+const documentsAddonOn = instanceAddonGate(ADDON_IDS.DOCUMENTS);/*** The MCP half of document sync, mirroring /api/trips/:tripId/docsync.diff --git a/server/src/nest/doc-sync/doc-sync.service.ts b/server/src/nest/doc-sync/doc-sync.service.tsindex ddc99e572..1eeb0c680 100644--- a/server/src/nest/doc-sync/doc-sync.service.ts+++ b/server/src/nest/doc-sync/doc-sync.service.ts@@ -129,16 +129,16 @@ export class DocSyncService {}/**- * Whether an admin has closed the door on this binding: the Documents addon- * is off, or the provider it runs against is.+ * Whether the door on this binding is closed: Documents off for the instance+ * or for the binding's trip, or its provider off (providers follow the instance).*- * A kill switch, not a failure. Nothing about the binding is written while it- * is off, not its state and not its documents' attempt counters, so it- * resumes exactly where it stopped once the switch is back on. Public because- * a manual run has to refuse before it un-shelves anything.+ * A kill switch, not a failure: nothing about the binding is written while it is off+ * (not its state, not its documents' attempt counters), so it resumes where it stopped.+ * Public because a manual run has to refuse before it un-shelves anything.*/- async isSwitchedOff(link: Pick<LinkRow, 'provider_id'>): Promise<boolean> {+ async isSwitchedOff(link: Pick<LinkRow, 'provider_id' | 'trip_id'>): Promise<boolean> {if (!(await this.addons.isAddonEnabled(ADDON_IDS.DOCUMENTS))) return true;+ if (!(await this.addons.isEnabledForTrip(link.trip_id, ADDON_IDS.DOCUMENTS))) return true;return !(await this.config.enabledProviderIds()).includes(link.provider_id);}diff --git a/server/src/nest/files/files-download.controller.ts b/server/src/nest/files/files-download.controller.tsindex 965ca5be8..9b7084596 100644--- a/server/src/nest/files/files-download.controller.ts+++ b/server/src/nest/files/files-download.controller.ts@@ -1,3 +1,6 @@+import { ADDON_IDS } from '../../addons';+import { addonOffMessage } from '../addons/addons.constants';+import { AddonsService } from '../addons/addons.service';import { Public } from '../auth-core/public.decorator';import { contentDisposition } from '../common/content-disposition';import { StorageService } from '../storage/storage.service';@@ -15,7 +18,9 @@ import path from 'path';* the legacy authenticateDownload helper. Byte-identical to the legacy route:* 401 token, 404 trip/file, .pkpass served inline for Wallet. Bytes come from* storage.sendToResponse, whose local branch is the root-relative res.sendFile- * form this route needs under the ExpressAdapter.+ * form this route needs under the ExpressAdapter. A trip that has Documents off+ * answers 404 "Documents addon is not enabled" after the trip check, like every+ * other files route.*/@Public('authenticates itself: the download link carries a short-lived ?token the client mints')@Controller('api/trips/:tripId/files')@@ -23,6 +28,7 @@ export class FilesDownloadController {constructor(private readonly files: FilesService,private readonly storage: StorageService,+ private readonly addons: AddonsService,) {}// response-contract-exempt: streams the file through @Res(), there is no JSON body to check.@@ -39,6 +45,9 @@ export class FilesDownloadController {if (!trip) {throw new HttpException({ error: 'Trip not found' }, 404);}+ if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS))) {+ throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);+ }const file = await this.files.getFileById(id, tripId);if (!file) {diff --git a/server/src/nest/files/files.controller.ts b/server/src/nest/files/files.controller.tsindex 905b346d6..dbcc476d5 100644--- a/server/src/nest/files/files.controller.ts+++ b/server/src/nest/files/files.controller.ts@@ -1,5 +1,10 @@+import { ADDON_IDS } from '../../addons';import type { TripAccess } from '../../db/repositories/Trips.repository';import type { User } from '../../types';+import { addonOffMessage } from '../addons/addons.constants';+import { AddonsService } from '../addons/addons.service';+import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { RuntimeEnvService } from '../app-config/runtime-env.service';import { logError } from '../audit/audit-log.logger';import { CurrentUser } from '../auth-core/current-user.decorator';@@ -116,12 +121,18 @@ export function filesUploadFileFilter(allowedTypes: AllowedFileTypesService): Op// socket destroyed, so the caller sees ECONNRESET instead of the 404. Refusing after// the body has been read costs the bandwidth but keeps the answer readable, which is// the behaviour every client already handles.+//+// Documents is a trip addon: a trip it is off for answers 404 "Documents addon is+// not enabled" on every route, after the trip check, with TripAddonGuard beside+// TripAccessGuard and inline in the upload. The files themselves stay.@UseGuards(JwtAuthGuard)+@RequireAddon(ADDON_IDS.DOCUMENTS, 'Documents')export class FilesController {constructor(private readonly files: FilesService,private readonly env: RuntimeEnvService,private readonly storage: StorageService,+ private readonly addons: AddonsService,) {}// A file may only point at reservations/assignments/places/budget_items from its own trip.@@ -141,7 +152,7 @@ export class FilesController {}}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get()@ResponseContract(tripFilesResponseSchema)async list(@@ -180,6 +191,9 @@ export class FilesController {if (!trip) {throw new HttpException({ error: 'Trip not found' }, 404);}+ if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS))) {+ throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);+ }// Inline rather than DemoWriteGuard: the 404 above has to come first, so a demo// user still cannot learn which trips exist.if (isDemoWriteBlocked(this.env, user.email)) {@@ -231,7 +245,7 @@ export class FilesController {return { file: created };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Put(':id')@ResponseContract(tripFileResponseSchema)async update(@@ -264,7 +278,7 @@ export class FilesController {return { file: updated };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Patch(':id/star')@ResponseContract(tripFileResponseSchema)async star(@@ -286,7 +300,7 @@ export class FilesController {return { file: updated };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Delete('trash/empty')@ResponseContract(fileTrashEmptyResponseSchema)async emptyTrash(@CurrentUser() user: User, @Trip() trip: TripAccess, @Param('tripId') tripId: string) {@@ -297,7 +311,7 @@ export class FilesController {return { success: true, deleted };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Delete(':id/permanent')@ResponseContract(successResponseSchema)async permanent(@@ -319,7 +333,7 @@ export class FilesController {return { success: true };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Delete(':id')@ResponseContract(successResponseSchema)async remove(@@ -341,7 +355,7 @@ export class FilesController {return { success: true };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Post(':id/restore')@HttpCode(200) // Express answers restore with res.json (200), not the POST-default 201.@ResponseContract(tripFileResponseSchema)@@ -364,7 +378,7 @@ export class FilesController {return { file: restored };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Post(':id/link')@HttpCode(200) // Express answers link with res.json (200).@ResponseContract(fileLinkCreateResponseSchema)@@ -402,7 +416,7 @@ export class FilesController {return { success: true, links };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Delete(':id/link/:linkId')@ResponseContract(successResponseSchema)async unlink(@@ -427,7 +441,7 @@ export class FilesController {return { success: true };}- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)@Get(':id/links')@ResponseContract(fileLinksResponseSchema)async links(diff --git a/server/src/nest/files/files.mcp.ts b/server/src/nest/files/files.mcp.tsindex 6534c1417..8365f87df 100644--- a/server/src/nest/files/files.mcp.ts+++ b/server/src/nest/files/files.mcp.ts@@ -1,3 +1,4 @@+import { ADDON_IDS } from '../../addons';import { noAccess, permissionDenied } from '../../mcp/tools/_shared';import {McpController,@@ -9,6 +10,8 @@ import {errorResult,ok,} from '../../nest-mcp';+import { addonGate } from '../addons/addon-gate';+import { AddonsService } from '../addons/addons.service';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';import { contentTypeFor } from '../storage/content-type';import { AllowedFileTypesService } from './allowed-file-types.service';@@ -21,6 +24,12 @@ import { z } from 'zod';const CONTENT_MAX_MB = Math.round(FILE_CONTENT_MAX / (1024 * 1024));+/**+ * The trip file manager is the Documents addon: its tools are offered while it is on for the+ * instance or a trip of the caller, and each call needs it on for the trip it names (the host's+ * tool gate), as every files route answers 404 "Documents addon is not enabled" otherwise.+ */+const documentsAddonOn = addonGate(ADDON_IDS.DOCUMENTS);/*** The upload tool's cap: the same 10 MB a read hands back, or the operator's* upload limit when that is lower. The bytes travel base64 inside one JSON-RPC@@ -70,6 +79,7 @@ export class FilesMcp {private readonly files: FilesService,private readonly guards: McpToolGuardsService,private readonly allowedTypes: AllowedFileTypesService,+ readonly addons: AddonsService,) {}@Tool({@@ -82,6 +92,7 @@ export class FilesMcp {},annotations: TOOL_ANNOTATIONS_READONLY,access: { group: 'files', mode: 'read' },+ when: documentsAddonOn,})async listTripFiles({ tripId, trash }: { tripId: number; trash?: boolean }, ctx: McpContext) {if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();@@ -100,6 +111,7 @@ export class FilesMcp {// passport scan are different privileges, and the plugin host draws the same// line (db:read:files vs db:read:files:content).access: { group: 'files', mode: 'content' },+ when: documentsAddonOn,})async readTripFile({ tripId, fileId }: { tripId: number; fileId: number }, ctx: McpContext) {if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();@@ -144,6 +156,7 @@ export class FilesMcp {},annotations: TOOL_ANNOTATIONS_WRITE,access: { group: 'files', mode: 'write' },+ when: documentsAddonOn,})async uploadTripFile({@@ -210,6 +223,7 @@ export class FilesMcp {},annotations: TOOL_ANNOTATIONS_WRITE,access: { group: 'files', mode: 'write' },+ when: documentsAddonOn,})async updateTripFile({ tripId, fileId, ...fields }: { tripId: number; fileId: number } & FileUpdateRequest,@@ -252,6 +266,7 @@ export class FilesMcp {},annotations: TOOL_ANNOTATIONS_WRITE,access: { group: 'files', mode: 'write' },+ when: documentsAddonOn,})async linkTripFile({ tripId, fileId, ...targets }: { tripId: number; fileId: number } & FileLinkRequest,@@ -283,6 +298,7 @@ export class FilesMcp {},annotations: TOOL_ANNOTATIONS_DELETE,access: { group: 'files', mode: 'write' },+ when: documentsAddonOn,})async unlinkTripFile({ tripId, fileId, linkId }: { tripId: number; fileId: number; linkId: number },@@ -308,6 +324,7 @@ export class FilesMcp {},annotations: TOOL_ANNOTATIONS_READONLY,access: { group: 'files', mode: 'read' },+ when: documentsAddonOn,})async listTripFileLinks({ tripId, fileId }: { tripId: number; fileId: number }, ctx: McpContext) {if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();diff --git a/server/src/nest/files/files.module.ts b/server/src/nest/files/files.module.tsindex 7bfec61e1..c97887c6d 100644--- a/server/src/nest/files/files.module.ts+++ b/server/src/nest/files/files.module.ts@@ -7,6 +7,7 @@ import { TripFiles } from '../../db/entities/TripFiles.entity';import { Trips } from '../../db/entities/Trips.entity';import { Users } from '../../db/entities/Users.entity';import { PluginGuardsModule } from '../../nest-rpc/plugin-guards.module';+import { AddonsModule } from '../addons/addons.module';import { AppConfigModule } from '../app-config/app-config.module';import { EphemeralTokenModule } from '../auth-core/ephemeral-token.module';import { McpSharedModule } from '../mcp-shared/mcp-shared.module';@@ -62,6 +63,8 @@ import { MulterModule } from '@nestjs/platform-express';RealtimeModule,PluginGuardsModule,McpSharedModule,+ // Documents is a trip addon; the routes ask whether it applies to their trip.+ AddonsModule,// FilesMcp's upload tool checks the same extension list as the multipart filter.AllowedFileTypesModule,],diff --git a/server/src/nest/files/files.rpc.ts b/server/src/nest/files/files.rpc.tsindex e669b39e1..7dbd776a7 100644--- a/server/src/nest/files/files.rpc.ts+++ b/server/src/nest/files/files.rpc.ts@@ -1,7 +1,8 @@+import { ADDON_IDS } from '../../addons';import { readEnv } from '../../app-config';import { Users } from '../../db/entities/Users.entity';import type { UsersRepository } from '../../db/repositories/Users.repository';-import { PluginGuards } from '../../nest-rpc/plugin-guards.service';+import { PluginGuards, type RpcAddon } from '../../nest-rpc/plugin-guards.service';import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors';import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators';import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';@@ -33,6 +34,9 @@ type CreateInput = {reservation_id?: number;};+/** Every read and write here belongs to the documents addon and follows it per trip. */+const FILES_ADDON: RpcAddon = { addonId: ADDON_IDS.DOCUMENTS, noun: 'documents' };+/*** The file surface a plugin may reach (#plugins).*@@ -59,15 +63,21 @@ export class FilesRpc {@PluginMethod('files.list', { permission: 'db:read:files' })async list(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {// Trash excluded, the same view the files tab shows.- return await this.guards.tripRead(params, ctx, async () =>- this.files.listFiles(rowIdParam(params.tripId, 'tripId'), false),+ return await this.guards.tripRead(+ params,+ ctx,+ async () => this.files.listFiles(rowIdParam(params.tripId, 'tripId'), false),+ FILES_ADDON,);}@PluginMethod('files.getContent', { permission: 'db:read:files:content' })getContent(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {- return this.guards.tripRead(params, ctx, () =>- this.readContent(rowIdParam(params.tripId, 'tripId'), rowIdParam(params.fileId, 'fileId')),+ return this.guards.tripRead(+ params,+ ctx,+ () => this.readContent(rowIdParam(params.tripId, 'tripId'), rowIdParam(params.fileId, 'fileId')),+ FILES_ADDON,);}@@ -106,7 +116,7 @@ export class FilesRpc {if (input.content_base64.length > 14 * 1024 * 1024) {throw new BadParams('file exceeds the 10MB plugin upload cap');}- await this.guards.requireTripEdit(tripId, actor, UPLOAD_ACTION);+ await this.guards.requireTripEdit(tripId, actor, UPLOAD_ACTION, FILES_ADDON);return this.writeFile(tripId, input as unknown as CreateInput, actor);}@@ -158,7 +168,7 @@ export class FilesRpc {const tripId = rowIdParam(params.tripId, 'tripId');const fileId = rowIdParam(params.fileId, 'fileId');const actor = this.guards.requireActor(ctx, 'file link');- await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION, FILES_ADDON);if (!(await this.files.getFileById(fileId, tripId)))throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);const opts = asPayload(params.opts) as { reservation_id?: number; assignment_id?: number; place_id?: number };@@ -177,7 +187,7 @@ export class FilesRpc {const tripId = rowIdParam(params.tripId, 'tripId');const fileId = rowIdParam(params.fileId, 'fileId');const actor = this.guards.requireActor(ctx, 'file');- await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION, FILES_ADDON);const current = await this.files.getFileById(fileId, tripId);if (!current) throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);const input = asPayload(params.input) as {@@ -206,7 +216,7 @@ export class FilesRpc {const tripId = rowIdParam(params.tripId, 'tripId');const fileId = rowIdParam(params.fileId, 'fileId');const actor = this.guards.requireActor(ctx, 'file');- await this.guards.requireTripEdit(tripId, actor, DELETE_ACTION);+ await this.guards.requireTripEdit(tripId, actor, DELETE_ACTION, FILES_ADDON);if (!(await this.files.getFileById(fileId, tripId)))throw new ForbiddenResource(`no file ${fileId} on trip ${tripId}`);await this.files.softDeleteFile(fileId);diff --git a/server/src/nest/mail-ingest/mail-ingest-apply.service.ts b/server/src/nest/mail-ingest/mail-ingest-apply.service.tsindex 40a265ace..b4a92eb3c 100644--- a/server/src/nest/mail-ingest/mail-ingest-apply.service.ts+++ b/server/src/nest/mail-ingest/mail-ingest-apply.service.ts@@ -176,7 +176,7 @@ export class MailIngestApplyService {mail: WalkedMail,userId: number,): Promise<{ fileIds: number[]; error: string | null }> {- if (!(await this.addons.isAddonEnabled(ADDON_IDS.DOCUMENTS))) return { fileIds: [], error: null };+ if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS))) return { fileIds: [], error: null };const allowed = await this.settings.allowedFileTypes();const kept = mail.attachments.filter((file) => isUploadTypeAllowed(file.fileName, file.mimeType, allowed));const uploads = kept.length@@ -298,7 +298,7 @@ export class MailIngestApplyService {}/**- * The cost a price becomes: only with the costs addon on, a price read to+ * The cost a price becomes: only with the costs addon on for the trip, a price read to* the cent and, in a foreign currency, a rate frozen now. Undefined where* there is no cost to write, null where the mail names a price that cannot* be written without guessing (the field is marked instead).@@ -306,7 +306,7 @@ export class MailIngestApplyService {private async costOf(item: BookingImportPreviewItem, trip: TripOption): Promise<CostEntry | null> {const meta = item.metadata ?? {};if (meta.price == null || meta.price === '') return undefined;- if (!(await this.addons.isAddonEnabled(ADDON_IDS.BUDGET))) return undefined;+ if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.BUDGET))) return undefined;const currency = typeof meta.priceCurrency === 'string' ? meta.priceCurrency.toUpperCase() : null;const minor = parsePriceMinor(meta.price, currency ?? trip.currency);if (minor === null || minor <= 0) return null;diff --git a/server/src/nest/notifications/notification-preferences.service.ts b/server/src/nest/notifications/notification-preferences.service.tsindex 0f59373c8..591c5619e 100644--- a/server/src/nest/notifications/notification-preferences.service.ts+++ b/server/src/nest/notifications/notification-preferences.service.ts@@ -4,6 +4,7 @@ import { AppSettings } from '../../db/entities/AppSettings.entity';import { NotificationChannelPreferences } from '../../db/entities/NotificationChannelPreferences.entity';import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';import type { NotificationChannelPreferencesRepository } from '../../db/repositories/NotificationChannelPreferences.repository';+import { TRIP_ADDON_IDS } from '../addons/addons.constants';import { AddonsService } from '../addons/addons.service';import { readAppSetting, resolveAppSetting } from '../common/app-settings.registry';import { UnitOfWork } from '../database/unit-of-work';@@ -93,14 +94,20 @@ export class NotificationPreferencesService {* The events the matrices list: what the install can raise at all* (offeredEventTypes), narrowed to the features that are switched on. A row* for vacation sharing on an install without Vacay, or for Synology without- * the provider, is a switch that never does anything.+ * the provider, is a switch that never does anything. For one user's own+ * matrix a trip addon counts as on while it is on in any of their trips, so a+ * trip that switched Collab on lists its chat row although the instance has it off.*/- private async listedEventTypes(): Promise<NotifEventType[]> {+ private async listedEventTypes(userId?: number): Promise<NotifEventType[]> {const photoProviders = await this.addons.enabledPhotoProviderIds();+ const read = (id: string): Promise<boolean> =>+ userId !== undefined && TRIP_ADDON_IDS.has(id)+ ? this.addons.isEnabledForUserAnywhere(userId, id)+ : this.addons.isAddonEnabled(id);// One read per addon, shared by the events that hang off it.const addonOn = new Map<string, Promise<boolean>>();const on = (id: string): Promise<boolean> => {- if (!addonOn.has(id)) addonOn.set(id, this.addons.isAddonEnabled(id));+ if (!addonOn.has(id)) addonOn.set(id, read(id));return addonOn.get(id) as Promise<boolean>;};const events = offeredEventTypes();@@ -374,8 +381,8 @@ export class NotificationPreferencesService {// Filter event types by scopeconst event_types =scope === 'admin'- ? (await this.listedEventTypes()).filter((e) => ADMIN_SCOPED_EVENTS.has(e))- : (await this.listedEventTypes()).filter((e) => !ADMIN_SCOPED_EVENTS.has(e));+ ? (await this.listedEventTypes(userId)).filter((e) => ADMIN_SCOPED_EVENTS.has(e))+ : (await this.listedEventTypes(userId)).filter((e) => !ADMIN_SCOPED_EVENTS.has(e));return {preferences,diff --git a/server/src/nest/notifications/reminder-jobs.service.ts b/server/src/nest/notifications/reminder-jobs.service.tsindex 19c535e42..24bfee09f 100644--- a/server/src/nest/notifications/reminder-jobs.service.ts+++ b/server/src/nest/notifications/reminder-jobs.service.ts@@ -1,9 +1,11 @@+import { ADDON_IDS } from '../../addons';import { AppSettings } from '../../db/entities/AppSettings.entity';import { TodoItems } from '../../db/entities/TodoItems.entity';import { Trips } from '../../db/entities/Trips.entity';import { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';import { TodoItemsRepository } from '../../db/repositories/TodoItems.repository';import { TripsRepository } from '../../db/repositories/Trips.repository';+import { AddonsService } from '../addons/addons.service';import { logInfo, logError, logWarn } from '../audit/audit-log.logger';import { readAppSetting } from '../common/app-settings.registry';import { appClock } from '../common/timezoneService';@@ -52,6 +54,7 @@ export class ReminderJobsService implements OnApplicationBootstrap {@InjectRepository(TodoItems) private readonly todoItems: TodoItemsRepository,private readonly notifications: NotificationsService,private readonly registrar: CronRegistrarService,+ private readonly addons: AddonsService,) {}async onApplicationBootstrap(): Promise<void> {@@ -180,7 +183,12 @@ export class ReminderJobsService implements OnApplicationBootstrap {const todayDate = appClock().date;const cutoffDate = addIsoDays(todayDate, TODO_REMINDER_LEAD_DAYS);- const todos = await this.todoItems.listDueForReminder(todayDate, cutoffDate);+ // A trip that has Lists off shows no todos, so it is reminded of none; its todos stay unclaimed.+ const due = await this.todoItems.listDueForReminder(todayDate, cutoffDate);+ const tripIds = [...new Set(due.map((todo) => todo.trip_id))];+ const listsOn = await Promise.all(tripIds.map((id) => this.addons.isEnabledForTrip(id, ADDON_IDS.PACKING)));+ const withLists = new Set(tripIds.filter((_id, i) => listsOn[i]));+ const todos = due.filter((todo) => withLists.has(todo.trip_id));let sent = 0;for (const todo of todos) {diff --git a/server/src/nest/packing/packing.controller.ts b/server/src/nest/packing/packing.controller.tsindex f4d5767c3..f02b5de60 100644--- a/server/src/nest/packing/packing.controller.ts+++ b/server/src/nest/packing/packing.controller.ts@@ -1,4 +1,7 @@+import { ADDON_IDS } from '../../addons';import type { User } from '../../types';+import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { toRowId } from '../common/row-id';@@ -54,8 +57,10 @@ import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';@Controller('api/trips/:tripId/packing')// TripAccessGuard resolves :tripId and 404s a trip the user cannot reach; mutations// add @RequirePermission('packing_edit'), the same action string the service's canEdit-// passes, so the HTTP and MCP paths cannot demand different rights.-@UseGuards(JwtAuthGuard, TripAccessGuard)+// passes, so the HTTP and MCP paths cannot demand different rights. TripAddonGuard follows it:+// a trip that has Lists (packing and todos) off answers 404 "Packing addon is not enabled", data kept.+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)+@RequireAddon(ADDON_IDS.PACKING, 'Packing')export class PackingController {constructor(private readonly packing: PackingService,diff --git a/server/src/nest/packing/packing.mcp.ts b/server/src/nest/packing/packing.mcp.tsindex bb3520e0d..567e44e9f 100644--- a/server/src/nest/packing/packing.mcp.ts+++ b/server/src/nest/packing/packing.mcp.ts@@ -12,7 +12,7 @@ import {errorResult,ok,} from '../../nest-mcp';-import { addonGate } from '../addons/addon-gate';+import { addonGate, addonOffResource } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { uriRowId } from '../common/row-id';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';@@ -720,6 +720,7 @@ export class PackingMcp {],};}+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.PACKING))) return addonOffResource(uri, ADDON_IDS.PACKING);// Hide other members' private items (#858) from the requesting user.const items = await this.packing.listItems(id, ctx.userId);return {@@ -754,6 +755,7 @@ export class PackingMcp {],};}+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.PACKING))) return addonOffResource(uri, ADDON_IDS.PACKING);const bags = await this.packing.listBags(id);return {contents: [diff --git a/server/src/nest/packing/packing.rpc.ts b/server/src/nest/packing/packing.rpc.tsindex 6a392465d..09eb9a8ed 100644--- a/server/src/nest/packing/packing.rpc.ts+++ b/server/src/nest/packing/packing.rpc.ts@@ -1,4 +1,5 @@-import { PluginGuards } from '../../nest-rpc/plugin-guards.service';+import { ADDON_IDS } from '../../addons';+import { PluginGuards, type RpcAddon } from '../../nest-rpc/plugin-guards.service';import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors';import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators';import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';@@ -13,6 +14,9 @@ const PACKING_EDIT_ACTION = 'packing_edit';type PrivacyItem = { is_private?: number; owner_id?: number | null; recipients?: { user_id: number }[] };+/** Every read and write here belongs to the packing addon and follows it per trip. */+const PACKING_ADDON: RpcAddon = { addonId: ADDON_IDS.PACKING, noun: 'packing' };+/*** The packing surface a plugin may reach (#plugins).*@@ -37,8 +41,11 @@ export class PackingRpc {list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {// Scoped to the acting user so the #858 visibility filter applies: a plugin must// not see another member's private items.- return this.guards.tripRead(params, ctx, (userId) =>- this.packing.listItems(rowIdParam(params.tripId, 'tripId'), userId),+ return this.guards.tripRead(+ params,+ ctx,+ (userId) => this.packing.listItems(rowIdParam(params.tripId, 'tripId'), userId),+ PACKING_ADDON,);}@@ -48,7 +55,7 @@ export class PackingRpc {const actor = this.guards.requireActor(ctx, 'packing item');const parsed = packingCreateItemRequestSchema.safeParse(params.input);if (!parsed.success) throw new BadParams(`invalid packing item: ${schemaMessage(parsed.error)}`);- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);const item = (await this.packing.createItem(String(tripId), parsed.data as never, actor)) as PrivacyItem;// A referenced bag must exist on this trip (#2154), as on the REST route.if (isInvalidBagRef(item)) throw new BadParams(`no packing bag ${parsed.data.bag_id} on trip ${tripId}`);@@ -64,7 +71,7 @@ export class PackingRpc {const actor = this.guards.requireActor(ctx, 'packing item');const parsed = packingUpdateItemRequestSchema.safeParse(params.input);if (!parsed.success) throw new BadParams(`invalid packing item: ${schemaMessage(parsed.error)}`);- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);// Read the privacy BEFORE the write, so a public/private toggle routes correctly.const before = await this.packing.getItemPrivacy(tripId, itemId);const input = parsed.data as Record<string, unknown>;@@ -94,7 +101,7 @@ export class PackingRpc {const tripId = rowIdParam(params.tripId, 'tripId');const itemId = rowIdParam(params.itemId, 'itemId');const actor = this.guards.requireActor(ctx, 'packing item');- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);// Plan 4 Task 8b (U6) — same drop of itemId's String() wrapper as update above.const deleted = (await this.packing.deleteItem(String(tripId), itemId, actor)) as PrivacyItem | null;if (!deleted) throw new ForbiddenResource(`no packing item ${itemId} on trip ${tripId}`);@@ -111,6 +118,7 @@ export class PackingRpc {params,ctx,async () => (await this.packing.listBags(String(rowIdParam(params.tripId, 'tripId')))) as unknown[],+ PACKING_ADDON,);}@@ -120,7 +128,7 @@ export class PackingRpc {const actor = this.guards.requireActor(ctx, 'packing bag');const input = asPayload(params.input);if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('bag name is required');- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);const bag = await this.packing.createBag(String(tripId), {name: input.name,color: typeof input.color === 'string' ? input.color : undefined,@@ -135,7 +143,7 @@ export class PackingRpc {const tripId = rowIdParam(params.tripId, 'tripId');const bagId = rowIdParam(params.bagId, 'bagId');const actor = this.guards.requireActor(ctx, 'packing bag');- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);const input = asPayload(params.input);// Plan 4 Task 8b (U6) — bagId is already a real row id (rowIdParam() above);// PackingService.updateBag's bagId param no longer needs the String() wrapper.@@ -150,7 +158,7 @@ export class PackingRpc {const tripId = rowIdParam(params.tripId, 'tripId');const bagId = rowIdParam(params.bagId, 'bagId');const actor = this.guards.requireActor(ctx, 'packing bag');- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);// Plan 4 Task 8b (U6) — same drop of bagId's String() wrapper as updateBag above.if (!(await this.packing.deleteBag(String(tripId), bagId))) {throw new ForbiddenResource(`no packing bag ${bagId} on trip ${tripId}`);@@ -166,7 +174,7 @@ export class PackingRpc {const tripId = rowIdParam(params.tripId, 'tripId');const bagId = rowIdParam(params.bagId, 'bagId');const actor = this.guards.requireActor(ctx, 'packing bag');- await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION, PACKING_ADDON);// userIds sits on the params object itself, not under `input`.const raw = asPayload(params).userIds;const userIds = Array.isArray(raw) ? raw.filter((x): x is number => typeof x === 'number') : [];diff --git a/server/src/nest/paddle-obstacles/paddle-obstacles.controller.ts b/server/src/nest/paddle-obstacles/paddle-obstacles.controller.tsindex 9419985ca..45cf96875 100644--- a/server/src/nest/paddle-obstacles/paddle-obstacles.controller.ts+++ b/server/src/nest/paddle-obstacles/paddle-obstacles.controller.ts@@ -41,7 +41,7 @@ import type { Request } from 'express';* Asking again follows the load; it never starts a second one.*/@Controller('api/paddle')-@UseGuards(AddonGuard, JwtAuthGuard)+@UseGuards(JwtAuthGuard, AddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class PaddleObstaclesController {constructor(diff --git a/server/src/nest/paddle-routing/paddle-routing.controller.ts b/server/src/nest/paddle-routing/paddle-routing.controller.tsindex f5d6dfea7..0eb182b4a 100644--- a/server/src/nest/paddle-routing/paddle-routing.controller.ts+++ b/server/src/nest/paddle-routing/paddle-routing.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { TripAccessGuard } from '../permissions/trip-access.guard';@@ -15,7 +15,7 @@ import { paddleRouteResponseSchema } from '@trek/shared';* path only says whose planner asks, so anyone who can see the trip may.*/@Controller('api/trips/:tripId/paddle')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class PaddleRoutingController {constructor(private readonly routing: PaddleRoutingService) {}diff --git a/server/src/nest/plugins/contributions/view-contributions.controller.ts b/server/src/nest/plugins/contributions/view-contributions.controller.tsindex eb4a2eaac..3c0792284 100644--- a/server/src/nest/plugins/contributions/view-contributions.controller.ts+++ b/server/src/nest/plugins/contributions/view-contributions.controller.ts@@ -1,3 +1,5 @@+import { ADDON_IDS } from '../../../addons';+import { AddonsService } from '../../addons/addons.service';import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';import { toRowId } from '../../common/row-id';import { TripAccessService } from '../../trip-membership/trip-access.service';@@ -55,6 +57,13 @@ const VIEWS: ReadonlySet<string> = new Set(['files','todos',]);+/** The views that belong to a trip addon: a trip that has it off gets no columns there. */+const VIEW_ADDON: Readonly<Record<string, string>> = {+ costs: ADDON_IDS.BUDGET,+ packing: ADDON_IDS.PACKING,+ todos: ADDON_IDS.PACKING,+ files: ADDON_IDS.DOCUMENTS,+};const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);const MAX_COLUMNS = 20;const MAX_ACTIONS = 10;@@ -140,6 +149,7 @@ export class ViewContributionsController {constructor(private readonly hooks: PluginHooks,private readonly trips: TripAccessService,+ private readonly addons: AddonsService,) {}@Get(':view/:tripId')@@ -153,6 +163,8 @@ export class ViewContributionsController {const userId = req.user?.id;if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId)))return { contributions: [] };+ const addonId = VIEW_ADDON[view];+ if (addonId && !(await this.addons.isEnabledForTrip(tripId, addonId))) return { contributions: [] };const ids = this.hooks.providersOf('tableContributor');const perProvider = await Promise.all(diff --git a/server/src/nest/plugins/plugin-event-addons.ts b/server/src/nest/plugins/plugin-event-addons.tsnew file mode 100644index 000000000..697ca9e42--- /dev/null+++ b/server/src/nest/plugins/plugin-event-addons.ts@@ -0,0 +1,51 @@+import { ADDON_IDS } from '../../addons';+import type { PluginEventMeta } from '../../plugin-event-sink';+import type { AddonsService } from '../addons/addons.service';+import { withRequestContext } from '../database/request-context';+import type { MikroORM } from '@mikro-orm/core';++/**+ * The trip addon a core event belongs to, read from its family (the part of+ * the name before the first colon), or null for an event of the trip itself.+ * A trip that has the addon off sends a plugin none of that family's events,+ * as it shows none of their rows: costs, lists, files, collab, road trip and+ * tours stay between the trip's members while the owner keeps them off.+ */+const FAMILY_ADDON: Readonly<Record<string, string>> = {+ budget: ADDON_IDS.BUDGET,+ packing: ADDON_IDS.PACKING,+ todo: ADDON_IDS.PACKING,+ file: ADDON_IDS.DOCUMENTS,+ collab: ADDON_IDS.COLLAB,+ roadtripBoundary: ADDON_IDS.ROADTRIP,+ roadtripPreferences: ADDON_IDS.ROADTRIP,+ roadtripTrack: ADDON_IDS.ROADTRIP,+ roadtripVia: ADDON_IDS.ROADTRIP,+ tours: ADDON_IDS.TOURS,+};++export function tripAddonOfEvent(event: string): string | null {+ const family = event.split(':', 1)[0];+ return Object.prototype.hasOwnProperty.call(FAMILY_ADDON, family) ? FAMILY_ADDON[family] : null;+}++type Deliver = (tripId: number, event: string, meta?: PluginEventMeta) => void;++/**+ * The plugin event sink with the trip's addons in front of it: an event of a+ * trip addon's family is handed on only once the addon is read as on for the+ * trip, any other event at once. An addon that cannot be read sends nothing,+ * since events are best-effort and a family the owner switched off must not+ * leak through a failed read.+ */+export function tripEventSink(addons: AddonsService, orm: MikroORM | undefined, deliver: Deliver): Deliver {+ return (tripId, event, meta) => {+ const addonId = tripAddonOfEvent(event);+ if (!addonId) return deliver(tripId, event, meta);+ const ask = () => addons.isEnabledForTrip(tripId, addonId);+ void (orm ? withRequestContext(orm, ask) : ask()).then(+ (on) => on && deliver(tripId, event, meta),+ () => undefined,+ );+ };+}diff --git a/server/src/nest/plugins/plugin-runtime.service.ts b/server/src/nest/plugins/plugin-runtime.service.tsindex ce32ba8f1..387ac27c0 100644--- a/server/src/nest/plugins/plugin-runtime.service.ts+++ b/server/src/nest/plugins/plugin-runtime.service.ts@@ -38,6 +38,7 @@ import { NotificationChannelPreferences } from '../../db/entities/NotificationChimport type { NotificationChannelPreferencesRepository } from '../../db/repositories/NotificationChannelPreferences.repository';import { pluginsEnabled } from './kill-switch';import { setPluginEventSink } from '../../plugin-event-sink';+import { tripEventSink } from './plugin-event-addons';import { setUserDeletedSink } from '../../plugin-user-lifecycle';import { setPluginChannelSource, pluginChannelId } from '../notifications/channel-registry';import type { ChannelMessage, ExternalChannel } from '../notifications/notification-events';@@ -330,9 +331,8 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDesawait this.supervisor.shutdownAll();applyStagedPluginTrees();});- // Forward core trip events to plugins that subscribed (events:subscribe). The- // sink is name-only + fire-and-forget, so it can never block a core broadcast.- setPluginEventSink((tripId, event, meta) => this.supervisor.deliverEvent(tripId, event, meta));+ // Core trip events go to subscribed plugins, fire-and-forget, unless the trip has the event's addon off.+ setPluginEventSink(tripEventSink(this.addons, this.orm, (t, e, m) => this.supervisor.deliverEvent(t, e, m)));// Expose plugin notification channels to the (plain, non-Nest) notification// service. Pull-based: it calls this on every dispatch, so enabling or removing// a plugin takes effect immediately with nothing to invalidate.diff --git a/server/src/nest/receipt-scan/receipt-scan.controller.ts b/server/src/nest/receipt-scan/receipt-scan.controller.tsindex 5d50a9543..27148db09 100644--- a/server/src/nest/receipt-scan/receipt-scan.controller.ts+++ b/server/src/nest/receipt-scan/receipt-scan.controller.ts@@ -59,7 +59,7 @@ export class ReceiptScanController {): Promise<ReceiptScanStartResponse> {const trip = await this.trips.findAccessible(tripId, user.id);if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);- if (!(await this.addons.isAddonEnabled(ADDON_IDS.BUDGET)))+ if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.BUDGET)))throw new HttpException({ error: 'Costs addon is not enabled' }, 404);if (!(await this.permissions.checkPermission(diff --git a/server/src/nest/reservations/reservation-inputs.ts b/server/src/nest/reservations/reservation-inputs.tsindex 6b480103e..01cee1c1a 100644--- a/server/src/nest/reservations/reservation-inputs.ts+++ b/server/src/nest/reservations/reservation-inputs.ts@@ -73,3 +73,16 @@ export interface UpdateReservationData {endpoints?: EndpointInput[];needs_review?: boolean;}++/** The stay times a hotel booking keeps in its metadata. */+export type AccommodationTimesMeta = {+ check_in_time?: string | null;+ check_in_end_time?: string | null;+ check_out_time?: string | null;+};++/** A booking's linked cost as a write takes it. */+export type BudgetEntry =+ { total_price?: number; category?: string; currency?: string | null; exchange_rate?: number } | undefined;+/** A booking's cost as written: the entry, dated on the booking's day (bookingDate), never by the caller. */+export type DatedBudgetEntry = (NonNullable<BudgetEntry> & { expense_date?: string | null }) | undefined;diff --git a/server/src/nest/reservations/reservations.module.ts b/server/src/nest/reservations/reservations.module.tsindex 9a4207e79..1d414e0ec 100644--- a/server/src/nest/reservations/reservations.module.ts+++ b/server/src/nest/reservations/reservations.module.ts@@ -12,6 +12,7 @@ import { Trips } from '../../db/entities/Trips.entity';import { Users } from '../../db/entities/Users.entity';import { PluginGuardsModule } from '../../nest-rpc/plugin-guards.module';import { AccommodationsModule } from '../accommodations/accommodations.module';+import { AddonsModule } from '../addons/addons.module';import { AssignmentsModule } from '../assignments/assignments.module';import { BudgetModule } from '../budget/budget.module';import { DaysModule } from '../days/days.module';@@ -64,6 +65,8 @@ import { Module } from '@nestjs/common';RealtimeModule,PluginGuardsModule,ReservationsReadModule,+ // A booking write files its cost only while the trip has Costs on.+ AddonsModule,AirtrailCoreModule,MikroOrmModule.forFeature([Reservations,diff --git a/server/src/nest/reservations/reservations.service.ts b/server/src/nest/reservations/reservations.service.tsindex 9d54b59e4..7791122ca 100644--- a/server/src/nest/reservations/reservations.service.ts+++ b/server/src/nest/reservations/reservations.service.ts@@ -1,5 +1,5 @@import { originColumns } from './reservation-origin.contract';-import type { CreateAccommodation, CreateReservationData, EndpointInput, ReservationEndpoint, UpdateReservationData } from './reservation-inputs';+import type { AccommodationTimesMeta, BudgetEntry, CreateAccommodation, CreateReservationData, DatedBudgetEntry, EndpointInput, ReservationEndpoint, UpdateReservationData } from './reservation-inputs';export type { CreateAccommodation, CreateReservationData, EndpointInput, ReservationEndpoint, UpdateReservationData } from './reservation-inputs';import type { ReservationRow, ReservationTraveler } from './reservation-rows';export type { ReservationRow, ReservationTraveler } from './reservation-rows';@@ -15,6 +15,8 @@ import { keepMirroredPrice } from './reservation-metadata';import { endpointRows, groupDayPositions, groupEndpointsByReservation } from './reservations.helpers';import type { Reservation, User } from '../../types';import { BudgetService } from '../budget/budget.service';+import { AddonsService } from '../addons/addons.service';+import { ADDON_IDS } from '../../addons';import { isDerivedCostCategory, typeToCostCategory } from '@trek/shared';import { NotificationsService } from '../notifications/notifications.service';import { AccommodationsService, noStayMirror, type AccommodationMirror } from '../accommodations/accommodations.service';@@ -47,22 +49,12 @@ import { RESERVATION_METADATA } from '../../db/json-columns';import { decodeJson } from '../../utils/json-column';type Trip = TripAccess;-type BudgetEntry = { total_price?: number; category?: string; currency?: string | null; exchange_rate?: number } | undefined;-/** A booking's cost as written: the entry, dated on the booking's day (bookingDate), never by the caller. */-type DatedBudgetEntry = (NonNullable<BudgetEntry> & { expense_date?: string | null }) | undefined;-/** What a booking write did to its linked costs, for the caller to send once the write has committed. */export type CostEvent =| { event: 'budget:created'; payload: TrekWsPayload<'budget:created'> }| { event: 'budget:updated'; payload: TrekWsPayload<'budget:updated'> }| { event: 'budget:deleted'; payload: TrekWsPayload<'budget:deleted'> };-type AccommodationTimesMeta = {- check_in_time?: string | null;- check_in_end_time?: string | null;- check_out_time?: string | null;-};-/*** Reservations domain service: the reservation SQL with the legacy `||`* defaults and COALESCE update semantics, every multi-statement write in one@@ -91,6 +83,7 @@ export class ReservationsService {@InjectRepository(Users) private readonly usersRepo: UsersRepository,@InjectRepository(Trips) private readonly tripsRepo: TripsRepository,@InjectRepository(BudgetItems) private readonly budgetItemsRepo: BudgetItemsRepository,+ private readonly addons: AddonsService,) {}async verifyTripAccess(tripId: string | number, userId: number) {@@ -568,7 +561,7 @@ export class ReservationsService {async createWithCostInTx(tripId: string, data: CreateReservationData, entry: BudgetEntry) {const costEvents: CostEvent[] = [];const done = await this.createInTx(tripId, data);- await this.syncBudgetOnCreate(tripId, done.reservation.id, data.title, data.type, await this.dated(entry, done.reservation), undefined, costEvents);+ if (await this.costsOn(tripId)) await this.syncBudgetOnCreate(tripId, done.reservation.id, data.title, data.type, await this.dated(entry, done.reservation), undefined, costEvents);return { ...done, costEvents };}@@ -577,13 +570,18 @@ export class ReservationsService {const costEvents: CostEvent[] = [];const { stayMirror, ...written } = await this.uow.transactional(async () => {const done = await this.updateInTx(id, tripId, data, current);- await this.syncBudgetOnUpdate(tripId, id, data.title ?? '', data.type, current.title, current.type ?? undefined, await this.dated(entry, done.reservation), undefined, costEvents);+ if (await this.costsOn(tripId)) await this.syncBudgetOnUpdate(tripId, id, data.title ?? '', data.type, current.title, current.type ?? undefined, await this.dated(entry, done.reservation), undefined, costEvents);return done;});await this.announceStayMirror(tripId, stayMirror);return { ...written, costEvents };}+ /** A booking write files no cost while the trip has Costs off; the costs it has stay as they are. */+ private costsOn(tripId: string): Promise<boolean> {+ return this.addons.isEnabledForTrip(Number(tripId), ADDON_IDS.BUDGET);+ }+/** Sends a booking write's cost events to the trip. */announceCost(tripId: string | number, events: readonly CostEvent[], socketId: string | undefined): void {for (const e of events) this.realtime.broadcast(tripId, e.event, e.payload, socketId);diff --git a/server/src/nest/roadtrip/charging-lookup.controller.ts b/server/src/nest/roadtrip/charging-lookup.controller.tsindex 42718f480..dde522e8e 100644--- a/server/src/nest/roadtrip/charging-lookup.controller.ts+++ b/server/src/nest/roadtrip/charging-lookup.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { TripAccessGuard } from '../permissions/trip-access.guard';import { ChargingService } from './charging.service';@@ -29,7 +29,7 @@ export class ChargingLookupDto extends createZodDto(chargingLookupSchema) {}* and a name, which belongs in a body behind a contract rather than in a query string.*/@Controller('api/trips/:tripId/roadtrip/charging-lookup')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class ChargingLookupController {constructor(private readonly charging: ChargingService) {}diff --git a/server/src/nest/roadtrip/charging.controller.ts b/server/src/nest/roadtrip/charging.controller.tsindex 04886c53c..697475a4f 100644--- a/server/src/nest/roadtrip/charging.controller.ts+++ b/server/src/nest/roadtrip/charging.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ParseRowIdPipe } from '../common/row-id.pipe';import { TripAccessGuard } from '../permissions/trip-access.guard';@@ -8,7 +8,7 @@ import { ChargingService } from './charging.service';import { Controller, Get, Param, UseGuards } from '@nestjs/common';@Controller('api/trips/:tripId/roadtrip/charging')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class ChargingController {constructor(private readonly charging: ChargingService) {}diff --git a/server/src/nest/roadtrip/day-boundaries.controller.ts b/server/src/nest/roadtrip/day-boundaries.controller.tsindex b16a998ab..fb014c98d 100644--- a/server/src/nest/roadtrip/day-boundaries.controller.ts+++ b/server/src/nest/roadtrip/day-boundaries.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ParseRowIdPipe } from '../common/row-id.pipe';import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';@@ -14,7 +14,7 @@ import { createZodDto } from 'nestjs-zod';export class DayBoundaryDto extends createZodDto(roadtripDayBoundarySchema) {}@Controller('api/trips/:tripId/roadtrip/day-boundaries')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class DayBoundariesController {constructor(diff --git a/server/src/nest/roadtrip/google-route.controller.ts b/server/src/nest/roadtrip/google-route.controller.tsindex fddfc46be..f9c3fc50b 100644--- a/server/src/nest/roadtrip/google-route.controller.ts+++ b/server/src/nest/roadtrip/google-route.controller.ts@@ -1,6 +1,7 @@import { ADDON_IDS } from '../../addons';import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { TripAccessGuard } from '../permissions/trip-access.guard';import { GoogleRouteService } from './google-route.service';@@ -13,8 +14,13 @@ import { createZodDto } from 'nestjs-zod';export class PreviewDto extends createZodDto(googleRoutePreviewRequestSchema) {}export class ImportDto extends createZodDto(googleRouteImportSchema) {}+/**+ * The preview has no trip, so AddonGuard opens it while the instance or any+ * trip of the caller has Road trip on. The import writes into one trip and+ * asks that trip, after TripAccessGuard.+ */@Controller('api')-@UseGuards(AddonGuard, JwtAuthGuard)+@UseGuards(JwtAuthGuard, AddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class GoogleRouteController {constructor(private readonly routes: GoogleRouteService) {}@@ -26,7 +32,7 @@ export class GoogleRouteController {@Post('trips/:tripId/roadtrip/google-maps-import')@HttpCode(200)- @UseGuards(TripAccessGuard)+ @UseGuards(TripAccessGuard, TripAddonGuard)import(@Param('tripId') tripId: string,@Body() input: ImportDto,diff --git a/server/src/nest/roadtrip/roadtrip-hazards.controller.ts b/server/src/nest/roadtrip/roadtrip-hazards.controller.tsindex 2646fc83f..386a2458d 100644--- a/server/src/nest/roadtrip/roadtrip-hazards.controller.ts+++ b/server/src/nest/roadtrip/roadtrip-hazards.controller.ts@@ -1,13 +1,13 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { TripAccessGuard } from '../permissions/trip-access.guard';import { RoadtripHazardsService } from './roadtrip-hazards.service';import { Controller, Get, UseGuards } from '@nestjs/common';@Controller('api/trips/:tripId/roadtrip/hazards')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class RoadtripHazardsController {constructor(private readonly hazards: RoadtripHazardsService) {}diff --git a/server/src/nest/roadtrip/roadtrip-preferences.controller.ts b/server/src/nest/roadtrip/roadtrip-preferences.controller.tsindex cf547144d..048c94a27 100644--- a/server/src/nest/roadtrip/roadtrip-preferences.controller.ts+++ b/server/src/nest/roadtrip/roadtrip-preferences.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';import { RoadtripPreferencesService } from './roadtrip-preferences.service';@@ -12,7 +12,7 @@ import { createZodDto } from 'nestjs-zod';export class PreferencesDto extends createZodDto(roadtripPreferencesUpdateSchema) {}@Controller('api/trips/:tripId/roadtrip/preferences')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class RoadtripPreferencesController {constructor(private readonly preferences: RoadtripPreferencesService) {}diff --git a/server/src/nest/roadtrip/roadtrip.controller.ts b/server/src/nest/roadtrip/roadtrip.controller.tsindex c7fc178d3..4108df8e7 100644--- a/server/src/nest/roadtrip/roadtrip.controller.ts+++ b/server/src/nest/roadtrip/roadtrip.controller.ts@@ -1,7 +1,7 @@import { ADDON_IDS } from '../../addons';import type { User } from '../../types';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';@@ -45,11 +45,11 @@ import type { RoadtripDayTrack, RoadtripVia } from '@trek/shared';* socket that sent the request.*/@Controller('api/trips/:tripId/roadtrip')-// AddonGuard FIRST: @RequireAddon is metadata and does nothing on its own, and the guard-// is not registered globally either, so without it here the decorator below was inert and-// all six routes answered on an instance that had the addon switched off. It leads the-// chain because a disabled addon owes an anonymous caller a 404, not a 401.-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+// TripAddonGuard enforces @RequireAddon, which is metadata and does nothing on its own: without+// a guard here the decorator below was inert and all six routes answered on an instance that+// had the addon switched off. It runs after TripAccessGuard because what applies is the trip's+// own choice, which only a caller who may see the trip learns.+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')export class RoadtripController {constructor(private readonly roadtrip: RoadtripService) {}diff --git a/server/src/nest/share/share.module.ts b/server/src/nest/share/share.module.tsindex 1d7019058..d6c17cfe9 100644--- a/server/src/nest/share/share.module.ts+++ b/server/src/nest/share/share.module.ts@@ -8,6 +8,7 @@ import { Places } from '../../db/entities/Places.entity';import { Reservations } from '../../db/entities/Reservations.entity';import { ShareTokens } from '../../db/entities/ShareTokens.entity';import { Trips } from '../../db/entities/Trips.entity';+import { AddonsModule } from '../addons/addons.module';import { McpSharedModule } from '../mcp-shared/mcp-shared.module';import { PermissionsModule } from '../permissions/permissions.module';import { PlacePhotosModule } from '../place-photos/place-photos.module';@@ -29,6 +30,8 @@ import { Module } from '@nestjs/common';// for the same reason).@Module({imports: [+ // The shared sections follow the trip's addons (ShareService.getSharedTripData).+ AddonsModule,McpSharedModule,SettingsModule,PermissionsModule,diff --git a/server/src/nest/share/share.service.ts b/server/src/nest/share/share.service.tsindex 90594390a..0046621aa 100644--- a/server/src/nest/share/share.service.ts+++ b/server/src/nest/share/share.service.ts@@ -1,3 +1,4 @@+import { ADDON_IDS } from '../../addons';import { BudgetItems } from '../../db/entities/BudgetItems.entity';import { CollabMessages } from '../../db/entities/CollabMessages.entity';import { DayAssignments } from '../../db/entities/DayAssignments.entity';@@ -19,6 +20,7 @@ import type { ReservationsRepository } from '../../db/repositories/Reservations.import type { ShareTokensRepository } from '../../db/repositories/ShareTokens.repository';import type { TripsRepository, TripAccess } from '../../db/repositories/Trips.repository';import type { User } from '../../types';+import { AddonsService } from '../addons/addons.service';import { UnitOfWork } from '../database/unit-of-work';import { PermissionsService } from '../permissions/permissions.service';import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';@@ -214,6 +216,7 @@ export class ShareService {@InjectRepository(PackingItems) private readonly packingItems: PackingItemsRepository,@InjectRepository(BudgetItems) private readonly budgetItems: BudgetItemsRepository,@InjectRepository(CollabMessages) private readonly collabMessages: CollabMessagesRepository,+ private readonly addons: AddonsService,) {}/** SH-AP1 — the same `TripsRepository.findAccessible` every other access-primitive call in this plan reuses. */@@ -346,12 +349,15 @@ export class ShareService {const trip = await this.trips.findPublicForShare(tripId);if (!trip) return null;+ // A section whose addon is off for this trip is not shared, whatever the+ // link allows, and the page is told so through the same flags it reads.+ const on = async (addonId: string) => this.addons.isEnabledForTrip(tripId, addonId);const permissions = {share_map: !!shareRow.share_map,share_bookings: !!shareRow.share_bookings,- share_packing: !!shareRow.share_packing,- share_budget: !!shareRow.share_budget,- share_collab: !!shareRow.share_collab,+ share_packing: !!shareRow.share_packing && (await on(ADDON_IDS.PACKING)),+ share_budget: !!shareRow.share_budget && (await on(ADDON_IDS.BUDGET)),+ share_collab: !!shareRow.share_collab && (await on(ADDON_IDS.COLLAB)),share_travel_only: !!shareRow.share_travel_only,share_hide_images: !!shareRow.share_hide_images,};diff --git a/server/src/nest/ski-routing/ski-routing.controller.ts b/server/src/nest/ski-routing/ski-routing.controller.tsindex 6c94218f4..725cfdd27 100644--- a/server/src/nest/ski-routing/ski-routing.controller.ts+++ b/server/src/nest/ski-routing/ski-routing.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { TripAccessGuard } from '../permissions/trip-access.guard';@@ -18,7 +18,7 @@ import type { Response } from 'express';* the areas are downloaded by id and searched here.*/@Controller('api/trips/:tripId/ski')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class SkiRoutingController {constructor(private readonly routing: SkiRoutingService) {}diff --git a/server/src/nest/todo/todo.controller.ts b/server/src/nest/todo/todo.controller.tsindex 51def983a..77b36884e 100644--- a/server/src/nest/todo/todo.controller.ts+++ b/server/src/nest/todo/todo.controller.ts@@ -1,4 +1,7 @@+import { ADDON_IDS } from '../../addons';import type { User } from '../../types';+import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';@@ -29,8 +32,10 @@ import {@Controller('api/trips/:tripId/todo')// TripAccessGuard resolves :tripId and 404s a trip the user cannot reach; mutations// add @RequirePermission('packing_edit'), the same action string the service's canEdit-// passes, so the HTTP and MCP paths cannot demand different rights.-@UseGuards(JwtAuthGuard, TripAccessGuard)+// passes, so the HTTP and MCP paths cannot demand different rights. TripAddonGuard follows it:+// a trip that has Lists (packing and todos) off answers 404 "Packing addon is not enabled", data kept.+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)+@RequireAddon(ADDON_IDS.PACKING, 'Packing')export class TodoController {constructor(private readonly todo: TodoService) {}diff --git a/server/src/nest/todo/todo.mcp.ts b/server/src/nest/todo/todo.mcp.tsindex a6ef55a6b..8ff832027 100644--- a/server/src/nest/todo/todo.mcp.ts+++ b/server/src/nest/todo/todo.mcp.ts@@ -12,7 +12,7 @@ import {errorResult,ok,} from '../../nest-mcp';-import { addonGate } from '../addons/addon-gate';+import { addonGate, addonOffResource } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { uriRowId } from '../common/row-id';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';@@ -305,6 +305,7 @@ export class TodoMcp {],};}+ if (!(await this.addons.isEnabledForTrip(id, ADDON_IDS.PACKING))) return addonOffResource(uri, ADDON_IDS.PACKING);const items = await this.todos.listItems(id);return {contents: [diff --git a/server/src/nest/todo/todo.rpc.ts b/server/src/nest/todo/todo.rpc.tsindex 580c97536..d76b44ddf 100644--- a/server/src/nest/todo/todo.rpc.ts+++ b/server/src/nest/todo/todo.rpc.ts@@ -1,4 +1,5 @@-import { PluginGuards } from '../../nest-rpc/plugin-guards.service';+import { ADDON_IDS } from '../../addons';+import { PluginGuards, type RpcAddon } from '../../nest-rpc/plugin-guards.service';import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors';import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators';import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';@@ -9,6 +10,9 @@ import { TodoService } from './todo.service';/** The app edits todos under 'packing_edit', not under a todo-specific action. */const TODO_EDIT_ACTION = 'packing_edit';+/** Every read and write here belongs to the packing addon and follows it per trip. */+const TODO_ADDON: RpcAddon = { addonId: ADDON_IDS.PACKING, noun: 'packing' };+/*** 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.@@ -32,6 +36,7 @@ export class TodoRpc {params,ctx,async () => (await this.todos.listItems(String(rowIdParam(params.tripId, 'tripId')))) as unknown[],+ TODO_ADDON,);}@@ -41,7 +46,7 @@ export class TodoRpc {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');- await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION, TODO_ADDON);const item = await this.todos.createItem(String(tripId), input as never);this.realtime.broadcast(tripId, 'todo:created', { item }, undefined);return item;@@ -52,7 +57,7 @@ export class TodoRpc {const tripId = rowIdParam(params.tripId, 'tripId');const todoId = rowIdParam(params.todoId, 'todoId');const actor = this.guards.requireActor(ctx, 'todo');- await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION, TODO_ADDON);const input = asPayload(params.input);const updated = await this.todos.updateItem(String(tripId), todoId, input as never, Object.keys(input));if (!updated) throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`);@@ -65,7 +70,7 @@ export class TodoRpc {const tripId = rowIdParam(params.tripId, 'tripId');const todoId = rowIdParam(params.todoId, 'todoId');const actor = this.guards.requireActor(ctx, 'todo');- await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION);+ await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION, TODO_ADDON);if (!(await this.todos.deleteItem(String(tripId), todoId))) {throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`);}diff --git a/server/src/nest/tours/collection-tours.controller.ts b/server/src/nest/tours/collection-tours.controller.tsindex 83882e46e..fac1d32f5 100644--- a/server/src/nest/tours/collection-tours.controller.ts+++ b/server/src/nest/tours/collection-tours.controller.ts@@ -2,6 +2,7 @@ import { ADDON_IDS } from '../../addons';import type { User } from '../../types';import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { DomainError } from '../common/domain-error';@@ -33,7 +34,7 @@ function rowId(raw: string, missing: string): number {* and, when a tour is kept, that they can open the trip it comes from.*/@Controller('api/addons/collections/:collectionId/tours')-@UseGuards(AddonGuard, JwtAuthGuard)+@UseGuards(JwtAuthGuard, AddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class CollectionToursController {constructor(private readonly kept: CollectionToursService) {}@@ -89,7 +90,7 @@ export class CollectionToursController {* 'place_edit' on it; the service checks the collection.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class CollectionTourTakeOverController {constructor(private readonly kept: CollectionToursService) {}diff --git a/server/src/nest/tours/collection-tours.mcp.ts b/server/src/nest/tours/collection-tours.mcp.tsindex bb97384b5..18d7d4598 100644--- a/server/src/nest/tours/collection-tours.mcp.ts+++ b/server/src/nest/tours/collection-tours.mcp.ts@@ -11,7 +11,7 @@ import {ok,type McpContext,} from '../../nest-mcp';-import { addonGate, type HasAddons } from '../addons/addon-gate';+import { allAddonsGate } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';import { TripAccessService } from '../trip-membership/trip-access.service';@@ -28,13 +28,8 @@ import {const save = collectionTourSaveRequestSchema.shape;const takeOver = collectionTourTakeOverRequestSchema.shape;-const toursOn = addonGate(ADDON_IDS.TOURS);-const collectionsOn = addonGate(ADDON_IDS.COLLECTIONS);-/** A kept tour is a tour that lives in a collection, so both addons have to be on. */-async function keptToursOn(ctx: McpContext, self: HasAddons): Promise<boolean> {- return (await toursOn(ctx, self)) && (await collectionsOn(ctx, self));-}+const keptToursOn = allAddonsGate(ADDON_IDS.TOURS, ADDON_IDS.COLLECTIONS);/*** LIB-03: the whole tours a collection keeps, over the same service and thediff --git a/server/src/nest/tours/collection-tours.service.ts b/server/src/nest/tours/collection-tours.service.tsindex 62447c0da..b2181f2e5 100644--- a/server/src/nest/tours/collection-tours.service.ts+++ b/server/src/nest/tours/collection-tours.service.ts@@ -90,6 +90,8 @@ export class CollectionToursService {await this.assertCollectionsOn();await this.collections.assertCanEdit(userId, collectionId);if (!(await this.access.findAccessible(body.source_trip_id, userId))) throw tourNotFound();+ // A trip with Tours off shows its tours nowhere, so it has none to keep either.+ if (!(await this.addons.isEnabledForTrip(body.source_trip_id, ADDON_IDS.TOURS))) throw tourNotFound();const [trip] = await this.kept.targetTrips([body.source_trip_id]);if (!trip) throw tourNotFound();const id = await this.uow.transactional(async () => {@@ -161,9 +163,13 @@ export class CollectionToursService {return row;}- /** Every trip the user can open, the newest first, each saying whether they may add a tour to it. */+ /**+ * Every trip the user can open that has Tours on, the newest first, each+ * saying whether they may add a tour to it. A trip with Tours off refuses+ * the take-over, so it is no target.+ */private async targets(user: CollectionTourUser): Promise<CollectionTourTarget[]> {- const ids = await this.membership.listAccessibleTripIds(user.id);+ const ids = await this.addons.tripsWithAddon(await this.membership.listAccessibleTripIds(user.id), ADDON_IDS.TOURS);const trips = new Map((await this.kept.targetTrips(ids)).map((trip) => [trip.id, trip]));const known = ids.flatMap((id) => {const trip = trips.get(id);diff --git a/server/src/nest/tours/tour-activities.controller.ts b/server/src/nest/tours/tour-activities.controller.tsindex c3c37443b..bed6b21f1 100644--- a/server/src/nest/tours/tour-activities.controller.ts+++ b/server/src/nest/tours/tour-activities.controller.ts@@ -1,7 +1,7 @@import { ADDON_IDS } from '../../addons';import type { User } from '../../types';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';@@ -21,7 +21,7 @@ import { tourDetailResponseSchema } from '@trek/shared';* Reading them is the tour's detail.*/@Controller('api/trips/:tripId/tours/:placeId/activities')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourActivitiesController {constructor(private readonly activities: TourActivitiesService) {}diff --git a/server/src/nest/tours/tour-activity-stats.controller.ts b/server/src/nest/tours/tour-activity-stats.controller.tsindex 487b471d9..64995943a 100644--- a/server/src/nest/tours/tour-activity-stats.controller.ts+++ b/server/src/nest/tours/tour-activity-stats.controller.ts@@ -18,7 +18,7 @@ import { tourActivityStatsResponseSchema } from '@trek/shared';* asks for no trip permission beyond being able to open the trip.*/@Controller('api/tours/activity-stats')-@UseGuards(AddonGuard, JwtAuthGuard)+@UseGuards(JwtAuthGuard, AddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourActivityStatsController {constructor(private readonly stats: TourActivityStatsService) {}diff --git a/server/src/nest/tours/tour-activity-stats.service.ts b/server/src/nest/tours/tour-activity-stats.service.tsindex daa3ca95c..a1112a990 100644--- a/server/src/nest/tours/tour-activity-stats.service.ts+++ b/server/src/nest/tours/tour-activity-stats.service.ts@@ -1,3 +1,4 @@+import { ADDON_IDS } from '../../addons';import { TourActivities } from '../../db/entities/TourActivities.entity';import { TourActivityExclusions } from '../../db/entities/TourActivityExclusions.entity';import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';@@ -6,6 +7,7 @@ import type { TourActivitiesRepository, TourStatsExecutionRow } from '../../db/rimport type { TourActivityExclusionsRepository } from '../../db/repositories/TourActivityExclusions.repository';import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';import type { ToursRepository } from '../../db/repositories/Tours.repository';+import { AddonsService } from '../addons/addons.service';import { TripMembershipService } from '../trip-membership/trip-membership.service';import { buildActivityStats } from './tour-activity-stats.helpers';import { InjectRepository } from '@mikro-orm/nestjs';@@ -17,8 +19,8 @@ import { tourStageKeysOf, type TourActivityExclusionRequest, type TourActivitySt* user can open, and leaving one out of them. Reads only, apart from the* user's own exclusions: no tour, day or plan changes here. Every answer is* bounded by the trips the user owns or is a member of, read anew for each- * call; within them only the user's own part counts (see- * `buildActivityStats`). REST and MCP call these two methods.+ * call, and of them only the ones with Tours on; within them only the user's+ * own part counts (see `buildActivityStats`). REST and MCP call these two methods.*/@Injectable()export class TourActivityStatsService {@@ -28,8 +30,14 @@ export class TourActivityStatsService {@InjectRepository(TourActivities) private readonly activitiesRepo: TourActivitiesRepository,@InjectRepository(TourActivityExclusions) private readonly exclusionsRepo: TourActivityExclusionsRepository,@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,+ private readonly addons: AddonsService,) {}+ /** The trips the user can open that have Tours on; a trip that switched it off adds nothing. */+ private async tourTrips(userId: number): Promise<number[]> {+ return this.addons.tripsWithAddon(await this.membership.listAccessibleTripIds(userId), ADDON_IDS.TOURS);+ }+/*** MDT-02: the stages of each tour that has a stage on a day of its own, by* the key of the stop each starts at, read from the tour's saved points.@@ -43,7 +51,7 @@ export class TourActivityStatsService {}async stats(userId: number): Promise<TourActivityStatsResponse> {- const tripIds = await this.membership.listAccessibleTripIds(userId);+ const tripIds = await this.tourTrips(userId);const [executions, tracks, excluded] = await Promise.all([this.activitiesRepo.listExecutionsForStats(tripIds, userId),this.activitiesRepo.listTracksForStats(tripIds),@@ -59,7 +67,7 @@ export class TourActivityStatsService {* other id reads as missing. Only the user's own sums change.*/async setExcluded(userId: number, input: TourActivityExclusionRequest): Promise<TourActivityStatsResponse> {- const tripIds = await this.membership.listAccessibleTripIds(userId);+ const tripIds = await this.tourTrips(userId);if (!(await this.toursRepo.findForLibrary(tripIds, input.place_id))) throw new NotFoundException('Tour not found');if (input.excluded) await this.exclusionsRepo.exclude(userId, input.place_id);else await this.exclusionsRepo.include(userId, input.place_id);diff --git a/server/src/nest/tours/tour-drafts.controller.ts b/server/src/nest/tours/tour-drafts.controller.tsindex 7f2c157f9..9ab7dcceb 100644--- a/server/src/nest/tours/tour-drafts.controller.ts+++ b/server/src/nest/tours/tour-drafts.controller.ts@@ -1,7 +1,7 @@import { ADDON_IDS } from '../../addons';import type { User } from '../../types';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';@@ -19,7 +19,7 @@ import { successResponseSchema, tourDraftResponseSchema } from '@trek/shared';* names the signed-in user, so a traveller only ever reaches their own draft.*/@Controller('api/trips/:tripId/tour-draft')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourDraftsController {constructor(private readonly drafts: TourDraftsService) {}diff --git a/server/src/nest/tours/tour-horse-routes.controller.ts b/server/src/nest/tours/tour-horse-routes.controller.tsindex e76a6ba91..2ed1582fa 100644--- a/server/src/nest/tours/tour-horse-routes.controller.ts+++ b/server/src/nest/tours/tour-horse-routes.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { badRequest } from '../common/domain-error';import { ResponseContract } from '../common/response-contract';@@ -37,7 +37,7 @@ export function parseHorseRoutesQuery(raw: Record<string, unknown>): HorseRoutes* a tour.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourHorseRoutesController {constructor(private readonly horseRoutes: TourHorseRoutesService) {}diff --git a/server/src/nest/tours/tour-library.controller.ts b/server/src/nest/tours/tour-library.controller.tsindex 63590703c..ebac387f8 100644--- a/server/src/nest/tours/tour-library.controller.ts+++ b/server/src/nest/tours/tour-library.controller.ts@@ -2,6 +2,7 @@ import { ADDON_IDS } from '../../addons';import type { User } from '../../types';import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';@@ -18,7 +19,7 @@ import { tourCreateResponseSchema, tourLibraryDetailResponseSchema, tourLibraryR* service bounds every answer by the user's own trips.*/@Controller('api/tours/library')-@UseGuards(AddonGuard, JwtAuthGuard)+@UseGuards(JwtAuthGuard, AddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourLibraryController {constructor(private readonly library: TourLibraryService) {}@@ -44,7 +45,7 @@ export class TourLibraryController {* 'place_edit' on it; the service checks the source trip.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourTakeOverController {constructor(private readonly library: TourLibraryService) {}diff --git a/server/src/nest/tours/tour-library.service.ts b/server/src/nest/tours/tour-library.service.tsindex dc8289a3d..e935f98a1 100644--- a/server/src/nest/tours/tour-library.service.ts+++ b/server/src/nest/tours/tour-library.service.ts@@ -1,5 +1,7 @@+import { ADDON_IDS } from '../../addons';import { Tours } from '../../db/entities/Tours.entity';import type { ToursRepository, TourLibraryRow } from '../../db/repositories/Tours.repository';+import { AddonsService } from '../addons/addons.service';import { TripMembershipService } from '../trip-membership/trip-membership.service';import { parseRouteGeometry, thinnedLine } from './tours.helpers';import { ToursService } from './tours.service';@@ -48,8 +50,9 @@ function toItem(row: TourLibraryRow, points: Parameters<typeof walkStationFacts>* into the trip they are planning. Listing and previewing read only. Every* answer is bounded by the trips the user owns or is a member of, read anew* for each call: a tour of a trip out of reach is "not found", never a hint- * that it exists. Heights, times and distances are passed on as they are- * stored, null staying null.+ * that it exists. A trip with Tours off counts as out of reach, so its tours+ * are neither listed, shown nor taken over. Heights, times and distances are+ * passed on as they are stored, null staying null.*/@Injectable()export class TourLibraryService {@@ -57,10 +60,12 @@ export class TourLibraryService {@InjectRepository(Tours) private readonly toursRepo: ToursRepository,private readonly membership: TripMembershipService,private readonly tours: ToursService,+ private readonly addons: AddonsService,) {}+ /** The user's trips that have Tours on, the one being planned left out when named. */private async reachableTrips(userId: number, exclude?: number): Promise<number[]> {- const ids = await this.membership.listAccessibleTripIds(userId);+ const ids = await this.addons.tripsWithAddon(await this.membership.listAccessibleTripIds(userId), ADDON_IDS.TOURS);return exclude === undefined ? ids : ids.filter((id) => id !== exclude);}diff --git a/server/src/nest/tours/tour-packing-link.controller.ts b/server/src/nest/tours/tour-packing-link.controller.tsindex 69cad413c..98012257a 100644--- a/server/src/nest/tours/tour-packing-link.controller.ts+++ b/server/src/nest/tours/tour-packing-link.controller.ts@@ -1,7 +1,7 @@import { ADDON_IDS } from '../../addons';import type { User } from '../../types';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';@@ -19,7 +19,7 @@ import { tourDetailResponseSchema, tourPackingLinkResponseSchema } from '@trek/s* replayed from the offline queue lands like any other tour write.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourPackingLinkController {constructor(private readonly packingLinks: TourPackingLinkService) {}diff --git a/server/src/nest/tours/tour-packing-link.service.ts b/server/src/nest/tours/tour-packing-link.service.tsindex 5930f24d9..e37955650 100644--- a/server/src/nest/tours/tour-packing-link.service.ts+++ b/server/src/nest/tours/tour-packing-link.service.ts@@ -96,9 +96,9 @@ export class TourPackingLinkService {return { tripId: tid, placeId: pid, tour };}- /** Packing has to be on for a link to be made or read through. */- private async requirePacking(): Promise<void> {- if (!(await this.addons.isAddonEnabled(ADDON_IDS.PACKING))) {+ /** Packing has to be on for this trip for a link to be made or read through. */+ private async requirePacking(tripId: number): Promise<void> {+ if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.PACKING))) {throw new DomainError(404, 'Packing addon is not enabled', { code: 'packing_addon_off' });}}@@ -129,7 +129,7 @@ export class TourPackingLinkService {socketId?: string,): Promise<TourDetailResponse> {const tour = await this.tourIn(tripId, placeId);- await this.requirePacking();+ await this.requirePacking(tour.tripId);if (body.category !== null) {const items = await this.visibleItems(tour.tripId, userId);if (!items.some((item) => item.category === body.category)) {@@ -159,8 +159,8 @@ export class TourPackingLinkService {* points at, and the tour's facts as context. Reading changes nothing.*/async view(tripId: number, placeId: number, userId: number): Promise<TourPackingView> {- const { tour } = await this.tourIn(tripId, placeId);- await this.requirePacking();+ const { tour, tripId: tid } = await this.tourIn(tripId, placeId);+ await this.requirePacking(tid);const link = (await this.links.findForTour(placeId)) ?? null;const context = {name: tour.name,diff --git a/server/src/nest/tours/tour-packing.mcp.ts b/server/src/nest/tours/tour-packing.mcp.tsindex 385e9fee5..c672f7119 100644--- a/server/src/nest/tours/tour-packing.mcp.ts+++ b/server/src/nest/tours/tour-packing.mcp.ts@@ -9,20 +9,15 @@ import {ok,type McpContext,} from '../../nest-mcp';-import { addonGate, type HasAddons } from '../addons/addon-gate';+import { allAddonsGate } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';import { TripAccessService } from '../trip-membership/trip-access.service';import { TourPackingLinkService } from './tour-packing-link.service';import { idSchema, tourPackingLinkRequestSchema, type TourPackingLinkRequest } from '@trek/shared';-const toursOn = addonGate(ADDON_IDS.TOURS);-const packingOn = addonGate(ADDON_IDS.PACKING);-/** A tour's packing link reaches into Packing, so both addons have to be on. */-async function tourPackingOn(ctx: McpContext, self: HasAddons): Promise<boolean> {- return (await toursOn(ctx, self)) && (await packingOn(ctx, self));-}+const tourPackingOn = allAddonsGate(ADDON_IDS.TOURS, ADDON_IDS.PACKING);const tourIds = {tripId: idSchema,diff --git a/server/src/nest/tours/tour-poi-search.controller.ts b/server/src/nest/tours/tour-poi-search.controller.tsindex 5076602db..fb9862e46 100644--- a/server/src/nest/tours/tour-poi-search.controller.ts+++ b/server/src/nest/tours/tour-poi-search.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { TripAccessGuard } from '../permissions/trip-access.guard';@@ -15,7 +15,7 @@ import { tourPoiSearchResponseSchema } from '@trek/shared';* line comes in the body because the draft may not be saved yet.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourPoiSearchController {constructor(private readonly search: TourPoiSearchService) {}diff --git a/server/src/nest/tours/tour-ski.controller.ts b/server/src/nest/tours/tour-ski.controller.tsindex e184386fe..8ec4a7d6b 100644--- a/server/src/nest/tours/tour-ski.controller.ts+++ b/server/src/nest/tours/tour-ski.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';@@ -15,7 +15,7 @@ import { tourDetailResponseSchema } from '@trek/shared';* edit the trip's places. Answers the tour's detail, as the editor reads it.*/@Controller('api/trips/:tripId/tours/:placeId/ski')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourSkiController {constructor(private readonly ski: TourSkiService) {}diff --git a/server/src/nest/tours/tour-trail-grade.controller.ts b/server/src/nest/tours/tour-trail-grade.controller.tsindex 61aa78231..68fa68f30 100644--- a/server/src/nest/tours/tour-trail-grade.controller.ts+++ b/server/src/nest/tours/tour-trail-grade.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { TripAccessGuard } from '../permissions/trip-access.guard';@@ -17,7 +17,7 @@ import { tourTrailGradeResponseSchema } from '@trek/shared';* saved yet.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourTrailGradeController {constructor(private readonly trailGrades: TourTrailGradeService) {}diff --git a/server/src/nest/tours/tour-visits.controller.ts b/server/src/nest/tours/tour-visits.controller.tsindex 47247676f..2afef3d59 100644--- a/server/src/nest/tours/tour-visits.controller.ts+++ b/server/src/nest/tours/tour-visits.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { ParseRowIdPipe } from '../common/row-id.pipe';@@ -17,7 +17,7 @@ import { stationKeySchema, tourVisitListResponseSchema } from '@trek/shared';* someone who may edit the trip's days. Nothing here changes a route.*/@Controller('api/trips/:tripId/tour-visits')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourVisitsController {constructor(private readonly visits: TourVisitsService) {}diff --git a/server/src/nest/tours/tour-walk-import.controller.ts b/server/src/nest/tours/tour-walk-import.controller.tsindex d2c20f9be..388fbaf49 100644--- a/server/src/nest/tours/tour-walk-import.controller.ts+++ b/server/src/nest/tours/tour-walk-import.controller.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../addons';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';@@ -16,7 +16,7 @@ import { walkImportPreviewResponseSchema } from '@trek/shared';* may not edit places 403, since what comes next creates a tour.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class TourWalkImportController {constructor(private readonly walkImport: TourWalkImportService) {}diff --git a/server/src/nest/tours/tours-import.controller.ts b/server/src/nest/tours/tours-import.controller.tsindex c3e4b9986..1b2d60733 100644--- a/server/src/nest/tours/tours-import.controller.ts+++ b/server/src/nest/tours/tours-import.controller.ts@@ -37,8 +37,9 @@ const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024* AddonGuard and TripAccessGuard: a guard answers before multer has read the* multipart body, and the client then sees ECONNRESET instead of the 404 or* 403. The handlers run the same checks in the same order once the upload is- * drained, with the guards' own bodies: addon off 404, no trip access 404,- * no 'place_edit' 403. PlacesController.importGpx is the sibling.+ * drained, with the guards' own bodies: no trip access 404, Tours off for+ * this trip 404, no 'place_edit' 403. PlacesController.importGpx is the+ * sibling.*/@Controller('api/trips/:tripId/tours')@UseGuards(JwtAuthGuard)@@ -51,13 +52,13 @@ export class ToursImportController {/** The guards' checks, after the body is in, and the file they all need. */private async checkedFile(user: User, tripId: string, file: Express.Multer.File | undefined): Promise<Buffer> {- if (!(await this.addons.isAddonEnabled(ADDON_IDS.TOURS))) {- throw new HttpException({ error: 'Tours addon is not enabled' }, 404);- }const trip = await this.places.verifyTripAccess(tripId, user.id);if (!trip) {throw new HttpException({ error: 'Trip not found' }, 404);}+ if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.TOURS))) {+ throw new HttpException({ error: 'Tours addon is not enabled' }, 404);+ }if (!(await this.places.canEdit(trip, user))) {throw new HttpException({ error: 'No permission' }, 403);}diff --git a/server/src/nest/tours/tours-wanderer.controller.ts b/server/src/nest/tours/tours-wanderer.controller.tsindex 5e2c846c7..f31edfa49 100644--- a/server/src/nest/tours/tours-wanderer.controller.ts+++ b/server/src/nest/tours/tours-wanderer.controller.ts@@ -1,7 +1,7 @@import { ADDON_IDS } from '../../addons';import type { User } from '../../types';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { ResponseContract } from '../common/response-contract';@@ -27,7 +27,7 @@ import {* does, so it asks the same right.*/@Controller('api/trips/:tripId/tours/wanderer')-@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard, WandererEnabledGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class ToursWandererController {constructor(diff --git a/server/src/nest/tours/tours-wanderer.mcp.ts b/server/src/nest/tours/tours-wanderer.mcp.tsindex de59be456..52fc1ae68 100644--- a/server/src/nest/tours/tours-wanderer.mcp.ts+++ b/server/src/nest/tours/tours-wanderer.mcp.ts@@ -1,3 +1,4 @@+import { ADDON_IDS } from '../../addons';import { noAccess, permissionDenied } from '../../mcp/tools/_shared';import {McpController,@@ -7,7 +8,7 @@ import {ok,type McpContext,} from '../../nest-mcp';-import type { HasAddons } from '../addons/addon-gate';+import { addonGate, gateOnAddons } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';import { TripAccessService } from '../trip-membership/trip-access.service';@@ -24,8 +25,16 @@ import {type WandererMcpSourceRequest,} from '@trek/shared';-/** Offered only while the admin allows wanderer under Tours, as WandererEnabledGuard lets its routes through. */-const wandererOn = (_ctx: McpContext, self: HasAddons): Promise<boolean> => self.addons.isWandererAvailable();+const toursOn = addonGate(ADDON_IDS.TOURS);++/**+ * Offered only while the admin allows wanderer under Tours, as WandererEnabledGuard lets its routes through,+ * and Tours is on for the instance or a trip of the caller. Each call also needs Tours on for the trip it names.+ */+const wandererOn = gateOnAddons(+ [ADDON_IDS.TOURS],+ async (ctx, self) => (await self.addons.isWandererAllowed()) && (await toursOn(ctx, self)),+);/*** The trip-side wanderer routes over MCP (ToursWandererController): thediff --git a/server/src/nest/tours/tours.controller.ts b/server/src/nest/tours/tours.controller.tsindex bff97335a..8c37ca57a 100644--- a/server/src/nest/tours/tours.controller.ts+++ b/server/src/nest/tours/tours.controller.ts@@ -1,7 +1,7 @@import { ADDON_IDS } from '../../addons';import type { User } from '../../types';-import { AddonGuard } from '../addons/addon.guard';import { RequireAddon } from '../addons/require-addon.decorator';+import { TripAddonGuard } from '../addons/trip-addon.guard';import { CurrentUser } from '../auth-core/current-user.decorator';import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';import { contentDisposition } from '../common/content-disposition';@@ -27,7 +27,7 @@ import type { Response } from 'express';* ToursImportController, which checks the same rules in its handler.*/@Controller('api/trips/:tripId/tours')-@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)+@UseGuards(JwtAuthGuard, TripAccessGuard, TripAddonGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class ToursController {constructor(diff --git a/server/src/nest/tours/wanderer-watch.controller.ts b/server/src/nest/tours/wanderer-watch.controller.tsindex 6130e9128..cfa85a45d 100644--- a/server/src/nest/tours/wanderer-watch.controller.ts+++ b/server/src/nest/tours/wanderer-watch.controller.ts@@ -18,10 +18,12 @@ import type { Request } from 'express';* `/api/integrations/wanderer/watch` (WAN-02): the optional background watch* over the caller's own wanderer snapshots, beside the connection it runs on.* It reads and switches only the caller's own watch, and lists only the- * caller's own hints.+ * caller's own hints. It belongs to no one trip, so AddonGuard follows+ * JwtAuthGuard and opens while Tours is on for the instance or any trip of+ * the caller.*/@Controller('api/integrations/wanderer/watch')-@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard)+@UseGuards(JwtAuthGuard, AddonGuard, WandererEnabledGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class WandererWatchController {constructor(private readonly watch: WandererWatchService) {}diff --git a/server/src/nest/trip-read-model/trip-read-model.module.ts b/server/src/nest/trip-read-model/trip-read-model.module.tsindex 3f402b9c2..08d535cbf 100644--- a/server/src/nest/trip-read-model/trip-read-model.module.ts+++ b/server/src/nest/trip-read-model/trip-read-model.module.ts@@ -1,5 +1,6 @@import { Trips } from '../../db/entities/Trips.entity';import { AccommodationsModule } from '../accommodations/accommodations.module';+import { AddonsModule } from '../addons/addons.module';import { BudgetModule } from '../budget/budget.module';import { CollabModule } from '../collab/collab.module';import { DaysModule } from '../days/days.module';@@ -33,6 +34,7 @@ import { Module } from '@nestjs/common';PlacesModule,TodoModule,FilesModule,+ AddonsModule,],providers: [TripReadModelService],exports: [TripReadModelService],diff --git a/server/src/nest/trip-read-model/trip-read-model.service.ts b/server/src/nest/trip-read-model/trip-read-model.service.tsindex 422dd5249..9b3773d75 100644--- a/server/src/nest/trip-read-model/trip-read-model.service.ts+++ b/server/src/nest/trip-read-model/trip-read-model.service.ts@@ -1,6 +1,8 @@+import { ADDON_IDS } from '../../addons';import { Trips } from '../../db/entities/Trips.entity';import type { TripsRepository } from '../../db/repositories/Trips.repository';import { AccommodationsService } from '../accommodations/accommodations.service';+import { AddonsService } from '../addons/addons.service';import { BudgetService } from '../budget/budget.service';import { CollabService } from '../collab/collab.service';import { DaysService } from '../days/days.service';@@ -37,6 +39,7 @@ export class TripReadModelService {private readonly places: PlacesService,private readonly todo: TodoService,private readonly files: FilesService,+ private readonly addons: AddonsService,) {}// ── Trip summary (used by MCP get_trip_summary tool) ──────────────────────@@ -99,21 +102,30 @@ export class TripReadModelService {// ── Bundle / notifications (route helpers) ────────────────────────────────- /** Aggregates every trip sub-collection for offline caching (legacy /:id/bundle). */- async bundle(tripId: string, trip: { user_id: number }, viewerId: number) {+ /**+ * Aggregates every trip sub-collection for offline caching (legacy /:id/bundle).+ *+ * A section whose addon is off for this trip (Lists for packing and todos,+ * Costs, Documents) goes out as an empty list rather than being left out, so+ * a client that replaces its cache from the bundle drops what it may no+ * longer show, and one that expects every key still finds it.+ */+ async bundle(tripId: string, trip: { id: number; user_id: number }, viewerId: number) {const { days } = await this.days.list(tripId);const { owner, members } = await this.members.listMembers(tripId, trip.user_id);+ const on = async (addonId: string) => this.addons.isEnabledForTrip(trip.id, addonId);+ const packingOn = await on(ADDON_IDS.PACKING);return {trip,days,places: await this.places.list(String(tripId), {}),// Scope to the requesting member so other members' private packing items// (#858) never land in this viewer's offline cache.- packingItems: await this.packing.listItems(tripId, viewerId),- todoItems: await this.todo.listItems(tripId),- budgetItems: await this.budget.listBudgetItems(tripId),+ packingItems: packingOn ? await this.packing.listItems(tripId, viewerId) : [],+ todoItems: packingOn ? await this.todo.listItems(tripId) : [],+ budgetItems: (await on(ADDON_IDS.BUDGET)) ? await this.budget.listBudgetItems(tripId) : [],reservations: await this.reservations.list(tripId),- files: await this.files.listFiles(tripId, false),+ files: (await on(ADDON_IDS.DOCUMENTS)) ? await this.files.listFiles(tripId, false) : [],accommodations: await this.accommodations.list(tripId),members: [owner, ...(members || [])].filter(Boolean),};diff --git a/server/src/nest/trips/trip-prompts.mcp.ts b/server/src/nest/trips/trip-prompts.mcp.tsindex 8b4a10432..8d7fd2e07 100644--- a/server/src/nest/trips/trip-prompts.mcp.ts+++ b/server/src/nest/trips/trip-prompts.mcp.ts@@ -1,6 +1,7 @@import { ADDON_IDS } from '../../addons';import { McpController, Prompt, type McpContext } from '../../nest-mcp';import { addonGate } from '../addons/addon-gate';+import { addonOffMessage } from '../addons/addons.constants';import { AddonsService } from '../addons/addons.service';import { tripIdPromptArg } from '../mcp-shared/prompt-args';import { PackingService } from '../packing/packing.service';@@ -10,6 +11,12 @@ import { TripsService } from './trips.service';const budgetAddonOn = addonGate(ADDON_IDS.BUDGET);const packingAddonOn = addonGate(ADDON_IDS.PACKING);+/** A prompt's answer while its addon is off for the trip it names. */+function addonOffPrompt(addonId: string) {+ const text = `${addonOffMessage(addonId)}.`;+ return { messages: [{ role: 'user' as const, content: { type: 'text' as const, text } }] };+}+/*** The two cross-domain prompts, relocated from budget.mcp.ts / packing.mcp.ts* (where the 1:1 port from src/mcp/tools/prompts.ts had left them). Both read@@ -47,6 +54,7 @@ export class TripPromptsMcp {],};}+ if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.BUDGET))) return addonOffPrompt(ADDON_IDS.BUDGET);const summary = await this.readModel.getTripSummary(tripId, ctx.userId);if (!summary) {return { messages: [{ role: 'user' as const, content: { type: 'text' as const, text: 'Trip not found.' } }] };@@ -105,6 +113,7 @@ export class TripPromptsMcp {],};}+ if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.PACKING))) return addonOffPrompt(ADDON_IDS.PACKING);// Hide other members' private items (#858) from the requesting user.const items = await this.packing.listItems(tripId, ctx.userId);if (!items.length) {diff --git a/server/src/nest/trips/trips.controller.ts b/server/src/nest/trips/trips.controller.tsindex 199239fee..0f30e4106 100644--- a/server/src/nest/trips/trips.controller.ts+++ b/server/src/nest/trips/trips.controller.ts@@ -336,7 +336,7 @@ export class TripsController {@Get(':id/bundle')async bundle(@CurrentUser() user: User, @Param('id') id: string) {- const trip = (await this.trips.get(id, user.id)) as { user_id: number } | undefined;+ const trip = (await this.trips.get(id, user.id)) as { id: number; user_id: number } | undefined;if (!trip) {throw new HttpException({ error: 'Trip not found' }, 404);}diff --git a/server/src/nest/trips/trips.mcp.ts b/server/src/nest/trips/trips.mcp.tsindex 568bd3b06..b18b67a3a 100644--- a/server/src/nest/trips/trips.mcp.ts+++ b/server/src/nest/trips/trips.mcp.ts@@ -432,10 +432,10 @@ export class TripsMcp {const summary = await this.readModel.getTripSummary(tripId, ctx.userId);if (!summary) return noAccess();const R = canReadTrips(ctx.scopes);- // Addon availability gates- const packingEnabled = await this.addons.isAddonEnabled(ADDON_IDS.PACKING);- const budgetEnabled = await this.addons.isAddonEnabled(ADDON_IDS.BUDGET);- const collabEnabled = await this.addons.isAddonEnabled(ADDON_IDS.COLLAB);+ // Addon availability gates, as they apply to this trip+ const packingEnabled = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.PACKING);+ const budgetEnabled = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.BUDGET);+ const collabEnabled = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.COLLAB);const collabFeatures = collabEnabled ? await this.addons.getCollabFeatures() : null;// Scope gates — sections not covered by the client's OAuth scopes are omitted.// Core trip data (metadata, days, members, accommodations) is always included@@ -781,15 +781,21 @@ export class TripsMcp {}const { trip, days, members, budget, packing, reservations, collab_notes } = summary as any;const memberList = [members?.owner, ...(members?.collaborators || [])].filter(Boolean);+ // A section whose addon is off for this trip is left out, as get_trip_summary leaves it out.+ const [packingOn, budgetOn, collabOn] = await Promise.all(+ [ADDON_IDS.PACKING, ADDON_IDS.BUDGET, ADDON_IDS.COLLAB].map((id) => this.addons.isEnabledForTrip(tripId, id)),+ );+ const sections = [+ packingOn ? `Packing: ${packing?.checked || 0}/${packing?.total || 0} items packed\n` : '',+ budgetOn ? `Budget: ${budget?.total || 0} ${trip?.currency || 'EUR'} total\n` : '',+ ].join('');+ const notes = collabOn ? `Collab Notes: ${collab_notes?.length || 0}\n` : '';const text = `Trip: ${trip?.title || 'Untitled'}${trip?.description ? `\n${trip.description}` : ''}Dates: ${trip?.start_date || '?'} to ${trip?.end_date || '?'}Members: ${memberList.length} (${memberList.map((m: any) => m.name || m.email).join(', ') || 'none'})Days: ${days?.length || 0}-Packing: ${packing?.checked || 0}/${packing?.total || 0} items packed-Budget: ${budget?.total || 0} ${trip?.currency || 'EUR'} total-Reservations: ${reservations?.length || 0}-Collab Notes: ${collab_notes?.length || 0}-${days?.map((d: any, i: number) => `Day ${i + 1} (${d.date}): ${d.assignments?.length || 0} places${d.title ? ` - ${d.title}` : ''}`).join('\n') || 'No days yet'}`;+${sections}Reservations: ${reservations?.length || 0}+${notes}${days?.map((d: any, i: number) => `Day ${i + 1} (${d.date}): ${d.assignments?.length || 0} places${d.title ? ` - ${d.title}` : ''}`).join('\n') || 'No days yet'}`;return {description: `Summary of trip "${trip?.title || tripId}"`,messages: [{ role: 'user' as const, content: { type: 'text' as const, text } }],diff --git a/server/src/nest/trips/trips.service.ts b/server/src/nest/trips/trips.service.tsindex 6ae0bf753..d6d7f0bd8 100644--- a/server/src/nest/trips/trips.service.ts+++ b/server/src/nest/trips/trips.service.ts@@ -47,6 +47,7 @@ import { VacayService } from '../vacay/vacay.service';import { UnsplashService } from '../unsplash/unsplash.service';import { StorageReleaseService } from '../storage/storage-release.service';import { SettingsService } from '../settings/settings.service';+import { TripAddonsService } from '../addons/trip-addons.service';import { escapeLikePattern } from '../places/places.helpers';import { NotFoundError, ValidationError } from '../common/domain-errors';import { inOrder } from '../common/in-order';@@ -128,6 +129,7 @@ export class TripsService {// .forRoot`'s core module), so no module needs new wiring.private readonly em: EntityManager,private readonly settings: SettingsService,+ private readonly tripAddons: TripAddonsService, // the owner's per-trip addon switches travel with a copy) {}// Plan 3c Task 7: the raw better-sqlite3 handle used to back `remove`'s@@ -755,6 +757,7 @@ export class TripsService {await this.roadtripPreferencesRepo.upsertValue(newTripId, pref.key, pref.value); // TP50}+ await this.tripAddons.copyOverrides(Number(sourceTripId), newTripId); // the trip addons switched on or off for the tripconst oldBoundaries = await this.roadtripDayBoundariesRepo.listForTrip(Number(sourceTripId)); // TP51for (const boundary of oldBoundaries) {const from = assignmentMap.get(boundary.from_assignment_id);diff --git a/server/src/nest/wanderer/wanderer-enabled.guard.ts b/server/src/nest/wanderer/wanderer-enabled.guard.tsindex 5de4c1f92..581fe7a28 100644--- a/server/src/nest/wanderer/wanderer-enabled.guard.ts+++ b/server/src/nest/wanderer/wanderer-enabled.guard.ts@@ -5,14 +5,17 @@ import { CanActivate, Injectable } from '@nestjs/common';/*** Lets a wanderer route through only while the admin allows wanderer under* Tours (Admin, Addons, Tours). Runs after the Tours addon check, so with- * Tours off the caller still hears that Tours is off.+ * Tours off the caller still hears that Tours is off. That check decides+ * Tours (AddonGuard for the instance or any trip of the caller, TripAddonGuard+ * for one trip), so this guard asks the sub-option alone: it stays+ * instance-wide and applies wherever Tours is on.*/@Injectable()export class WandererEnabledGuard implements CanActivate {constructor(private readonly addons: AddonsService) {}async canActivate(): Promise<boolean> {- if (!(await this.addons.isWandererAvailable())) {+ if (!(await this.addons.isWandererAllowed())) {throw new DomainError(404, 'wanderer is not enabled', {code: 'wanderer_disabled',details: { code: 'disabled' },diff --git a/server/src/nest/wanderer/wanderer.controller.ts b/server/src/nest/wanderer/wanderer.controller.tsindex 9ce5ee0d1..b02ee7381 100644--- a/server/src/nest/wanderer/wanderer.controller.ts+++ b/server/src/nest/wanderer/wanderer.controller.ts@@ -24,9 +24,12 @@ import type { Request } from 'express';* to the Tours addon, which is what it feeds, and only ever touches the* caller's own row. The test answers 200 with the reason in the body, since a* form showing someone their own typo needs a field to render, not an error.+ *+ * AddonGuard runs after JwtAuthGuard: the connection belongs to no one trip, so+ * it opens while Tours is on for the instance or for any trip of the caller.*/@Controller('api/integrations/wanderer')-@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard)+@UseGuards(JwtAuthGuard, AddonGuard, WandererEnabledGuard)@RequireAddon(ADDON_IDS.TOURS, 'Tours')export class WandererController {constructor(private readonly wanderer: WandererService) {}diff --git a/server/tests/e2e/addons.e2e.test.ts b/server/tests/e2e/addons.e2e.test.tsindex 90a7d33ff..b0491c2d8 100644--- a/server/tests/e2e/addons.e2e.test.ts+++ b/server/tests/e2e/addons.e2e.test.ts@@ -138,6 +138,8 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {toursWanderer: false,toursHikingMap: false,toursCycleMap: false,+ // The options themselves, which apply wherever a trip switched Tours on.+ toursOptions: { wanderer: false, hikingMap: true, cycleMap: true },addons: [{ id: 'packing', name: 'Packing', type: 'trip', icon: 'Backpack', enabled: true },{ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true },diff --git a/server/tests/e2e/doc-sync.e2e.test.ts b/server/tests/e2e/doc-sync.e2e.test.tsindex ae4a11698..0f729bdf1 100644--- a/server/tests/e2e/doc-sync.e2e.test.ts+++ b/server/tests/e2e/doc-sync.e2e.test.ts@@ -62,7 +62,11 @@ vi.mock('../../src/db/database', async () => {};});-const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));+const { isAddonEnabled, isEnabledForTrip } = vi.hoisted(() => ({+ isAddonEnabled: vi.fn(() => true),+ // What the owner chose for Documents on the trip; the instance switch above still has to be on.+ isEnabledForTrip: vi.fn(async () => true),+}));/*** The SSRF guard resolves DNS, and `paperless.example.com` does not exist. In@@ -147,7 +151,7 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DocSyncModule],}).overrideProvider(AddonsService)- .useValue({ isAddonEnabled });+ .useValue({ isAddonEnabled, isEnabledForTrip });const fakes = providers.map(([, id]) => fakeProvider(id));providers.forEach(([token], i) => {builder = builder.overrideProvider(token).useValue(fakes[i]);@@ -185,6 +189,16 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>beforeEach(() => {isAddonEnabled.mockReturnValue(true);+ isEnabledForTrip.mockResolvedValue(true);+ });++ it('answers 404 to a member of a trip that has Documents off for itself, the instance on', async () => {+ isEnabledForTrip.mockResolvedValue(false);+ const res = await request(server)+ .get(`/api/trips/${tripId}/docsync/status`)+ .set('Cookie', sessionCookie(ownerId))+ .expect(404);+ expect(res.body).toEqual({ error: 'Documents addon is not enabled' });});it('answers 404 rather than 401 when the addon is off, to everyone alike', async () => {diff --git a/server/tests/e2e/files.e2e.test.ts b/server/tests/e2e/files.e2e.test.tsindex f9fb07608..6f994168c 100644--- a/server/tests/e2e/files.e2e.test.ts+++ b/server/tests/e2e/files.e2e.test.ts@@ -61,6 +61,13 @@ const { db } = vi.hoisted(() => {// StorageRegistryService (behind StorageModule, now in this module chain) reads// this at onModuleInit.tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');+ // Documents is a trip addon: every files route asks whether it applies to its trip+ // (the trip's own choice, else the instance switch), so both tables are here, Documents on.+ tmp.exec(`CREATE TABLE addons (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, type TEXT DEFAULT 'global',+ icon TEXT, enabled INTEGER DEFAULT 0, config TEXT DEFAULT '{}', sort_order INTEGER DEFAULT 0);`);+ tmp.exec("INSERT INTO addons (id, name, type, enabled) VALUES ('documents', 'Documents', 'trip', 1);");+ tmp.exec(`CREATE TABLE trip_addon_overrides (trip_id INTEGER NOT NULL, addon_id TEXT NOT NULL, enabled INTEGER NOT NULL,+ updated_at TEXT, PRIMARY KEY (trip_id, addon_id));`);return { db: tmp };});diff --git a/server/tests/e2e/paddle-obstacles.e2e.test.ts b/server/tests/e2e/paddle-obstacles.e2e.test.tsindex 4d4643bc2..edd85f635 100644--- a/server/tests/e2e/paddle-obstacles.e2e.test.ts+++ b/server/tests/e2e/paddle-obstacles.e2e.test.ts@@ -176,12 +176,14 @@ afterAll(async () => {});describe('GET /api/paddle/obstacles', () => {- it('PADE2E-001: 404 while Tours is off, ahead of the session check; 401 without a cookie once on', async () => {+ it('PADE2E-001: 404 while Tours is off for the caller; 401 without a cookie, whatever Tours says', async () => {+ // The obstacles belong to no one trip: Tours opens them for a caller one of whose trips has it on,+ // so the addon is asked once the session says who is asking.await setAddonEnabled(orm, 'tours', false);- for (const res of [await obstacles(BOX), await obstacles(BOX, USER)]) {- expect(res.status).toBe(404);- expect(res.body).toEqual({ error: 'Tours addon is not enabled' });- }+ const off = await obstacles(BOX, USER);+ expect(off.status).toBe(404);+ expect(off.body).toEqual({ error: 'Tours addon is not enabled' });+ expect((await obstacles(BOX)).status).toBe(401);await setAddonEnabled(orm, 'tours', true);const anonymous = await obstacles(BOX);expect(anonymous.status).toBe(401);diff --git a/server/tests/e2e/roadtrip.e2e.test.ts b/server/tests/e2e/roadtrip.e2e.test.tsindex 9b5c4c70b..92983d928 100644--- a/server/tests/e2e/roadtrip.e2e.test.ts+++ b/server/tests/e2e/roadtrip.e2e.test.ts@@ -387,12 +387,13 @@ describe('Roadtrip e2e (real guard chain + temp SQLite)', () => {}});- it('ROADTRIP-E2E-002: a disabled addon owes an anonymous caller a 404, not a 401', async () => {- // The gate leads the chain for this reason: a 401 tells a stranger the- // route exists. Both answers refuse; only one of them says nothing.+ it('ROADTRIP-E2E-002: with the addon off an anonymous caller gets the 401 every trip route answers', async () => {+ // Whether Road trip applies is the trip's own choice now (a trip may switch it on while the+ // instance has it off), and only somebody who may see the trip learns it, so the addon gate+ // follows the auth and trip guards and an anonymous caller hears what it hears on any trip route.await setAddon(false);const res = await request(server).get('/api/trips/5/roadtrip/vias');- expect(res.status).toBe(404);+ expect(res.status).toBe(401);});it('ROADTRIP-E2E-003: with the addon on, an anonymous caller gets 401', async () => {diff --git a/server/tests/e2e/route-row-ids.e2e.test.ts b/server/tests/e2e/route-row-ids.e2e.test.tsindex 67318b45e..78217a8da 100644--- a/server/tests/e2e/route-row-ids.e2e.test.ts+++ b/server/tests/e2e/route-row-ids.e2e.test.ts@@ -79,6 +79,7 @@ const NOT_ROW_IDS: Record<string, string> = {'* /api/plugin-settings/ :id': 'a plugin id is its manifest slug','* /api/oauth/clients/ :id': 'an OAuth client row id is a generated text key','PUT /api/admin/addons/:id :id': 'an addon id is its key',+ 'PUT /api/trips/:tripId/addons/:addonId :addonId': 'an addon id is its key','GET /api/maps/place-photo/:placeId :placeId': 'a maps provider place id is a provider string','* /api/ :toolCallId': "an assistant tool call id is the model's string",};diff --git a/server/tests/e2e/tours-activity-stats.e2e.test.ts b/server/tests/e2e/tours-activity-stats.e2e.test.tsindex 39b92efda..1b022701c 100644--- a/server/tests/e2e/tours-activity-stats.e2e.test.ts+++ b/server/tests/e2e/tours-activity-stats.e2e.test.ts@@ -12,6 +12,7 @@ import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipimport { Days } from '../../src/db/entities/Days.entity';import { Places } from '../../src/db/entities/Places.entity';import { TourActivityExclusions } from '../../src/db/entities/TourActivityExclusions.entity';+import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';import { Trips } from '../../src/db/entities/Trips.entity';import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';@@ -22,7 +23,7 @@ import { ToursModule } from '../../src/nest/tours/tours.module';import { createSnapshotTestDb } from '../helpers/db-mock';import { makeDayAssignment } from '../helpers/factories/itinerary';import { countRows, deleteRows, insertRow, insertRows } from '../helpers/factories/rows';-import { setAddonEnabled } from '../helpers/factories/settings';+import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';import { addTripMember } from '../helpers/factories/trips';import { makeUser } from '../helpers/factories/users';import { FakeRealtimeService } from '../helpers/fake-realtime';@@ -218,6 +219,24 @@ describe('Tour activity stats e2e (STA-02)', () => {expect(off.body).toEqual({ error: 'Tours addon is not enabled' });});+ it('STA2-E2E-006: a trip with Tours off adds nothing to the sums and its tours cannot be left out, data kept', async () => {+ const ridge = await tourOnDay('Ridge', 3);+ await setTripAddon(orm, TRIP, 'tours', false);+ try {+ const off = await request(server).get(STATS).set(as(OWNER));+ expect(off.status).toBe(200);+ expect(off.body).toEqual({ entries: [], uncounted: { unassigned: 0, undated: 0 } });+ const left = await exclude({ place_id: ridge.placeId, excluded: true });+ expect(left.status).toBe(404);+ expect(left.body).toEqual({ error: 'Tour not found' });+ expect(await countRows(orm, TourActivityExclusions)).toBe(0);+ } finally {+ await deleteRows(orm, TripAddonOverrides);+ }+ const back = await request(server).get(STATS).set(as(OWNER));+ expect(back.body.entries.map((entry: { place_id: number }) => entry.place_id)).toEqual([ridge.placeId]);+ });+it('STA2-E2E-005: a tour on two days counts once, dated on the last of them', async () => {const ridge = await tourOnDay('Ridge', 3);await makeDayAssignment(orm, 4, ridge.placeId);diff --git a/server/tests/e2e/tours-planned.e2e.test.ts b/server/tests/e2e/tours-planned.e2e.test.tsindex b0956b489..af8ff7376 100644--- a/server/tests/e2e/tours-planned.e2e.test.ts+++ b/server/tests/e2e/tours-planned.e2e.test.ts@@ -11,6 +11,7 @@import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';import { Places } from '../../src/db/entities/Places.entity';import { Tours } from '../../src/db/entities/Tours.entity';+import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';import { Trips } from '../../src/db/entities/Trips.entity';import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';@@ -23,7 +24,7 @@ import { ToursModule } from '../../src/nest/tours/tours.module';import { createSnapshotTestDb } from '../helpers/db-mock';import { makePlace } from '../helpers/factories/places';import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';-import { setAddonEnabled } from '../helpers/factories/settings';+import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';import { makeTour } from '../helpers/factories/tours';import { addTripMember } from '../helpers/factories/trips';import { makeUser } from '../helpers/factories/users';@@ -660,6 +661,30 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {expect(await countRows(orm, Places, { trip: 7 })).toBe(before);});+ it('a trip with Tours off is out of the library: not listed, previewed or taken over, its tours kept', async () => {+ const ridge = await createViaApi(5);+ await createViaApi(6, tourBody({ name: 'Valley walk' }));+ await setTripAddon(orm, 5, 'tours', false);+ try {+ const all = await request(server).get('/api/tours/library').set('Cookie', sessionCookie(OWNER));+ expect(all.body.tours.map((tour: { name: string }) => tour.name)).toEqual(['Valley walk']);+ expect(all.body.trips).toEqual([{ id: 6, title: 'Other', tour_count: 1 }]);+ const named = await request(server).get('/api/tours/library?trip_id=5').set('Cookie', sessionCookie(OWNER));+ expect(named.body.tours).toEqual([]);+ const preview = await request(server).get(`/api/tours/library/${ridge}`).set('Cookie', sessionCookie(OWNER));+ expect(preview.status).toBe(404);+ const taken = await request(server)+ .post('/api/trips/6/tours/take-over')+ .set('Cookie', sessionCookie(OWNER))+ .send({ source_trip_id: 5, source_place_id: ridge });+ expect(taken.status).toBe(404);+ expect(taken.body).toEqual({ error: 'Tour not found' });+ } finally {+ await deleteRows(orm, TripAddonOverrides);+ }+ expect(await findRow(orm, Places, { id: ridge })).toMatchObject({ trip_id: 5 });+ });+it('needs place_edit on the trip it writes into, the addon on, a session and a well-formed body', async () => {const source = await createViaApi(6);const viewer = await request(server)diff --git a/server/tests/e2e/trip-addons-enforcement.e2e.test.ts b/server/tests/e2e/trip-addons-enforcement.e2e.test.tsnew file mode 100644index 000000000..16358f74e--- /dev/null+++ b/server/tests/e2e/trip-addons-enforcement.e2e.test.ts@@ -0,0 +1,329 @@+/**+ * Per-trip addons, enforced: what a trip's own choice does to the surfaces of+ * its addons, end to end on the whole app (buildApp, the real guards, the+ * response contract check, the MCP registry with the host's tool gate).+ *+ * Every surface is held both ways: the instance has the addon off and the+ * trip switched it on (allowed), and the instance has it on and the trip+ * switched it off (refused with `<Label> addon is not enabled`, data kept).+ * A trip without a choice follows the instance, so the instance switch now+ * closes the lists, costs, collab and files routes too.+ */+import { buildApp } from '../../src/bootstrap';+import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';+import { Reservations } from '../../src/db/entities/Reservations.entity';+import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';+import { withRequestContext } from '../../src/nest/database/request-context';+import { makeBudgetItem } from '../helpers/factories/budget';+import { makeCollabNote } from '../helpers/factories/collab';+import { makeTripFile } from '../helpers/factories/files';+import { makePackingItem } from '../helpers/factories/packing';+import { countRows } from '../helpers/factories/rows';+import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';+import { makeTodoItem } from '../helpers/factories/todos';+import { addTripMember, makeShareToken, makeTrip } from '../helpers/factories/trips';+import { makeUser } from '../helpers/factories/users';+import { oneByOne } from '../helpers/one-by-one';+import { resetDatabase } from '../helpers/reset-database';+import { sessionCookie } from './harness';+import { MikroORM } from '@mikro-orm/core';+import { Client } from '@modelcontextprotocol/sdk/client/index';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';+import type { INestApplication } from '@nestjs/common';++import request from 'supertest';+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';++let app: INestApplication;+let orm: MikroORM;++beforeAll(async () => {+ app = await buildApp();+ orm = app.get(MikroORM);+}, 60_000);+beforeEach(async () => {+ await resetDatabase(orm);+});+afterAll(async () => {+ await app?.close();+});++const TRIP_ADDONS = ['packing', 'budget', 'documents', 'collab', 'roadtrip', 'tours'];++/**+ * Every trip addon on for the instance, an owner with two trips, a member on+ * the first, and a stranger; each trip holds a row of every addon.+ */+async function world() {+ await Promise.all(TRIP_ADDONS.map((addonId) => setAddonEnabled(orm, addonId, true)));+ const { user: owner } = await makeUser(orm);+ const { user: member } = await makeUser(orm);+ const { user: stranger } = await makeUser(orm);+ const chosen = await makeTrip(orm, owner.id, { title: 'Chosen' });+ const plain = await makeTrip(orm, owner.id, { title: 'Plain' });+ await addTripMember(orm, chosen.id, member.id, owner.id);+ await Promise.all(+ [chosen.id, plain.id].map(async (tripId) => {+ await makePackingItem(orm, tripId, { name: 'Tent' });+ await makeTodoItem(orm, tripId, { name: 'Book ferry' });+ await makeBudgetItem(orm, tripId, { name: 'Hotel' });+ await makeCollabNote(orm, tripId, owner.id, { title: 'Ideas' });+ await makeTripFile(orm, tripId, { original_name: 'ticket.pdf' });+ }),+ );+ return { owner, member, stranger, chosen, plain };+}++const get = (userId: number | null, path: string) => {+ const req = request(app.getHttpServer()).get(path);+ return userId === null ? req : req.set('Cookie', sessionCookie(userId));+};++/** One read route per trip addon whose REST surface had no addon check before. */+const ROUTES: ReadonlyArray<[string, string, (tripId: number) => string]> = [+ ['packing', 'Packing', (id) => `/api/trips/${id}/packing`],+ ['packing', 'Packing', (id) => `/api/trips/${id}/todo`],+ ['budget', 'Costs', (id) => `/api/trips/${id}/budget`],+ ['collab', 'Collab', (id) => `/api/trips/${id}/collab/notes`],+ ['documents', 'Documents', (id) => `/api/trips/${id}/files`],+ ['roadtrip', 'Road trip', (id) => `/api/trips/${id}/roadtrip/vias`],+ ['tours', 'Tours', (id) => `/api/trips/${id}/tours`],+];++describe('trip-scoped REST', () => {+ it.each(ROUTES)(+ 'TRIPADDON-ENF-001: %s at %s: a trip that switched it off answers 404 while the instance has it on',+ async (addonId, label, path) => {+ const { owner, member, chosen, plain } = await world();+ await setAddonEnabled(orm, addonId, true);+ await setTripAddon(orm, chosen.id, addonId, false);+ const [own, asMember, other] = await oneByOne(+ [+ () => get(owner.id, path(chosen.id)),+ () => get(member.id, path(chosen.id)),+ () => get(owner.id, path(plain.id)),+ ],+ (send) => send(),+ );+ expect(own.status).toBe(404);+ expect(own.body).toEqual({ error: `${label} addon is not enabled` });+ expect(asMember.status).toBe(404);+ expect(other.status).toBe(200);+ },+ );++ it.each(ROUTES)(+ 'TRIPADDON-ENF-002: %s at %s: a trip that switched it on answers while the instance has it off, the others 404',+ async (addonId, label, path) => {+ const { owner, member, chosen, plain } = await world();+ await setAddonEnabled(orm, addonId, false);+ await setTripAddon(orm, chosen.id, addonId, true);+ const [own, asMember, other] = await oneByOne(+ [+ () => get(owner.id, path(chosen.id)),+ () => get(member.id, path(chosen.id)),+ () => get(owner.id, path(plain.id)),+ ],+ (send) => send(),+ );+ expect(own.status).toBe(200);+ expect(asMember.status).toBe(200);+ expect(other.status).toBe(404);+ expect(other.body).toEqual({ error: `${label} addon is not enabled` });+ },+ );++ it('TRIPADDON-ENF-003: a stranger hears "Trip not found" and nobody signed in a 401, whatever the trip chose', async () => {+ const { stranger, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'budget', false);+ const [unseen, anonymous] = await oneByOne(+ [() => get(stranger.id, `/api/trips/${chosen.id}/budget`), () => get(null, `/api/trips/${chosen.id}/budget`)],+ (send) => send(),+ );+ expect(unseen.status).toBe(404);+ expect(unseen.body).toEqual({ error: 'Trip not found' });+ expect(anonymous.status).toBe(401);+ });++ it('TRIPADDON-ENF-004: the multipart upload refuses in its handler, so the caller reads the 404 body', async () => {+ const { owner, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'documents', false);+ const res = await request(app.getHttpServer())+ .post(`/api/trips/${chosen.id}/files`)+ .set('Cookie', sessionCookie(owner.id))+ .attach('file', Buffer.from('%PDF-1.4 test'), 'ticket.pdf');+ expect(res.status).toBe(404);+ expect(res.body).toEqual({ error: 'Documents addon is not enabled' });+ });++ it('TRIPADDON-ENF-005: switching back on brings every row back where it was', async () => {+ const { owner, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'packing', false);+ expect((await get(owner.id, `/api/trips/${chosen.id}/packing`)).status).toBe(404);+ await setTripAddon(orm, chosen.id, 'packing', true);+ const res = await get(owner.id, `/api/trips/${chosen.id}/packing`);+ expect(res.status).toBe(200);+ expect((res.body.items as Array<{ name: string }>).map((item) => item.name)).toEqual(['Tent']);+ });+});++describe('routes about no one trip', () => {+ it('TRIPADDON-ENF-010: the tour library opens for a user one of whose trips switched Tours on', async () => {+ const { owner, member, stranger, chosen } = await world();+ await setAddonEnabled(orm, 'tours', false);+ expect((await get(owner.id, '/api/tours/library')).status).toBe(404);+ await setTripAddon(orm, chosen.id, 'tours', true);+ const [own, asMember, other] = await oneByOne(+ [+ () => get(owner.id, '/api/tours/library'),+ () => get(member.id, '/api/tours/library'),+ () => get(stranger.id, '/api/tours/library'),+ ],+ (send) => send(),+ );+ expect(own.status).toBe(200);+ expect(asMember.status).toBe(200);+ expect(other.status).toBe(404);+ expect(other.body).toEqual({ error: 'Tours addon is not enabled' });+ });++ it('TRIPADDON-ENF-011: a trip that switched Tours off closes the library for nobody while the instance has it on', async () => {+ const { owner, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'tours', false);+ expect((await get(owner.id, '/api/tours/library')).status).toBe(200);+ });+});++describe('what leaves the trip in bulk', () => {+ it('TRIPADDON-ENF-020: the offline bundle sends empty lists for the addons the trip has off', async () => {+ const { owner, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'packing', false);+ await setTripAddon(orm, chosen.id, 'documents', false);+ const res = await get(owner.id, `/api/trips/${chosen.id}/bundle`);+ expect(res.status).toBe(200);+ expect(res.body.packingItems).toEqual([]);+ expect(res.body.todoItems).toEqual([]);+ expect(res.body.files).toEqual([]);+ expect((res.body.budgetItems as Array<{ name: string }>).map((item) => item.name)).toEqual(['Hotel']);+ });++ it('TRIPADDON-ENF-021: the offline bundle carries an addon a trip switched on while the instance has it off', async () => {+ const { owner, chosen, plain } = await world();+ await setAddonEnabled(orm, 'budget', false);+ await setTripAddon(orm, chosen.id, 'budget', true);+ const [on, off] = await oneByOne(+ [() => get(owner.id, `/api/trips/${chosen.id}/bundle`), () => get(owner.id, `/api/trips/${plain.id}/bundle`)],+ (send) => send(),+ );+ expect((on.body.budgetItems as unknown[]).length).toBe(1);+ expect(off.body.budgetItems).toEqual([]);+ });++ it('TRIPADDON-ENF-022: a share link leaves out what the trip has off, whatever the link allows', async () => {+ const { owner, chosen } = await world();+ const share = await makeShareToken(orm, chosen.id, owner.id, {+ token: 'trip-addon-share',+ share_packing: 1,+ share_budget: 1,+ share_collab: 1,+ });+ await setTripAddon(orm, chosen.id, 'budget', false);+ const res = await get(null, `/api/shared/${share.token}`);+ expect(res.status).toBe(200);+ expect(res.body.permissions).toMatchObject({ share_packing: true, share_budget: false, share_collab: true });+ expect((res.body.packing as unknown[]).length).toBe(1);+ });+});++/** One MCP tool call as `userId` through a real session: its JSON, or its error text. */+async function callTool(userId: number, name: string, args: Record<string, unknown>) {+ const server = createLocalMcpServer('TREK trip addon enforcement e2e');+ const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);+ await withRequestContext(orm, () =>+ app+ .get(McpRegistryService)+ .attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),+ );+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ const client = new Client({ name: 'trip-addon-enforcement-e2e', version: '1.0.0' });+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ try {+ const listed = (await client.listTools()).tools.map((tool) => tool.name);+ if (!listed.includes(name)) return { listed: false, answer: null, error: null };+ const result = await client.callTool({ name, arguments: args });+ const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];+ const text = content[0]?.text ?? '';+ return result.isError === true+ ? { listed: true, answer: null, error: text }+ : { listed: true, answer: JSON.parse(text) as Record<string, unknown>, error: null };+ } finally {+ await client.close();+ await server.close();+ }+}++describe('MCP', () => {+ it('TRIPADDON-ENF-030: a trip that switched Lists off refuses the tool for that trip and keeps it for the others', async () => {+ const { owner, chosen, plain } = await world();+ await setTripAddon(orm, chosen.id, 'packing', false);+ const refused = await callTool(owner.id, 'list_packing_items', { tripId: chosen.id });+ expect(refused.error).toBe('Packing addon is not enabled');+ const other = await callTool(owner.id, 'list_packing_items', { tripId: plain.id });+ expect(other.error).toBeNull();+ expect(other.answer).not.toBeNull();+ });++ it('TRIPADDON-ENF-031: with the instance off a tool is offered to whoever has a trip that switched it on, for that trip', async () => {+ const { owner, stranger, chosen, plain } = await world();+ await setAddonEnabled(orm, 'packing', false);+ expect((await callTool(owner.id, 'list_packing_items', { tripId: chosen.id })).listed).toBe(false);+ await setTripAddon(orm, chosen.id, 'packing', true);+ const allowed = await callTool(owner.id, 'list_packing_items', { tripId: chosen.id });+ expect(allowed.error).toBeNull();+ const elsewhere = await callTool(owner.id, 'list_packing_items', { tripId: plain.id });+ expect(elsewhere.error).toBe('Packing addon is not enabled');+ expect((await callTool(stranger.id, 'list_packing_items', { tripId: chosen.id })).listed).toBe(false);+ });++ it('TRIPADDON-ENF-032: a trip the caller cannot see gets the tool\'s own "not found", never the addon answer', async () => {+ const { stranger, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'budget', false);+ await setTripAddon(orm, (await makeTrip(orm, stranger.id)).id, 'budget', true);+ const res = await callTool(stranger.id, 'list_settlements', { tripId: chosen.id });+ expect(res.listed).toBe(true);+ expect(res.error).not.toBe('Costs addon is not enabled');+ });++ it('TRIPADDON-ENF-033: the trip summary leaves out the sections of the addons the trip has off', async () => {+ const { owner, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'packing', false);+ await setTripAddon(orm, chosen.id, 'budget', false);+ const res = await callTool(owner.id, 'get_trip_summary', { tripId: chosen.id });+ expect(res.error).toBeNull();+ expect(res.answer).not.toHaveProperty('packing');+ expect(res.answer).not.toHaveProperty('budget');+ });+});++describe('what a booking writes into Costs', () => {+ it('TRIPADDON-ENF-040: a booking with a price on a trip with Costs off is written without its cost, REST and MCP alike', async () => {+ const { owner, chosen } = await world();+ await setTripAddon(orm, chosen.id, 'budget', false);+ const rest = await request(app.getHttpServer())+ .post(`/api/trips/${chosen.id}/reservations`)+ .set('Cookie', sessionCookie(owner.id))+ .send({ title: 'Hut night', type: 'other', create_budget_entry: { total_price: 80 } });+ expect(rest.status).toBe(201);+ const tool = await callTool(owner.id, 'create_reservation', {+ tripId: chosen.id,+ title: 'Museum',+ type: 'event',+ price: 20,+ });+ expect(tool.error).toBeNull();+ expect(await countRows(orm, Reservations, { trip: chosen.id })).toBe(2);+ // Only the cost world() made before; the trip keeps it while Costs is off.+ expect(await countRows(orm, BudgetItems, { trip: chosen.id })).toBe(1);+ });+});diff --git a/server/tests/e2e/trip-addons.e2e.test.ts b/server/tests/e2e/trip-addons.e2e.test.tsnew file mode 100644index 000000000..96f1d546b--- /dev/null+++ b/server/tests/e2e/trip-addons.e2e.test.ts@@ -0,0 +1,250 @@+/**+ * Per-trip addons end to end: GET and PUT /api/trips/:tripId/addons and the+ * MCP tools get_trip_addons and set_trip_addon on the whole app (buildApp, the+ * real guards, the response contract check, the registry with its scopes and+ * error mapper), seeded through the ORM factories.+ *+ * Who may do what: every member reads the list, only the owner changes it. A+ * member and an admin who does not own the trip get a 403, somebody who+ * cannot see the trip a 404, and nothing is written for either.+ */+import { buildApp } from '../../src/bootstrap';+import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';+import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';+import { TRIP_ADDON_NOT_FOUND, TRIP_ADDON_OWNER_ONLY } from '../../src/nest/addons/trip-addons.service';+import { withRequestContext } from '../../src/nest/database/request-context';+import { countRows } from '../helpers/factories/rows';+import { setAddonEnabled } from '../helpers/factories/settings';+import { addTripMember, makeTrip } from '../helpers/factories/trips';+import { makeAdmin, makeUser } from '../helpers/factories/users';+import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';+import { oneByOne } from '../helpers/one-by-one';+import { resetDatabase } from '../helpers/reset-database';+import { sessionCookie } from './harness';+import { MikroORM } from '@mikro-orm/core';+import { Client } from '@modelcontextprotocol/sdk/client/index';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';+import type { INestApplication } from '@nestjs/common';+import type { TripAddon } from '@trek/shared';++import request from 'supertest';+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';++let app: INestApplication;+let orm: MikroORM;+let spies: RealtimeSpies;++beforeAll(async () => {+ app = await buildApp();+ orm = app.get(MikroORM);+ spies = spyOnRealtime(app);+}, 60_000);+beforeEach(async () => {+ await resetDatabase(orm);+ spies.broadcast.mockClear();+});+afterAll(async () => {+ await app?.close();+});++/** An owner with a trip, a member on it, an admin on it, an admin off it and a stranger. */+async function world() {+ const { user: owner } = await makeUser(orm);+ const { user: member } = await makeUser(orm);+ const { user: adminMember } = await makeAdmin(orm);+ const { user: admin } = await makeAdmin(orm);+ const { user: stranger } = await makeUser(orm);+ const trip = await makeTrip(orm, owner.id, { title: 'Porto' });+ await addTripMember(orm, trip.id, member.id, owner.id);+ await addTripMember(orm, trip.id, adminMember.id, owner.id);+ return { owner, member, adminMember, admin, stranger, trip };+}++const get = (userId: number, tripId: number | string) =>+ request(app.getHttpServer()).get(`/api/trips/${tripId}/addons`).set('Cookie', sessionCookie(userId));++const put = (userId: number, tripId: number, addonId: string, body: unknown, socketId?: string) => {+ const req = request(app.getHttpServer())+ .put(`/api/trips/${tripId}/addons/${addonId}`)+ .set('Cookie', sessionCookie(userId));+ if (socketId) req.set('X-Socket-Id', socketId);+ return req.send(body as object);+};++const entry = (addons: TripAddon[], id: string) => addons.find((a) => a.id === id);++/** One MCP tool call as `userId` through a real session: its JSON or its error text. */+async function callTool(userId: number, name: string, args: Record<string, unknown>) {+ const server = createLocalMcpServer('TREK trip addons e2e');+ const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);+ await withRequestContext(orm, () =>+ app+ .get(McpRegistryService)+ .attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),+ );+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ const client = new Client({ name: 'trip-addons-e2e', version: '1.0.0' });+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ try {+ const result = await client.callTool({ name, arguments: args });+ const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];+ const text = content[0]?.text ?? '';+ if (result.isError === true) return { answer: null, error: text };+ return { answer: JSON.parse(text) as { tripId: number; addons: TripAddon[] }, error: null };+ } finally {+ await client.close();+ await server.close();+ }+}++describe('GET /api/trips/:tripId/addons', () => {+ it('TRIPADDON-E2E-001: every member reads the trip addons with their instance state', async () => {+ const { owner, member, trip } = await world();+ for (const res of await oneByOne([owner.id, member.id], (userId) => get(userId, trip.id))) {+ expect(res.status).toBe(200);+ expect(res.body.tripId).toBe(trip.id);+ const ids = (res.body.addons as TripAddon[]).map((a) => a.id);+ expect(ids).toEqual(expect.arrayContaining(['packing', 'budget', 'documents', 'collab', 'roadtrip', 'tours']));+ expect(ids).not.toContain('memories');+ for (const addon of res.body.addons as TripAddon[]) {+ expect(addon.overridden).toBe(false);+ expect(addon.enabled).toBe(addon.instanceEnabled);+ }+ }+ });++ it('TRIPADDON-E2E-002: somebody who cannot see the trip, an admin included, gets a 404; nobody signed in a 401', async () => {+ const { admin, stranger, trip } = await world();+ for (const res of await oneByOne([admin.id, stranger.id], (userId) => get(userId, trip.id))) {+ expect(res.status).toBe(404);+ expect(res.body).toEqual({ error: 'Trip not found' });+ }+ expect((await request(app.getHttpServer()).get(`/api/trips/${trip.id}/addons`)).status).toBe(401);+ });+});++describe('PUT /api/trips/:tripId/addons/:addonId', () => {+ it('TRIPADDON-E2E-010: the owner switches costs off for the trip; every other tab gets the list', async () => {+ const { owner, member, trip } = await world();+ const res = await put(owner.id, trip.id, 'budget', { enabled: false }, 'sock-owner');+ expect(res.status).toBe(200);+ expect(entry(res.body.addons, 'budget')).toMatchObject({ enabled: false, instanceEnabled: true, overridden: true });+ expect(spies.broadcast).toHaveBeenCalledWith(+ String(trip.id),+ 'tripAddons:changed',+ { addons: res.body.addons },+ 'sock-owner',+ );+ const seen = await get(member.id, trip.id);+ expect(entry(seen.body.addons, 'budget')).toMatchObject({ enabled: false, overridden: true });+ });++ it('TRIPADDON-E2E-011: a trip may switch an addon on that the instance has off', async () => {+ const { owner, trip } = await world();+ await setAddonEnabled(orm, 'roadtrip', false);+ const res = await put(owner.id, trip.id, 'roadtrip', { enabled: true });+ expect(res.status).toBe(200);+ expect(entry(res.body.addons, 'roadtrip')).toMatchObject({+ enabled: true,+ instanceEnabled: false,+ overridden: true,+ });+ });++ it('TRIPADDON-E2E-012: null goes back to the instance setting and drops the row', async () => {+ const { owner, trip } = await world();+ await put(owner.id, trip.id, 'budget', { enabled: false });+ const res = await put(owner.id, trip.id, 'budget', { enabled: null });+ expect(res.status).toBe(200);+ expect(entry(res.body.addons, 'budget')).toMatchObject({ enabled: true, overridden: false });+ expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);+ });++ it('TRIPADDON-E2E-013: a member and an admin on the trip are refused with 403; nothing is written or sent', async () => {+ const { member, adminMember, trip } = await world();+ const refused = await oneByOne([member.id, adminMember.id], (userId) =>+ put(userId, trip.id, 'budget', { enabled: false }),+ );+ for (const res of refused) {+ expect(res.status).toBe(403);+ expect(res.body).toEqual({ error: TRIP_ADDON_OWNER_ONLY });+ }+ expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);+ expect(spies.broadcast).not.toHaveBeenCalled();+ });++ it('TRIPADDON-E2E-014: an admin off the trip and a stranger get a 404', async () => {+ const { admin, stranger, trip } = await world();+ const unseen = await oneByOne([admin.id, stranger.id], (userId) =>+ put(userId, trip.id, 'budget', { enabled: false }),+ );+ for (const res of unseen) {+ expect(res.status).toBe(404);+ expect(res.body).toEqual({ error: 'Trip not found' });+ }+ expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);+ });++ it('TRIPADDON-E2E-015: an id that names no trip addon is a 404, a body that is no choice a 400', async () => {+ const { owner, trip } = await world();+ const unknown = await oneByOne(['vacay', 'memories', 'no_such_addon'], (addonId) =>+ put(owner.id, trip.id, addonId, { enabled: true }),+ );+ for (const res of unknown) {+ expect(res.status).toBe(404);+ expect(res.body).toEqual({ error: TRIP_ADDON_NOT_FOUND });+ }+ const malformed = await oneByOne([{}, { enabled: 'yes' }, { enabled: true, extra: 1 }], (body) =>+ put(owner.id, trip.id, 'budget', body),+ );+ expect(malformed.map((res) => res.status)).toEqual([400, 400, 400]);+ expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);+ });++ it('TRIPADDON-E2E-016: a copied trip keeps the switches of its source', async () => {+ const { owner, trip } = await world();+ await put(owner.id, trip.id, 'budget', { enabled: false });+ const copy = await request(app.getHttpServer())+ .post(`/api/trips/${trip.id}/copy`)+ .set('Cookie', sessionCookie(owner.id))+ .send({ title: 'Porto again' });+ expect(copy.status).toBe(201);+ const res = await get(owner.id, copy.body.trip.id as number);+ expect(entry(res.body.addons, 'budget')).toMatchObject({ enabled: false, overridden: true });+ });+});++describe('MCP get_trip_addons and set_trip_addon', () => {+ it('TRIPADDON-E2E-020: a member reads the list; somebody who cannot see the trip is told so', async () => {+ const { member, stranger, trip } = await world();+ const read = await callTool(member.id, 'get_trip_addons', { tripId: trip.id });+ expect(read.answer?.tripId).toBe(trip.id);+ expect(entry(read.answer?.addons ?? [], 'budget')).toMatchObject({ overridden: false });+ expect((await callTool(stranger.id, 'get_trip_addons', { tripId: trip.id })).error).toBe(+ 'Trip not found or access denied.',+ );+ });++ it('TRIPADDON-E2E-021: only the owner switches, with the REST refusal for anybody else', async () => {+ const { owner, member, adminMember, stranger, trip } = await world();+ const refused = await oneByOne([member.id, adminMember.id], (userId) =>+ callTool(userId, 'set_trip_addon', { tripId: trip.id, addonId: 'budget', enabled: false }),+ );+ expect(refused.map((res) => res.error)).toEqual([TRIP_ADDON_OWNER_ONLY, TRIP_ADDON_OWNER_ONLY]);+ const unseen = await callTool(stranger.id, 'set_trip_addon', {+ tripId: trip.id,+ addonId: 'budget',+ enabled: false,+ });+ expect(unseen.error).toBe('Trip not found or access denied.');+ expect(await countRows(orm, TripAddonOverrides, { trip: trip.id })).toBe(0);++ const done = await callTool(owner.id, 'set_trip_addon', { tripId: trip.id, addonId: 'budget', enabled: false });+ expect(entry(done.answer?.addons ?? [], 'budget')).toMatchObject({ enabled: false, overridden: true });+ const unknown = await callTool(owner.id, 'set_trip_addon', { tripId: trip.id, addonId: 'vacay', enabled: true });+ expect(unknown.error).toBe(TRIP_ADDON_NOT_FOUND);+ const reset = await callTool(owner.id, 'set_trip_addon', { tripId: trip.id, addonId: 'budget', enabled: null });+ expect(entry(reset.answer?.addons ?? [], 'budget')).toMatchObject({ overridden: false });+ });+});diff --git a/server/tests/helpers/factories/settings.ts b/server/tests/helpers/factories/settings.tsindex a74fd0ffe..901a7e101 100644--- a/server/tests/helpers/factories/settings.ts+++ b/server/tests/helpers/factories/settings.ts@@ -1,6 +1,7 @@import { Addons } from '../../../src/db/entities/Addons.entity';import { AppSettings } from '../../../src/db/entities/AppSettings.entity';import { Settings } from '../../../src/db/entities/Settings.entity';+import { TripAddonOverrides } from '../../../src/db/entities/TripAddonOverrides.entity';import type { FactoryOrm } from './context';import { findRow, upsertRow } from './rows';@@ -33,6 +34,15 @@ export async function setAddonEnabled(orm: FactoryOrm, addonId: string, enabled:await upsertRow(orm, Addons, { id: addonId, name: addonId, type: 'global', enabled }, ['enabled']);}+/**+ * The trip owner's choice for one trip addon on one trip, the row+ * `PUT /api/trips/:tripId/addons/:addonId` writes: on or off whatever the+ * instance says.+ */+export async function setTripAddon(orm: FactoryOrm, tripId: number, addonId: string, enabled: boolean): Promise<void> {+ await upsertRow(orm, TripAddonOverrides, { trip: tripId, addon: addonId, enabled: enabled ? 1 : 0 }, ['enabled']);+}+/** Collab's chat, notes, polls, links and next-up panels are opt-out app settings, not addon rows. */export async function setCollabFeature(orm: FactoryOrm,diff --git a/server/tests/helpers/notifications.ts b/server/tests/helpers/notifications.tsindex f7b6ce307..e3c748858 100644--- a/server/tests/helpers/notifications.ts+++ b/server/tests/helpers/notifications.ts@@ -108,10 +108,16 @@ export async function makeNotificationPreferencesService(* suite sees every event row unless it is about the narrowing itself.*/export function everyFeatureOn(- overrides: Partial<Pick<AddonsService, 'isAddonEnabled' | 'isWandererAvailable' | 'enabledPhotoProviderIds'>> = {},+ overrides: Partial<+ Pick<+ AddonsService,+ 'isAddonEnabled' | 'isEnabledForUserAnywhere' | 'isWandererAvailable' | 'enabledPhotoProviderIds'+ >+ > = {},): AddonsService {return {isAddonEnabled: async () => true,+ isEnabledForUserAnywhere: async () => true,isWandererAvailable: async () => true,enabledPhotoProviderIds: async () => ['immich', 'synologyphotos'],...overrides,diff --git a/server/tests/helpers/plugin-host.ts b/server/tests/helpers/plugin-host.tsindex 228eec64e..6217fbefc 100644--- a/server/tests/helpers/plugin-host.ts+++ b/server/tests/helpers/plugin-host.ts@@ -521,6 +521,7 @@ export async function createPluginRpcHostParts(await createTestUsersRepo(db),await createTestTripsRepo(db),await createTestBudgetItemsRepo(db),+ await createTestAddonsService(db),);const trips = new TripsService(reservations,@@ -535,6 +536,8 @@ export async function createPluginRpcHostParts(await createTestUnitOfWork(db),(await sharedTestOrm(db)).em,new SettingsService(await createTestUnitOfWork(db), appSettings, await createTestSettingsRepo(db), membership),+ // TripAddonsService: a copy's per-trip addon switches have their own suites; nothing is copied here.+ { copyOverrides: async () => {} } as never,);// Plan 4 Task 4: UserCleanupService's UC1 now goes through a directly-injected// EntityManager (MaintenanceRepository.deletePluginUserData), not DatabaseService.diff --git a/server/tests/helpers/test-addons.ts b/server/tests/helpers/test-addons.tsindex 2d3b0d810..81ea6f32d 100644--- a/server/tests/helpers/test-addons.ts+++ b/server/tests/helpers/test-addons.ts@@ -3,6 +3,7 @@ import { Addons } from '../../src/db/entities/Addons.entity';import { AppSettings } from '../../src/db/entities/AppSettings.entity';import { PhotoProviderFields } from '../../src/db/entities/PhotoProviderFields.entity';import { PhotoProviders } from '../../src/db/entities/PhotoProviders.entity';+import { TripAddonOverrides } from '../../src/db/entities/TripAddonOverrides.entity';import { Users } from '../../src/db/entities/Users.entity';import { AddonsService } from '../../src/nest/addons/addons.service';import { UnitOfWork } from '../../src/nest/database/unit-of-work';@@ -44,5 +45,6 @@ export async function createTestAddonsService(db: Database.Database): Promise<Adt.repo(AppSettings),t.repo(Users),new UnitOfWork(t.em, new SqliteEngine()),+ t.repo(TripAddonOverrides),);}diff --git a/server/tests/integration/broadcast-parity/plan.cases.ts b/server/tests/integration/broadcast-parity/plan.cases.tsindex a46fc6742..0562db9d8 100644--- a/server/tests/integration/broadcast-parity/plan.cases.ts+++ b/server/tests/integration/broadcast-parity/plan.cases.ts@@ -108,7 +108,8 @@ const tripTagId = (s: Scene): number => {/*** The planner: places and the tags their trip owns, the day plan, days, day- * notes, categories, and the collection places copied into a trip.+ * notes, categories, the collection places copied into a trip, and the trip+ * addons its owner switches for it.*/export const plan: CaseGroup = {name: 'plan',@@ -455,6 +456,13 @@ export const plan: CaseGroup = {},expect: ['day:updated'],},+ {+ // The owner switches costs off for the trip: every tab gets the trip's addon list.+ tool: 'set_trip_addon',+ args: (s) => ({ tripId: s.trip.id, addonId: 'budget', enabled: false }),+ rest: { method: 'put', path: (s) => `/api/trips/${s.trip.id}/addons/budget`, body: () => ({ enabled: false }) },+ expect: ['tripAddons:changed'],+ },],exempt: [{diff --git a/server/tests/integration/plugins/boot-registry-order.test.ts b/server/tests/integration/plugins/boot-registry-order.test.tsindex c1f9d9614..57959b9d8 100644--- a/server/tests/integration/plugins/boot-registry-order.test.ts+++ b/server/tests/integration/plugins/boot-registry-order.test.ts@@ -38,6 +38,7 @@ import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entiimport { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';import { Plugins } from '../../../src/db/entities/Plugins.entity';import { Settings } from '../../../src/db/entities/Settings.entity';+import { TripAddonOverrides } from '../../../src/db/entities/TripAddonOverrides.entity';import { Users } from '../../../src/db/entities/Users.entity';import { PluginRpcRegistry } from '../../../src/nest-rpc/rpc-kit/registry';import type { PluginRpcRegistryService } from '../../../src/nest-rpc/rpc-kit/registry.service';@@ -269,6 +270,7 @@ describe('plugin boot vs registry scan ordering', () => {t2.repo(AppSettings),t2.repo(Users),new UnitOfWork(t2.em, new SqliteEngine()),+ t2.repo(TripAddonOverrides),);const auditLogRepo2 = t2.repo(AuditLog);const usersRepo2 = t2.repo(Users);diff --git a/server/tests/unit/budget/costs.rpc.test.ts b/server/tests/unit/budget/costs.rpc.test.tsindex d1e168769..a2806f99f 100644--- a/server/tests/unit/budget/costs.rpc.test.ts+++ b/server/tests/unit/budget/costs.rpc.test.ts@@ -37,7 +37,15 @@ const req = (method: string, params: Record<string, unknown> = {}): RpcRequest =* `linkedTo` the booking cost 5 is linked to before the write.*/function build(- opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean; refusal?: string; linkedTo?: number | null } = {},+ opts: {+ addonOn?: boolean;+ canEdit?: boolean;+ missing?: boolean;+ refusal?: string;+ linkedTo?: number | null;+ /** What a trip's owner chose for Costs, by trip id; a trip left out follows the instance (`addonOn`). */+ tripAddon?: Record<number, boolean>;+ } = {},) {const budget = {listBudgetItems: vi.fn((tripId: number) => [{ id: 5, trip_id: tripId }]),@@ -63,7 +71,10 @@ function build(const guards = new PluginGuards(db,{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(() => opts.addonOn ?? true) } as unknown as AddonsService,+ {+ isAddonEnabled: vi.fn(() => opts.addonOn ?? true),+ isEnabledForTrip: vi.fn(async (tripId: number) => opts.tripAddon?.[tripId] ?? opts.addonOn ?? true),+ } as unknown as AddonsService,{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,);// The leaf membership read replaced the deleted trips.bridge for listMine.@@ -122,6 +133,37 @@ describe('CostsRpc reads', () => {});});+describe('CostsRpc per trip', () => {+ it('COSTS-RPC-TRIP-001 a trip that switched Costs on answers although the instance has it off', async () => {+ const f = build({ addonOn: false, tripAddon: { 1: true } });+ expect((await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)).ok).toBe(true);+ const created = await f.host().dispatch(req('costs.create', { tripId: 1, input: { name: 'Hotel', price: 1 } }), 42);+ expect(created.ok).toBe(true);+ });++ it('COSTS-RPC-TRIP-002 a trip that switched Costs off is refused although the instance has it on', async () => {+ const f = build({ tripAddon: { 1: false } });+ const read = (await f.host().dispatch(req('costs.getByTrip', { tripId: 1 }), 42)) as RpcError;+ expect(read.error.message).toBe('the costs addon is disabled');+ const write = (await f.host().dispatch(req('costs.delete', { tripId: 1, itemId: 5 }), 42)) as RpcError;+ expect(write.error.message).toBe('the costs addon is disabled');+ expect(f.budget.listBudgetItems).not.toHaveBeenCalled();+ expect(f.budget.remove).not.toHaveBeenCalled();+ });++ it('COSTS-RPC-TRIP-003 listMine leaves out the trips that have Costs off, and reads the ones that switched it on', async () => {+ const off = build({ tripAddon: { 2: false } });+ expect((await off.host().dispatch(req('costs.listMine'), 42)).ok).toBe(true);+ expect(off.budget.listBudgetItems).toHaveBeenCalledTimes(1);+ expect(off.budget.listBudgetItems).toHaveBeenCalledWith(1);++ const on = build({ addonOn: false, tripAddon: { 2: true } });+ expect((await on.host().dispatch(req('costs.listMine'), 42)).ok).toBe(true);+ expect(on.budget.listBudgetItems).toHaveBeenCalledTimes(1);+ expect(on.budget.listBudgetItems).toHaveBeenCalledWith(2);+ });+});+describe('CostsRpc writes', () => {it('COSTS-RPC-006 every write needs the addon, trip access and budget_edit', async () => {const f = build();diff --git a/server/tests/unit/db/connection.test.ts b/server/tests/unit/db/connection.test.tsindex ec5f3bf84..a94838591 100644--- a/server/tests/unit/db/connection.test.ts+++ b/server/tests/unit/db/connection.test.ts@@ -160,6 +160,7 @@ async function deleteTripAndWatchTempFiles(db: Database.Database): Promise<{new UnitOfWork(t.em, new SqliteEngine()),t.em,none,+ none,);await trips.remove(trip.id, user.id, 'user');return {diff --git a/server/tests/unit/db/entities-index.test.ts b/server/tests/unit/db/entities-index.test.tsindex a81562d96..fed2ab095 100644--- a/server/tests/unit/db/entities-index.test.ts+++ b/server/tests/unit/db/entities-index.test.ts@@ -59,14 +59,15 @@ describe('ALL_ENTITIES', () => {* + trip_member_removals, who another member took off a trip, so its invite link refuses them* + assistant_attachments, the files attached in the trip chat, kept with their conversation* + mail_ingest_addresses, _prefs, _cursor, _messages and _candidates, the forwarded- * booking mails, the bookings read from them and the switches and addresses behind them)+ * booking mails, the bookings read from them and the switches and addresses behind them+ * + trip_addon_overrides, the owner's per-trip on or off for a trip addon)* is registered, and no two share a class name (a silent duplicate would* shadow one of them in `orm.getMetadata()`, exactly the kind of drift* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,* which de-duplicates by class name).*/- it('ENT-003: exactly 173 entities, every class name unique', () => {- expect(ALL_ENTITIES.length).toBe(173);+ it('ENT-003: exactly 174 entities, every class name unique', () => {+ expect(ALL_ENTITIES.length).toBe(174);const names = ALL_ENTITIES.map((s) => s.meta.className);expect(new Set(names).size).toBe(names.length);});diff --git a/server/tests/unit/db/entity-class-fields.test.ts b/server/tests/unit/db/entity-class-fields.test.tsindex a2bf04c54..1686829b7 100644--- a/server/tests/unit/db/entity-class-fields.test.ts+++ b/server/tests/unit/db/entity-class-fields.test.ts@@ -66,7 +66,8 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';// + mail_ingest_addresses: id, token_hash, token_enc, user_id; mail_ingest_prefs: id, user_id; mail_ingest_cursor:// id, transport, mailbox; mail_ingest_messages: id, transport, dedupe_hash, user_id, size; mail_ingest_candidates:// id, message_id, user_id (each row is written whole by the mail import, which always knows all of them).-const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 632;+// + trip_addon_overrides: trip_id, addon_id, enabled (an override is only ever written whole, by the trip owner).+const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 635;describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.tsindex fa237de08..5a89e4825 100644--- a/server/tests/unit/db/legacy-baseline.test.ts+++ b/server/tests/unit/db/legacy-baseline.test.ts@@ -115,6 +115,7 @@ const UNNUMBERED = ['Migration20200101046450_a_carried_over_half_day_stays_half','Migration20200101046460_an_upgraded_install_gets_the_columns_its_history_skipped','Migration20200101046480_an_address_changed_after_an_admin_made_the_account',+ 'Migration20200101046490_a_trip_can_switch_its_own_addons',];// The last step the positional runner ever had; planLegacyBaseline refuses a// schema_version past it.diff --git a/server/tests/unit/db/repositories/TripAddonOverrides.repository.test.ts b/server/tests/unit/db/repositories/TripAddonOverrides.repository.test.tsnew file mode 100644index 000000000..357405921--- /dev/null+++ b/server/tests/unit/db/repositories/TripAddonOverrides.repository.test.ts@@ -0,0 +1,133 @@+/**+ * `TripAddonOverridesRepository`: a trip's own on or off for a trip addon.+ * Seeded and read through the ORM factories on the migrated snapshot, whose+ * seeded addon rows (packing, budget, tours, ...) the foreign key points at.+ */+import { TripAddonOverrides } from '../../../../src/db/entities/TripAddonOverrides.entity';+import { Trips } from '../../../../src/db/entities/Trips.entity';+import type { TripAddonOverridesRepository } from '../../../../src/db/repositories/TripAddonOverrides.repository';+import { createSnapshotTestDb } from '../../../helpers/db-mock';+import { countRows, deleteRows, findRow } from '../../../helpers/factories/rows';+import { addTripMember, makeTrip } from '../../../helpers/factories/trips';+import { makeUser } from '../../../helpers/factories/users';+import { resetTestDb } from '../../../helpers/test-db';+import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';++import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';++const testDb = createSnapshotTestDb();+let t: TestOrm;+let repo: TripAddonOverridesRepository;++beforeAll(async () => {+ t = await createTestOrm(testDb);+ repo = t.repo(TripAddonOverrides);+});+beforeEach(() => {+ resetTestDb(testDb);+ t.clear();+});+afterAll(async () => {+ await t.close();+ testDb.close();+});++async function ownerAndTrip() {+ const { user } = await makeUser(t);+ const trip = await makeTrip(t, user.id);+ return { user, trip };+}++describe('TripAddonOverridesRepository', () => {+ it('TAOREPO-001: a trip without choices lists nothing and follows the instance for every addon', async () => {+ const { trip } = await ownerAndTrip();+ expect(await repo.listForTrip(trip.id)).toEqual([]);+ expect(await repo.findForTrip(trip.id, 'budget')).toBeNull();+ });++ it('TAOREPO-002: upsertOverride writes on and off as booleans and replaces an earlier choice in place', async () => {+ const { trip } = await ownerAndTrip();+ await repo.upsertOverride(trip.id, 'budget', false);+ await repo.upsertOverride(trip.id, 'packing', true);+ expect(await repo.findForTrip(trip.id, 'budget')).toBe(false);+ expect(await repo.findForTrip(trip.id, 'packing')).toBe(true);++ await repo.upsertOverride(trip.id, 'budget', true);+ expect(await repo.listForTrip(trip.id)).toEqual([+ { addon_id: 'budget', enabled: true },+ { addon_id: 'packing', enabled: true },+ ]);+ expect(await countRows(t, TripAddonOverrides, { trip: trip.id })).toBe(2);+ const row = await findRow(t, TripAddonOverrides, { trip: trip.id, addon: 'budget' });+ expect(row?.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);+ });++ it('TAOREPO-003: deleteOverride drops one choice and leaves the others', async () => {+ const { trip } = await ownerAndTrip();+ await repo.upsertOverride(trip.id, 'budget', false);+ await repo.upsertOverride(trip.id, 'tours', true);+ await repo.deleteOverride(trip.id, 'budget');+ expect(await repo.listForTrip(trip.id)).toEqual([{ addon_id: 'tours', enabled: true }]);+ await repo.deleteOverride(trip.id, 'budget');+ expect(await repo.listForTrip(trip.id)).toEqual([{ addon_id: 'tours', enabled: true }]);+ });++ it('TAOREPO-004: the choices of one trip never show on another', async () => {+ const { user, trip } = await ownerAndTrip();+ const other = await makeTrip(t, user.id);+ await repo.upsertOverride(trip.id, 'budget', false);+ expect(await repo.listForTrip(other.id)).toEqual([]);+ expect(await repo.findForTrip(other.id, 'budget')).toBeNull();+ });++ it('TAOREPO-005: copyForTrip gives the new trip the same choices and leaves the source alone', async () => {+ const { user, trip } = await ownerAndTrip();+ const copy = await makeTrip(t, user.id);+ await repo.upsertOverride(trip.id, 'budget', false);+ await repo.upsertOverride(trip.id, 'roadtrip', true);++ await repo.copyForTrip(trip.id, copy.id);+ await repo.copyForTrip(trip.id, copy.id);++ const expected = [+ { addon_id: 'budget', enabled: false },+ { addon_id: 'roadtrip', enabled: true },+ ];+ expect(await repo.listForTrip(copy.id)).toEqual(expected);+ expect(await repo.listForTrip(trip.id)).toEqual(expected);+ });++ it('TAOREPO-006: copyForTrip of a trip without choices copies nothing', async () => {+ const { user, trip } = await ownerAndTrip();+ const copy = await makeTrip(t, user.id);+ await repo.copyForTrip(trip.id, copy.id);+ expect(await repo.listForTrip(copy.id)).toEqual([]);+ });++ it('TAOREPO-007: anyEnabledForUser sees a trip the user owns or belongs to that switched the addon on', async () => {+ const { user: owner, trip } = await ownerAndTrip();+ const { user: member } = await makeUser(t);+ const { user: stranger } = await makeUser(t);+ await addTripMember(t, trip.id, member.id, owner.id);++ expect(await repo.anyEnabledForUser(owner.id, 'roadtrip')).toBe(false);+ await repo.upsertOverride(trip.id, 'roadtrip', true);+ expect(await repo.anyEnabledForUser(owner.id, 'roadtrip')).toBe(true);+ expect(await repo.anyEnabledForUser(member.id, 'roadtrip')).toBe(true);+ expect(await repo.anyEnabledForUser(stranger.id, 'roadtrip')).toBe(false);+ expect(await repo.anyEnabledForUser(owner.id, 'tours')).toBe(false);+ });++ it('TAOREPO-008: a trip that switched the addon off counts for nobody', async () => {+ const { user, trip } = await ownerAndTrip();+ await repo.upsertOverride(trip.id, 'roadtrip', false);+ expect(await repo.anyEnabledForUser(user.id, 'roadtrip')).toBe(false);+ });++ it('TAOREPO-009: the choices go with their trip', async () => {+ const { trip } = await ownerAndTrip();+ await repo.upsertOverride(trip.id, 'budget', false);+ await deleteRows(t, Trips, { id: trip.id });+ expect(await countRows(t, TripAddonOverrides, { trip: trip.id })).toBe(0);+ });+});diff --git a/server/tests/unit/files/files.rpc.test.ts b/server/tests/unit/files/files.rpc.test.tsindex 8c63f8f9c..c9ffd4780 100644--- a/server/tests/unit/files/files.rpc.test.ts+++ b/server/tests/unit/files/files.rpc.test.ts@@ -80,7 +80,7 @@ function build(const guards = new PluginGuards(db,permissions,- { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,usersRepo,);const storage = {@@ -417,7 +417,7 @@ describe('FilesRpc writes', () => {const guards = new PluginGuards(db,{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,// PluginGuards' own role lookup — unrelated to FL28's `usersRepo` below,// which is used for the demo-uploader email check.{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,diff --git a/server/tests/unit/mcp/tools-prompts.test.ts b/server/tests/unit/mcp/tools-prompts.test.tsindex 4f28f561a..622e6fd31 100644--- a/server/tests/unit/mcp/tools-prompts.test.ts+++ b/server/tests/unit/mcp/tools-prompts.test.ts@@ -81,6 +81,9 @@ const { isAddonEnabledMock } = vi.hoisted(() => {// of behind an import path.const addonsStub = {isAddonEnabled: isAddonEnabledMock,+ // The trip addons answer per user and per trip; this suite has no overrides, so both follow the switch.+ isEnabledForUserAnywhere: isAddonEnabledMock,+ isEnabledForTrip: isAddonEnabledMock,getCollabFeatures: () => ({ chat: true, notes: true, links: true, polls: true, whatsnext: true }),} as unknown as AddonsService;@@ -420,6 +423,22 @@ describe('Prompt: trip-summary', () => {expect(text).toContain('?'); // start/end date fallbackexpect(text).toContain('EUR'); // currency fallback});++ it('leaves out the sections whose addon is off for the trip, the rest as before', async () => {+ const { user } = createUser(testDb);+ const trip = createTrip(testDb, user.id, { title: 'Lisbon' });+ isAddonEnabledMock.mockImplementation((tripOrId: unknown, id?: string) =>+ typeof tripOrId === 'number' && id !== undefined ? id === 'collab' : true,+ );++ const client = await buildServer(user.id);+ const text = await invokePromptText(client, 'trip-summary', { tripId: trip.id });+ expect(text).toContain('Lisbon');+ expect(text).toContain('Reservations:');+ expect(text).toContain('Collab Notes:');+ expect(text).not.toContain('Packing:');+ expect(text).not.toContain('Budget:');+ });});// ─────────────────────────────────────────────────────────────────────────────diff --git a/server/tests/unit/nest-mcp/tool-gate.test.ts b/server/tests/unit/nest-mcp/tool-gate.test.tsindex 07bce2bb3..6c8e812a3 100644--- a/server/tests/unit/nest-mcp/tool-gate.test.ts+++ b/server/tests/unit/nest-mcp/tool-gate.test.ts@@ -59,6 +59,7 @@ describe('tool gate', () => {expect(gate).toHaveBeenCalledWith(expect.objectContaining({ name: 'write_it', annotations: { readOnlyHint: false } }),asCtx({ userId: 3 }),+ { n: 1 },);});diff --git a/server/tests/unit/nest-rpc/plugin-guards.test.ts b/server/tests/unit/nest-rpc/plugin-guards.test.tsindex c17da3e23..55cf284e4 100644--- a/server/tests/unit/nest-rpc/plugin-guards.test.ts+++ b/server/tests/unit/nest-rpc/plugin-guards.test.ts@@ -48,7 +48,9 @@ const ctx = (actingUserId: number | undefined): PluginRpcContext => ({* carry a null role, and `getRole` has no way to tell "row absent" from "row present,* role null" apart even if it could.*/-function build(overrides: { role?: string | null; allow?: boolean; addonOn?: boolean } = {}) {+function build(+ overrides: { role?: string | null; allow?: boolean; addonOn?: boolean; tripAddon?: Record<number, boolean> } = {},+) {const db = {findAccessible: vi.fn(async (tripId: number, userId: number) =>tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined,@@ -60,8 +62,10 @@ function build(overrides: { role?: string | null; allow?: boolean; addonOn?: booconst permissions = {checkPermission: vi.fn(() => overrides.allow ?? true),} as unknown as PermissionsService;+ // `tripAddon` is what a trip's owner chose, by trip id; a trip left out follows the instance (`addonOn`).const addons = {isAddonEnabled: vi.fn(() => overrides.addonOn ?? true),+ isEnabledForTrip: vi.fn(async (tripId: number) => overrides.tripAddon?.[tripId] ?? overrides.addonOn ?? true),} as unknown as AddonsService;return { guards: new PluginGuards(db, permissions, addons, users), db, users, permissions, addons };}@@ -255,6 +259,56 @@ describe('PluginGuards — requireAddon', () => {});});+describe('PluginGuards: requireAddon for one trip', () => {+ it('PGUARD-030 a trip the user sees answers with its own choice, in either direction', async () => {+ const on = build({ addonOn: false, tripAddon: { 1: true } });+ await expect(on.guards.requireAddon('budget', 'costs', { tripId: 1, userId: 42 })).resolves.toBeUndefined();+ expect(on.addons.isEnabledForTrip).toHaveBeenCalledWith(1, 'budget');++ const off = build({ addonOn: true, tripAddon: { 1: false } });+ await expect(off.guards.requireAddon('budget', 'costs', { tripId: 1, userId: 42 })).rejects.toThrow(+ new ForbiddenResource('the costs addon is disabled'),+ );+ });++ it('PGUARD-031 a trip the user cannot see is answered with the instance switch, never its own choice', async () => {+ const f = build({ addonOn: true, tripAddon: { 1: false } });+ await expect(f.guards.requireAddon('budget', 'costs', { tripId: 1, userId: 7 })).resolves.toBeUndefined();+ expect(f.addons.isEnabledForTrip).not.toHaveBeenCalled();+ });++ it('PGUARD-032 tripRead and requireTripEdit ask the addon of the trip after the access check', async () => {+ const f = build({ tripAddon: { 1: false } });+ const read = vi.fn(() => 'rows');+ await expect(+ f.guards.tripRead({ tripId: 1 }, ctx(42), read, { addonId: 'packing', noun: 'packing' }),+ ).rejects.toThrow(new ForbiddenResource('the packing addon is disabled'));+ expect(read).not.toHaveBeenCalled();+ await expect(+ f.guards.requireTripEdit(1, 42, 'packing_edit', { addonId: 'packing', noun: 'packing' }),+ ).rejects.toThrow(new ForbiddenResource('the packing addon is disabled'));+ // Without an addon named, the two stay what they were.+ await expect(f.guards.tripRead({ tripId: 1 }, ctx(42), read)).resolves.toBe('rows');+ await expect(f.guards.requireTripEdit(1, 42, 'packing_edit')).resolves.toBeUndefined();+ });++ it('PGUARD-033 tripsWithAddon keeps the trips the addon applies to, in the order given', async () => {+ const f = build({ addonOn: true, tripAddon: { 2: false } });+ expect(await f.guards.tripsWithAddon('budget', 'costs', [3, 2, 1])).toEqual([3, 1]);+ // The instance off: only the trips that switched it on, and a refusal when none did.+ expect(+ await build({ addonOn: false, tripAddon: { 2: true } }).guards.tripsWithAddon('budget', 'costs', [1, 2]),+ ).toEqual([2]);+ await expect(build({ addonOn: false }).guards.tripsWithAddon('budget', 'costs', [1, 2])).rejects.toThrow(+ new ForbiddenResource('the costs addon is disabled'),+ );+ // The instance on with every trip switched off is an empty answer, not a refusal.+ expect(+ await build({ addonOn: true, tripAddon: { 1: false } }).guards.tripsWithAddon('budget', 'costs', [1]),+ ).toEqual([]);+ });+});+describe('PluginGuards — capStrings', () => {it('PGUARD-017 a field within the cap passes', () => {expect(() => build().guards.capStrings({ name: 'ok' }, { name: 200 })).not.toThrow();diff --git a/server/tests/unit/nest/addon-guard.test.ts b/server/tests/unit/nest/addon-guard.test.tsindex cea618b5b..bc924daef 100644--- a/server/tests/unit/nest/addon-guard.test.ts+++ b/server/tests/unit/nest/addon-guard.test.ts@@ -24,16 +24,20 @@ import { Reflector } from '@nestjs/core';import { describe, it, expect, vi } from 'vitest';-/** A context whose handler/class carry the decorator under test. */-function ctxFor(handler: object, cls: object = class {}): ExecutionContext {+/** A context whose handler/class carry the decorator under test, for a request with or without a user. */+function ctxFor(handler: object, cls: object = class {}, user?: { id: number }): ExecutionContext {return {getHandler: () => handler,getClass: () => cls,+ switchToHttp: () => ({ getRequest: () => ({ user }) }),} as unknown as ExecutionContext;}-function addons(enabled: boolean): AddonsService {- return { isAddonEnabled: vi.fn(() => enabled) } as unknown as AddonsService;+function addons(enabled: boolean, anywhere = false): AddonsService {+ return {+ isAddonEnabled: vi.fn(() => enabled),+ isEnabledForUserAnywhere: vi.fn(() => enabled || anywhere),+ } as unknown as AddonsService;}async function thrown(fn: () => unknown) {@@ -107,6 +111,39 @@ describe('AddonGuard', () => {});});+describe('AddonGuard once the user is known', () => {+ it('ADDON-GUARD-008: opens for a user one of whose trips switched the addon on, although the instance has it off', async () => {+ const cls = decorated(ADDON_IDS.TOURS, 'Tours');+ const svc = addons(false, true);+ const guard = new AddonGuard(svc, new Reflector());++ expect(await guard.canActivate(ctxFor(() => {}, cls, { id: 7 }))).toBe(true);+ expect(svc.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);+ expect(svc.isAddonEnabled).not.toHaveBeenCalled();+ });++ it('ADDON-GUARD-009: stays shut for a user none of whose trips switched it on', async () => {+ const cls = decorated(ADDON_IDS.ROADTRIP, 'Road trip');+ const guard = new AddonGuard(addons(false, false), new Reflector());++ expect(await thrown(() => guard.canActivate(ctxFor(() => {}, cls, { id: 7 })))).toEqual({+ status: 404,+ body: { error: 'Road trip addon is not enabled' },+ });+ });++ it('ADDON-GUARD-010: without a user it reads the instance switch alone', async () => {+ const cls = decorated(ADDON_IDS.TOURS, 'Tours');+ const svc = addons(false, true);++ expect(await thrown(() => new AddonGuard(svc, new Reflector()).canActivate(ctxFor(() => {}, cls)))).toEqual({+ status: 404,+ body: { error: 'Tours addon is not enabled' },+ });+ expect(svc.isEnabledForUserAnywhere).not.toHaveBeenCalled();+ });+});+describe('the gated route groups still declare their addon', () => {const metaOf = (cls: object): RequireAddonMeta | undefined => Reflect.getMetadata(REQUIRE_ADDON, cls);const guardsOf = (cls: object): unknown[] => Reflect.getMetadata('__guards__', cls) ?? [];diff --git a/server/tests/unit/nest/addons.service.test.ts b/server/tests/unit/nest/addons.service.test.tsindex e21d53618..ef1b0f879 100644--- a/server/tests/unit/nest/addons.service.test.ts+++ b/server/tests/unit/nest/addons.service.test.ts@@ -27,6 +27,7 @@ import { AppSettings } from '../../../src/db/entities/AppSettings.entity';import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';import { PlaceShadowPicks } from '../../../src/db/entities/PlaceShadowPicks.entity';+import { TripAddonOverrides } from '../../../src/db/entities/TripAddonOverrides.entity';import { Users } from '../../../src/db/entities/Users.entity';import type { AddonsRepository } from '../../../src/db/repositories/Addons.repository';import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';@@ -197,6 +198,7 @@ beforeEach(() => {appSettingsRepo,usersRepo,new UnitOfWork(t.em, new SqliteEngine()),+ t.repo(TripAddonOverrides),);});@@ -435,6 +437,22 @@ describe('AddonsService addon/feature flags', () => {expect((await svc.list()).toursWanderer).toBe(false);});+ it('the wanderer sub-option alone ignores the Tours switch, which a trip may decide for itself', async () => {+ expect(await svc.isWandererAllowed()).toBe(false); // absent row: OFF+ await svc.updateToursWanderer(true);+ // Tours is off for the instance, yet the option holds wherever a trip switched Tours on.+ expect(await svc.isWandererAllowed()).toBe(true);+ expect(await svc.isWandererAvailable()).toBe(false);+ const saved = process.env.TREK_MANAGED;+ try {+ process.env.TREK_MANAGED = '1';+ expect(await svc.isWandererAllowed()).toBe(false);+ } finally {+ if (saved === undefined) delete process.env.TREK_MANAGED;+ else process.env.TREK_MANAGED = saved;+ }+ });+it('wanderer is never available on a managed install, whatever the stored switch says', async () => {const saved = process.env.TREK_MANAGED;try {@@ -481,6 +499,16 @@ describe('AddonsService addon/feature flags', () => {expect((await svc.list()).toursHikingMap).toBe(true);});+ it('lists the Tours options apart from the instance Tours switch, for a trip that switched Tours on itself', async () => {+ // Tours is off for the instance: the combined flags say no, the options say what the admin chose.+ expect((await svc.list()).toursOptions).toEqual({ wanderer: false, hikingMap: true, cycleMap: true });+ expect((await svc.list()).toursHikingMap).toBe(false);+ await svc.updateToursWanderer(true);+ await svc.updateToursCycleMap(false);+ expect((await svc.list()).toursOptions).toEqual({ wanderer: true, hikingMap: true, cycleMap: false });+ expect((await svc.list()).toursWanderer).toBe(false);+ });+it('the piste router under Tours is on until an admin switches it off', async () => {expect(await svc.getToursSkiRouting()).toEqual({ enabled: true }); // absent row → ONexpect(await svc.updateToursSkiRouting(false)).toEqual({ enabled: false });diff --git a/server/tests/unit/nest/assistant/assistant-attachment-tools.test.ts b/server/tests/unit/nest/assistant/assistant-attachment-tools.test.tsindex 6f4beb164..1bf252325 100644--- a/server/tests/unit/nest/assistant/assistant-attachment-tools.test.ts+++ b/server/tests/unit/nest/assistant/assistant-attachment-tools.test.ts@@ -55,17 +55,18 @@ describe('attachedPort', () => {it('ASTATL-001: offers keep_attached_file where the thread holds a file, read_attached_file where one has text', () => {const port = base();expect(attachedPort(port, null)).toBe(port);- expect(attachedPort(port, { attached: [], sentTo: 'm', read: vi.fn() })).toBe(port);+ expect(attachedPort(port, { attached: [], sentTo: 'm', keeps: true, read: vi.fn() })).toBe(port);const scanOnly = attachedPort(port, {attached: [row(SCAN, { text_status: 'scanned' })],sentTo: 'm',+ keeps: true,read: vi.fn(),});expect(scanOnly.specs().map((spec) => spec.name)).toEqual(['get_trip_summary', KEEP_ATTACHED_FILE_SPEC.name]);expect(scanOnly.pinArgs('read_attached_file', { attachmentId: SCAN })).toEqual({args: { attachmentId: SCAN },});- const offered = attachedPort(port, { attached: ATTACHED, sentTo: 'm', read: vi.fn() });+ const offered = attachedPort(port, { attached: ATTACHED, sentTo: 'm', keeps: true, read: vi.fn() });expect(offered.specs().map((spec) => spec.name)).toEqual(['get_trip_summary',READ_ATTACHED_FILE_SPEC.name,@@ -74,7 +75,7 @@ describe('attachedPort', () => {});it('ASTATL-002: the first read of a file is held for the user, a shared one runs at once', () => {- const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', read: vi.fn() });+ const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', keeps: true, read: vi.fn() });expect(port.kindOf('read_attached_file', { attachmentId: OWN })).toBe('write');expect(port.kindOf('read_attached_file', { attachmentId: SHARED })).toBe('read');expect(port.kindOf('read_attached_file', { attachmentId: ELSEWHERE })).toBe('write');@@ -82,7 +83,12 @@ describe('attachedPort', () => {});it('ASTATL-003: the held call names the file and where its text goes, never more; anything else is refused alike', () => {- const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'gpt-5 (api.openai.com)', read: vi.fn() });+ const port = attachedPort(base(), {+ attached: ATTACHED,+ sentTo: 'gpt-5 (api.openai.com)',+ keeps: true,+ read: vi.fn(),+ });expect(port.pinArgs('read_attached_file', { attachmentId: OWN, sentTo: 'nowhere' })).toEqual({args: { attachmentId: OWN, name: '0b7c.pdf', sentTo: 'gpt-5 (api.openai.com)' },});@@ -96,7 +102,7 @@ describe('attachedPort', () => {it('ASTATL-004: a read runs through the turn, and only for a file of the thread', async () => {const read = vi.fn(async () => ({ ok: true, value: { name: 'x', read: true }, modelText: 'text' }));const inner = base();- const port = attachedPort(inner, { attached: ATTACHED, sentTo: 'm', read });+ const port = attachedPort(inner, { attached: ATTACHED, sentTo: 'm', keeps: true, read });expect(await port.call('read_attached_file', { attachmentId: SHARED })).toMatchObject({ modelText: 'text' });expect(read).toHaveBeenCalledWith(SHARED);expect(await port.call('read_attached_file', { attachmentId: ELSEWHERE })).toEqual({@@ -114,7 +120,7 @@ describe('attachedPort', () => {});it('ASTATL-006: a keep is always held, checked, and names the file; an attachment of no one here is refused alike', () => {- const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', read: vi.fn() });+ const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', keeps: true, read: vi.fn() });expect(port.kindOf('keep_attached_file', { attachmentId: SCAN })).toBe('write');expect(port.pinArgs('keep_attached_file', { attachmentId: SCAN, reservation_id: 5, name: 'forged.exe' })).toEqual({args: { attachmentId: SCAN, reservation_id: 5, name: '2d9e.pdf' },@@ -124,4 +130,14 @@ describe('attachedPort', () => {const bad = port.pinArgs('keep_attached_file', { attachmentId: OWN, budget_item_id: 'seven' });expect(bad).toEqual({ error: expect.stringContaining('Invalid arguments') });});++ it('ASTATL-007: no keep is offered or held while the trip has Documents off; the call goes to the port', () => {+ const inner = base();+ const port = attachedPort(inner, { attached: ATTACHED, sentTo: 'm', keeps: false, read: vi.fn() });+ expect(port.specs().map((spec) => spec.name)).toEqual(['get_trip_summary', READ_ATTACHED_FILE_SPEC.name]);+ expect(port.kindOf('keep_attached_file', { attachmentId: SCAN })).toBe('read');+ expect(inner.kindOf).toHaveBeenCalledWith('keep_attached_file', { attachmentId: SCAN });+ port.pinArgs('keep_attached_file', { attachmentId: SCAN });+ expect(inner.pinArgs).toHaveBeenCalledWith('keep_attached_file', { attachmentId: SCAN });+ });});diff --git a/server/tests/unit/nest/assistant/assistant-attachments.service.test.ts b/server/tests/unit/nest/assistant/assistant-attachments.service.test.tsindex a635a3ee0..cebd1177d 100644--- a/server/tests/unit/nest/assistant/assistant-attachments.service.test.ts+++ b/server/tests/unit/nest/assistant/assistant-attachments.service.test.ts@@ -53,10 +53,19 @@ interface Listed {mtimeMs: number;}-async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete?: string; failPut?: boolean } = {}) {+interface MakeOpts {+ text?: string | Error;+ listed?: Listed[];+ failDelete?: string;+ failPut?: boolean;+ attached?: Array<{ id: string; trip_id: number }>;+ documents?: boolean;+}++async function make(opts: MakeOpts = {}) {const rows = {insertAttachment: vi.fn(async () => undefined),- listForThread: vi.fn(async () => []),+ listForThread: vi.fn(async () => opts.attached ?? []),listObjectsOfThread: vi.fn(async () => [{ id: 'a1', storage_key: 'assistant/a1.pdf' }]),listCreatedBefore: vi.fn(async () => [{ id: 'old1', storage_key: 'assistant/old1.pdf' },@@ -90,6 +99,10 @@ async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete}),fitText: vi.fn((text: string, compact: boolean) => (compact ? text.slice(0, 4) : text)),};+ const keeper = {+ keep: vi.fn(async () => ({ ok: true, value: { file: { id: 3 } } })),+ keepsOn: vi.fn(async (_tripId: number) => opts.documents !== false),+ };const moduleRef = await Test.createTestingModule({providers: [AssistantAttachmentsService,@@ -99,11 +112,11 @@ async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete{ provide: MikroORM, useValue: {} },{provide: AssistantKeepFileService,- useValue: { keep: vi.fn(async () => ({ ok: true, value: { file: { id: 3 } } })) },+ useValue: keeper,},],}).compile();- return { service: moduleRef.get(AssistantAttachmentsService), rows, storage, llmParse };+ return { service: moduleRef.get(AssistantAttachmentsService), rows, storage, llmParse, keeper };}describe('AssistantAttachmentsService', () => {@@ -258,5 +271,18 @@ describe('AssistantAttachmentsService', () => {const cloud = await t.service.turnFor(7, 4, { kind: 'openai', model: 'gpt-5', host: 'api.openai.com' });expect(cloud.texts).toEqual(new Map([[SHARED, 'Casa Lisboa, HM4X2']]));expect(t.rows.listSharedTexts).toHaveBeenCalledWith(4, 7);+ // A thread without files has nothing to keep and asks no addon.+ expect(cloud.turn.keeps).toBe(false);+ expect(t.keeper.keepsOn).not.toHaveBeenCalled();+ });++ it('ASTATT-012: a turn may keep its files only while their trip has Documents on', async () => {+ const connection = { kind: 'openai', model: 'gpt-5', host: 'api.openai.com' } as const;+ const attached = [{ id: SHARED, trip_id: 9 }];+ const on = await make({ attached });+ expect((await on.service.turnFor(7, 4, connection)).turn.keeps).toBe(true);+ expect(on.keeper.keepsOn).toHaveBeenCalledWith(9);+ const off = await make({ attached, documents: false });+ expect((await off.service.turnFor(7, 4, connection)).turn.keeps).toBe(false);});});diff --git a/server/tests/unit/nest/assistant/assistant-booking-import.service.test.ts b/server/tests/unit/nest/assistant/assistant-booking-import.service.test.tsindex 885901165..d7ccd4433 100644--- a/server/tests/unit/nest/assistant/assistant-booking-import.service.test.ts+++ b/server/tests/unit/nest/assistant/assistant-booking-import.service.test.ts@@ -80,7 +80,7 @@ async function codeOf(promise: Promise<unknown>): Promise<string | null> {describe('AssistantBookingImportService', () => {it('ASTBKI-001: refuses a file nothing here reads, and a photo the model cannot see', async () => {const readable = async (opts: Opts, name: string) =>- codeOf((await make(opts)).service.ensureReadable(7, file(name)));+ codeOf((await make(opts)).service.ensureReadable(7, 1, file(name)));expect(await readable({ extractor: false }, 'a.pdf')).toBe('import_unavailable');expect(await readable({ extractor: false, ai: true }, 'a.pdf')).toBeNull();expect(await readable({}, 'a.pdf')).toBeNull();diff --git a/server/tests/unit/nest/assistant/assistant-keep-file.service.test.ts b/server/tests/unit/nest/assistant/assistant-keep-file.service.test.tsindex f032a2ca1..e41437983 100644--- a/server/tests/unit/nest/assistant/assistant-keep-file.service.test.ts+++ b/server/tests/unit/nest/assistant/assistant-keep-file.service.test.ts@@ -1,10 +1,11 @@/*** keep_attached_file applied: the checks a Files upload runs (demo, trip,- * rights, types, same-trip links), the bytes copied to a trip file of their+ * the trip's Documents addon, rights, types, same-trip links), the bytes copied to a trip file of their* own, the rows written in one transaction, the broadcast after it, and a* second keep that answers the first file.*/import { AssistantAttachments } from '../../../../src/db/entities/AssistantAttachments.entity';+import { AddonsService } from '../../../../src/nest/addons/addons.service';import { AssistantKeepFileService } from '../../../../src/nest/assistant/assistant-keep-file.service';import { DemoService } from '../../../../src/nest/common/demo.service';import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';@@ -28,6 +29,7 @@ const AT = { userId: 7, threadId: 4, tripId: 9 };interface Opts {demo?: boolean;trip?: boolean;+ documents?: boolean;upload?: boolean;edit?: boolean;allowed?: string;@@ -75,6 +77,8 @@ async function make(opts: Opts = {}) {),};const uow = { transactional: vi.fn(async (fn: () => Promise<unknown>) => fn()) };+ // The trip's Documents addon: what its owner chose, else the instance switch.+ const addons = { isEnabledForTrip: vi.fn(async () => opts.documents !== false) };const moduleRef = await Test.createTestingModule({providers: [AssistantKeepFileService,@@ -89,9 +93,10 @@ async function make(opts: Opts = {}) {useValue: { findAccessible: vi.fn(async () => (opts.trip === false ? undefined : { id: 9 })) },},{ provide: UnitOfWork, useValue: uow },+ { provide: AddonsService, useValue: addons },],}).compile();- return { service: moduleRef.get(AssistantKeepFileService), rows, files, guards, uow, storage };+ return { service: moduleRef.get(AssistantKeepFileService), rows, files, guards, uow, storage, addons };}describe('AssistantKeepFileService', () => {@@ -155,6 +160,19 @@ describe('AssistantKeepFileService', () => {});});+ it('ASTKEP-007: refused while the trip has Documents off, with the words the Files routes use', async () => {+ const t = await make({ documents: false });+ expect(await t.service.keep(AT, { attachmentId: ID })).toEqual({+ ok: false,+ value: 'Documents addon is not enabled',+ });+ expect(t.addons.isEnabledForTrip).toHaveBeenCalledWith(9, 'documents');+ expect(t.rows.findInThread).not.toHaveBeenCalled();+ expect(t.files.storeBytes).not.toHaveBeenCalled();+ expect(await t.service.keepsOn(9)).toBe(false);+ expect(await (await make()).service.keepsOn(9)).toBe(true);+ });+it('ASTKEP-004: an attachment of no one here, a type Files refuses and a link off the trip are refused', async () => {const run = async (opts: Opts, args: Record<string, unknown> = { attachmentId: ID }) =>(await make(opts)).service.keep(AT, args);diff --git a/server/tests/unit/nest/assistant/assistant-share.service.test.ts b/server/tests/unit/nest/assistant/assistant-share.service.test.tsindex 2d115769a..839c8918b 100644--- a/server/tests/unit/nest/assistant/assistant-share.service.test.ts+++ b/server/tests/unit/nest/assistant/assistant-share.service.test.ts@@ -30,7 +30,7 @@ const db = createSnapshotTestDb();let t: TestModule;const addons = {- isAddonEnabled: vi.fn(async () => true),+ isEnabledForTrip: vi.fn(async () => true),getCollabFeatures: vi.fn(async () => ({ chat: true, notes: true, polls: true })),};const collab = {@@ -108,7 +108,7 @@ describe('AssistantShareService', () => {it('ASTSHR-003: refused while the collab addon or its chat is off', async () => {const c = await conversation();const share = () => shareAs(c.user, c.tripId, c.threadId, `msg-${c.answer.id}`);- addons.isAddonEnabled.mockResolvedValueOnce(false);+ addons.isEnabledForTrip.mockResolvedValueOnce(false);await expect(share()).rejects.toMatchObject({ status: 403, message: 'Collab chat is off' });addons.getCollabFeatures.mockResolvedValueOnce({ chat: false, notes: true, polls: true });await expect(share()).rejects.toMatchObject({ status: 403, code: 'forbidden' });diff --git a/server/tests/unit/nest/assistant/assistant-tour-file.service.test.ts b/server/tests/unit/nest/assistant/assistant-tour-file.service.test.tsindex d93e75442..70d4ffd36 100644--- a/server/tests/unit/nest/assistant/assistant-tour-file.service.test.ts+++ b/server/tests/unit/nest/assistant/assistant-tour-file.service.test.ts@@ -37,15 +37,15 @@ function file(name: string): Express.Multer.File {async function make(tracks: TourFileTrack[], opts: { tours?: boolean; whole?: boolean } = {}) {const read = vi.fn(async () => ({ tracks, whole: opts.whole === true }));- const isAddonEnabled = vi.fn(async () => opts.tours !== false);+ const isEnabledForTrip = vi.fn(async () => opts.tours !== false);const moduleRef = await Test.createTestingModule({providers: [AssistantTourFileService,{ provide: TourFileReadService, useValue: { read } },- { provide: AddonsService, useValue: { isAddonEnabled } },+ { provide: AddonsService, useValue: { isEnabledForTrip } },],}).compile();- return { service: moduleRef.get(AssistantTourFileService), read, isAddonEnabled };+ return { service: moduleRef.get(AssistantTourFileService), read, isEnabledForTrip };}describe('AssistantTourFileService', () => {@@ -56,10 +56,10 @@ describe('AssistantTourFileService', () => {});it('AST-TOUR-FILE-002: refuses a route file where tours are off', async () => {- const { service, isAddonEnabled } = await make([], { tours: false });- await expect(service.ensureReadable(7, file('a.gpx'))).rejects.toBeInstanceOf(DomainError);- expect(isAddonEnabled).toHaveBeenCalledWith('tours');- await expect((await make([])).service.ensureReadable(7, file('a.gpx'))).resolves.toBeUndefined();+ const { service, isEnabledForTrip } = await make([], { tours: false });+ await expect(service.ensureReadable(7, 3, file('a.gpx'))).rejects.toBeInstanceOf(DomainError);+ expect(isEnabledForTrip).toHaveBeenCalledWith(3, 'tours');+ await expect((await make([])).service.ensureReadable(7, 3, file('a.gpx'))).resolves.toBeUndefined();});it('AST-TOUR-FILE-003: proposes one hike per track, the GPX text kept on the held call only', async () => {diff --git a/server/tests/unit/nest/booking-import/booking-import.service.test.ts b/server/tests/unit/nest/booking-import/booking-import.service.test.tsindex a92e045ce..1a025c716 100644--- a/server/tests/unit/nest/booking-import/booking-import.service.test.ts+++ b/server/tests/unit/nest/booking-import/booking-import.service.test.ts@@ -294,7 +294,7 @@ describe('BookingImportService.confirm venue website (#2483)', () => {reservationsRepo: reservationsRepoStub,reservations,guards: guardsStub,- addons: { isAddonEnabled: () => false },+ addons: { isAddonEnabled: () => false, isEnabledForTrip: async () => false },realtime: { broadcast: vi.fn() },maps: { geocodeQuery: vi.fn() },places,@@ -389,7 +389,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>reservations,guards: guardsStub,budget,- addons: { isAddonEnabled: async () => opts.budget ?? true },+ addons: { isAddonEnabled: async () => opts.budget ?? true, isEnabledForTrip: async () => opts.budget ?? true },realtime,maps: { geocodeQuery: vi.fn() },places,@@ -563,7 +563,7 @@ describe('BookingImportService.confirm reports every item it did not create', ()reservationsRepo: reservationsRepoStub,reservations,guards: guardsStub,- addons: { isAddonEnabled: async () => false },+ addons: { isAddonEnabled: async () => false, isEnabledForTrip: async () => false },realtime: { broadcast: vi.fn() },maps: { geocodeQuery: vi.fn() },places: { create: vi.fn() },diff --git a/server/tests/unit/nest/budget-items.mcp.test.ts b/server/tests/unit/nest/budget-items.mcp.test.tsindex 91658c00d..19b6bef06 100644--- a/server/tests/unit/nest/budget-items.mcp.test.ts+++ b/server/tests/unit/nest/budget-items.mcp.test.ts@@ -125,9 +125,10 @@ describe('BudgetItemsMcp surface', () => {expect(options.name).toBe(name);expect(options.access).toEqual({ group: 'budget', mode: 'read' });expect(options.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });- const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false);+ // Costs is a trip addon: the read is offered while the instance or any trip of the caller has it on.+ const enabled = vi.spyOn(t.get(AddonsService), 'isEnabledForUserAnywhere').mockResolvedValue(false);expect(await options.when?.(ctx(1), mcp)).toBe(false);- expect(enabled).toHaveBeenCalledWith(ADDON_IDS.BUDGET);+ expect(enabled).toHaveBeenCalledWith(1, ADDON_IDS.BUDGET);enabled.mockResolvedValue(true);expect(await options.when?.(ctx(1), mcp)).toBe(true);},diff --git a/server/tests/unit/nest/calendar.service.test.ts b/server/tests/unit/nest/calendar.service.test.tsindex 47079af9a..4d13e88f0 100644--- a/server/tests/unit/nest/calendar.service.test.ts+++ b/server/tests/unit/nest/calendar.service.test.ts@@ -34,6 +34,7 @@ import { CalendarService, calendarOptionsFromQuery, foldICS } from '../../../srcimport { CalendarModule } from '../../../src/nest/calendar/calendar.module';import { expectRegisteredProvider } from '../../helpers/module-providers';import { notificationsStub } from '../../helpers/notifications';+import { createTestAddonsService } from '../../helpers/test-addons';import { accommodationsOver } from '../../helpers/accommodations-service';import { createTestUnitOfWork, createTestAppSettingsRepo, createTestReservationsRepo, createTestReservationEndpointsRepo, createTestReservationTravelersRepo, createTestReservationDayPositionsRepo, createTestDayAccommodationsRepo, createTestDaysRepo, createTestDayNotesRepo, createTestPlacesRepo, createTestDayAssignmentsRepo, createTestTripMembersRepo, createTestUsersRepo, createTestTripsRepo } from '../../helpers/test-uow';import { createTestBudgetItemsRepo } from '../../helpers/files-repos';@@ -58,7 +59,7 @@ let orm: TestOrm;beforeAll(async () => {budgetSvc = new BudgetService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), new ExchangeRatesService(), realtime, await createTestUnitOfWork(testDb), ...(await budgetRepoArgs(testDb)));svc = new CalendarService(- new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await accommodationsOver(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),+ new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await accommodationsOver(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb)),await createTestTripsRepo(testDb), await createTestDaysRepo(testDb), await createTestDayNotesRepo(testDb), await createTestReservationsRepo(testDb),);});diff --git a/server/tests/unit/nest/city-walk.mcp.test.ts b/server/tests/unit/nest/city-walk.mcp.test.tsindex 307727899..f681482b9 100644--- a/server/tests/unit/nest/city-walk.mcp.test.ts+++ b/server/tests/unit/nest/city-walk.mcp.test.ts@@ -545,11 +545,11 @@ describe('CityWalkMcp (CW-11)', () => {]);expect(propose.description).toContain('stations_for_create');expect(create.description).toContain('route_pending');- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');const gated = await Promise.all(- [propose, create].map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })),+ [propose, create].map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })),);expect(gated).toEqual([true, true]);- expect(isAddonEnabled).toHaveBeenCalledWith('tours');+ expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');});});diff --git a/server/tests/unit/nest/collab.controller.test.ts b/server/tests/unit/nest/collab.controller.test.tsindex d2297e89e..998ed4f44 100644--- a/server/tests/unit/nest/collab.controller.test.ts+++ b/server/tests/unit/nest/collab.controller.test.ts@@ -1,3 +1,6 @@+import type { AddonsService } from '../../../src/nest/addons/addons.service';+import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import {@@ -54,8 +57,12 @@ const storageStub = {* Build the controller over its stubs. The env is the live one, so a case about* demo mode stubs DEMO_MODE and every other case runs outside it.*/-function ctl(service: CollabService, storage: StorageService = storageStub): CollabController {- return new CollabController(service, storage, new RuntimeEnvService());+/** Whether Collab applies to the trip: on, unless a test switches it off for its trip. */+const addonsOn = { isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService;+const addonsOff = { isEnabledForTrip: vi.fn(async () => false) } as unknown as AddonsService;++function ctl(service: CollabService, storage: StorageService = storageStub, addons = addonsOn): CollabController {+ return new CollabController(service, storage, new RuntimeEnvService(), addons);}async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number; body: unknown }> {@@ -346,6 +353,18 @@ describe('CollabController (parity with the legacy /api/trips/:tripId/collab rou).toEqual({ status: 403, body: { error: 'No permission' } });});+ it('refuses a trip that has Collab off for itself, after the trip check, with the addon text', async () => {+ const s = svc({ verifyTripAccess: vi.fn().mockResolvedValue({ id: 5, user_id: 1 }) } as Partial<CollabService>);+ expect(+ await thrownAsync(() => ctl(s, storageStub, addonsOff).createMessage(user, '5', { text: 'hi' }, undefined)),+ ).toEqual({+ status: 404,+ body: { error: 'Collab addon is not enabled' },+ });+ expect(addonsOff.isEnabledForTrip).toHaveBeenCalledWith(5, 'collab');+ expect(s.postMessage).not.toHaveBeenCalled();+ });+it('react 404 unknown, else broadcasts reactions (empty emoji now 400s in the Zod pipe)', async () => {expect(await thrownAsync(() =>@@ -667,8 +686,24 @@ describe('CollabController (parity with the legacy /api/trips/:tripId/collab roufor (const handler of [CollabController.prototype.createMessage, CollabController.prototype.addNoteFile]) {expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handler)).toBeUndefined();expect(guardsOn(handler)).not.toContain(TripAccessGuard);+ expect(guardsOn(handler)).not.toContain(TripAddonGuard);}});++ it('every other route asks the trip and then the Collab addon of that trip', async () => {+ expect(Reflect.getMetadata(REQUIRE_ADDON, CollabController)).toEqual({ addonId: 'collab', label: 'Collab' });+ const multipart = new Set<unknown>([+ CollabController.prototype.createMessage,+ CollabController.prototype.addNoteFile,+ ]);+ const proto = CollabController.prototype as unknown as Record<string, unknown>;+ const routes = Object.getOwnPropertyNames(CollabController.prototype)+ .map((name) => proto[name])+ .filter((fn) => typeof fn === 'function' && Reflect.getMetadata('method', fn as object) !== undefined)+ .filter((fn) => !multipart.has(fn));+ expect(routes.length).toBeGreaterThan(15);+ for (const handler of routes) expect(guardsOn(handler as object)).toEqual([TripAccessGuard, TripAddonGuard]);+ });});describe('link preview', () => {diff --git a/server/tests/unit/nest/collection-tours.controller.test.ts b/server/tests/unit/nest/collection-tours.controller.test.tsindex e4164b605..d62d8db51 100644--- a/server/tests/unit/nest/collection-tours.controller.test.ts+++ b/server/tests/unit/nest/collection-tours.controller.test.ts@@ -8,6 +8,7 @@ import 'reflect-metadata';import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { DomainError } from '../../../src/nest/common/domain-error';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';@@ -59,7 +60,7 @@ describe('CollectionToursController', () => {expect(Reflect.getMetadata(PATH_METADATA, CollectionToursController)).toBe('api/addons/collections/:collectionId/tours',);- expect(Reflect.getMetadata(GUARDS_METADATA, CollectionToursController)).toEqual([AddonGuard, JwtAuthGuard]);+ expect(Reflect.getMetadata(GUARDS_METADATA, CollectionToursController)).toEqual([JwtAuthGuard, AddonGuard]);expect(Reflect.getMetadata(REQUIRE_ADDON, CollectionToursController)).toEqual({ addonId: 'tours', label: 'Tours' });const proto = CollectionToursController.prototype;expect(route(proto, 'list')).toMatchObject({ path: '/', verb: RequestMethod.GET });@@ -98,9 +99,9 @@ describe('CollectionTourTakeOverController', () => {it('LIB3-CTRL-004: is trip-scoped, needs place_edit and hands the body on', async () => {expect(Reflect.getMetadata(PATH_METADATA, CollectionTourTakeOverController)).toBe('api/trips/:tripId/tours');expect(Reflect.getMetadata(GUARDS_METADATA, CollectionTourTakeOverController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(route(CollectionTourTakeOverController.prototype, 'takeOver')).toEqual({path: 'from-collection',diff --git a/server/tests/unit/nest/collection-tours.mcp.test.ts b/server/tests/unit/nest/collection-tours.mcp.test.tsindex 52f8d1cc1..6bd3df6b1 100644--- a/server/tests/unit/nest/collection-tours.mcp.test.ts+++ b/server/tests/unit/nest/collection-tours.mcp.test.ts@@ -215,12 +215,16 @@ describe('CollectionToursMcp', () => {if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);return entry.options;};- const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);+ // Collections is an instance addon, Tours a trip addon that is on for the caller while the instance+ // or any trip of theirs has it on.+ const collections = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);+ const tours = vi.spyOn(t.get(AddonsService), 'isEnabledForUserAnywhere').mockResolvedValue(true);const gate = options('listCollectionTours').when;expect(await gate?.(ctx(1), mcp)).toBe(true);- enabled.mockImplementation(async (id: string) => id !== 'collections');+ collections.mockImplementation(async (id: string) => id !== 'collections');expect(await gate?.(ctx(1), mcp)).toBe(false);- enabled.mockImplementation(async (id: string) => id !== 'tours');+ collections.mockResolvedValue(true);+ tours.mockImplementation(async (_userId: number, id: string) => id !== 'tours');expect(await gate?.(ctx(1), mcp)).toBe(false);const allowed = (name: string, scopes: string[]) => {diff --git a/server/tests/unit/nest/collection-tours.service.test.ts b/server/tests/unit/nest/collection-tours.service.test.tsindex b2f8c98bb..9af15d56f 100644--- a/server/tests/unit/nest/collection-tours.service.test.ts+++ b/server/tests/unit/nest/collection-tours.service.test.ts@@ -19,7 +19,7 @@ import { createSnapshotTestDb } from '../../helpers/db-mock';import { addCollectionMember, makeCollection } from '../../helpers/factories/collections';import { makePlace } from '../../helpers/factories/places';import { countRows, deleteRows, findRow, findRows, updateRows } from '../../helpers/factories/rows';-import { setAddonEnabled } from '../../helpers/factories/settings';+import { setAddonEnabled, setTripAddon } from '../../helpers/factories/settings';import { addTourWaypoints, makeTour } from '../../helpers/factories/tours';import { addTripMember, makeTrip } from '../../helpers/factories/trips';import { makeUser } from '../../helpers/factories/users';@@ -399,4 +399,17 @@ describe('CollectionToursService', () => {),).toEqual(off);});++ it('LIB3-SVC-013: a trip with Tours off has no tour to keep and is no target, the instance on', async () => {+ const f = await fixture();+ const tour = await keep(f);+ vi.spyOn(t.get(PermissionsService), 'checkPermission').mockResolvedValue(true);+ await setTripAddon(orm, f.alps.id, 'tours', false);+ expect(+ await refusal(service.save(f.owner.id, f.list.id, { source_trip_id: f.alps.id, source_place_id: f.ridge.id })),+ ).toEqual({ status: 404, error: 'Tour not found' });+ expect(await countRows(orm, CollectionTours)).toBe(1);+ const detail = await service.detail({ id: f.owner.id, role: 'user' }, f.list.id, tour.id);+ expect(detail.trips.map((trip) => trip.title).sort()).toEqual(['Away', 'Next']);+ });});diff --git a/server/tests/unit/nest/doc-sync/doc-sync.service.test.ts b/server/tests/unit/nest/doc-sync/doc-sync.service.test.tsindex fd3079137..e88310e46 100644--- a/server/tests/unit/nest/doc-sync/doc-sync.service.test.ts+++ b/server/tests/unit/nest/doc-sync/doc-sync.service.test.ts@@ -283,11 +283,8 @@ const sqlTime = (modifier: string): string =>// test-sql-allow: the timestamp has to come from SQLite's own clock, the one CURRENT_TIMESTAMP compares against.(testDb.prepare("SELECT datetime('now', ?) AS t").get(modifier) as { t: string }).t;-/**- * The Documents addon. Every binding asks it before it runs, so a double that- * always says yes would hide the one case worth a test.- */-const addons = { isAddonEnabled: vi.fn(() => true) };+/** The Documents addon (instance, then trip). An always-yes double would hide the one case worth a test. */+const addons = { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async (_t: number, _a: string) => true) };/** The admin's per-provider switch, which is a real row rather than a double. */const switchProvider = (id: string, on: boolean) =>@@ -1070,14 +1067,16 @@ describe('DocSyncService', () => {expect(await itemRow(itemId)).toEqual(itemBefore);});- it('stands down the same way while the Documents addon is off', async () => {+ it.each(['instance', 'trip'] as const)('stands down the same way with Documents off for the %s', async (where) => {const link = await makeLink();const before = await linkRow(link.id);- addons.isAddonEnabled.mockReturnValue(false);+ if (where === 'instance') addons.isAddonEnabled.mockReturnValue(false);+ else addons.isEnabledForTrip.mockResolvedValue(false);const res = await service.syncLink(link);expect(res.state).toBe('disabled');+ if (where === 'trip') expect(addons.isEnabledForTrip).toHaveBeenCalledWith(link.trip_id, 'documents');expect(provider.list).not.toHaveBeenCalled();expect(await linkRow(link.id)).toEqual(before);});diff --git a/server/tests/unit/nest/files.controller.test.ts b/server/tests/unit/nest/files.controller.test.tsindex 6ea73076e..5ee412e04 100644--- a/server/tests/unit/nest/files.controller.test.ts+++ b/server/tests/unit/nest/files.controller.test.ts@@ -1,9 +1,13 @@+import type { AddonsService } from '../../../src/nest/addons/addons.service';+import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';import { isDemoEmail } from '../../../src/nest/common/demo';import { DomainError } from '../../../src/nest/common/domain-error';import { FilesDownloadController } from '../../../src/nest/files/files-download.controller';import { FilesController } from '../../../src/nest/files/files.controller';import type { FilesService } from '../../../src/nest/files/files.service';+import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import { PhotosController } from '../../../src/nest/photos/photos.controller';import type { PhotosService } from '../../../src/nest/photos/photos.service';import type { StorageService } from '../../../src/nest/storage/storage.service';@@ -29,9 +33,13 @@ function fsvc(o: Partial<FilesService> = {}): FilesService {const storageStub = { put: vi.fn().mockResolvedValue(undefined) } as unknown as StorageService;+/** Whether Documents applies to the trip: on, unless a test switches it off for its trip. */+const addonsOn = { isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService;+const addonsOff = { isEnabledForTrip: vi.fn(async () => false) } as unknown as AddonsService;+/** Construct the controller with the standard env + storage stubs. */-function fc(svc: FilesService): FilesController {- return new FilesController(svc, new RuntimeEnvService(), storageStub);+function fc(svc: FilesService, addons: AddonsService = addonsOn): FilesController {+ return new FilesController(svc, new RuntimeEnvService(), storageStub, addons);}function thrown(fn: () => unknown): { status: number; body: unknown } {@@ -66,6 +74,21 @@ const trip = { id: 5, user_id: 42 } as never;// The 404 "Trip not found" cases moved to trip-access.guard.test.ts with the check.describe('FilesController (parity with the legacy /api/trips/:tripId/files route)', () => {+ it('every route but the multipart upload asks the trip and then the Documents addon of that trip', () => {+ expect(Reflect.getMetadata(REQUIRE_ADDON, FilesController)).toEqual({ addonId: 'documents', label: 'Documents' });+ const proto = FilesController.prototype as unknown as Record<string, unknown>;+ const routes = Object.getOwnPropertyNames(FilesController.prototype)+ .map((name) => proto[name])+ .filter((fn) => typeof fn === 'function' && Reflect.getMetadata('method', fn as object) !== undefined);+ const guarded = routes.filter((fn) => fn !== FilesController.prototype.upload);+ expect(guarded.length).toBeGreaterThan(8);+ for (const handler of guarded) {+ expect(Reflect.getMetadata('__guards__', handler as object)).toEqual([TripAccessGuard, TripAddonGuard]);+ }+ // A guard on the multipart route would answer before multer read the body (ECONNRESET), so it checks inside.+ expect(Reflect.getMetadata('__guards__', FilesController.prototype.upload)).toBeUndefined();+ });+it('GET / lists with the trash flag', async () => {const listFiles = vi.fn().mockReturnValue([{ id: 1 }]);expect(await fc(fsvc({ listFiles } as Partial<FilesService>)).list(user, trip, '5', 'true')).toEqual({@@ -86,6 +109,16 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route});const file = { filename: 'a.pdf' } as Express.Multer.File;+ it('404 while Documents is off for the trip, after the trip check and before anything is stored', async () => {+ const svc = fsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }) });+ expect(await rejected(fc(svc, addonsOff).upload(user, '5', file, {}))).toEqual({+ status: 404,+ body: { error: 'Documents addon is not enabled' },+ });+ expect(addonsOff.isEnabledForTrip).toHaveBeenCalledWith(5, 'documents');+ expect(storageStub.put).not.toHaveBeenCalled();+ });+it('403 in demo mode for a demo email', async () => {process.env.DEMO_MODE = 'true';vi.mocked(isDemoEmail).mockReturnValue(true);@@ -439,7 +472,7 @@ describe('FilesDownloadController', () => {const s = dsvc({authenticateDownload: vi.fn().mockRejectedValue(new DomainError(401, 'Authentication required')),});- expect(await rejected(new FilesDownloadController(s, dstor()).download(req, res, '5', '9'))).toEqual({+ expect(await rejected(new FilesDownloadController(s, dstor(), addonsOn).download(req, res, '5', '9'))).toEqual({status: 401,body: { error: 'Authentication required' },});@@ -448,45 +481,56 @@ describe('FilesDownloadController', () => {it('404 without trip access and 404 for an unknown file', async () => {expect(await rejected(- new FilesDownloadController(dsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), dstor()).download(- req,- res,- '5',- '9',- ),+ new FilesDownloadController(+ dsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }),+ dstor(),+ addonsOn,+ ).download(req, res, '5', '9'),),).toEqual({ status: 404, body: { error: 'Trip not found' } });expect(await rejected(- new FilesDownloadController(dsvc({ getFileById: vi.fn().mockReturnValue(undefined) }), dstor()).download(- req,- res,- '5',- '9',- ),+ new FilesDownloadController(+ dsvc({ getFileById: vi.fn().mockReturnValue(undefined) }),+ dstor(),+ addonsOn,+ ).download(req, res, '5', '9'),),).toEqual({ status: 404, body: { error: 'File not found' } });});- it('404 when the object is gone from storage', async () => {- const storage = dstor({ exists: vi.fn().mockResolvedValue(false) });- expect(await rejected(new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'))).toEqual({+ it('404 while Documents is off for the trip, before the file is looked up', async () => {+ const s = dsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }) });+ expect(await rejected(new FilesDownloadController(s, dstor(), addonsOff).download(req, res, '5', '9'))).toEqual({status: 404,- body: { error: 'File not found' },+ body: { error: 'Documents addon is not enabled' },});+ expect(s.getFileById).not.toHaveBeenCalled();+ });++ it('404 when the object is gone from storage', async () => {+ const storage = dstor({ exists: vi.fn().mockResolvedValue(false) });+ expect(await rejected(new FilesDownloadController(dsvc(), storage, addonsOn).download(req, res, '5', '9'))).toEqual(+ {+ status: 404,+ body: { error: 'File not found' },+ },+ );});it('404 when the stored name is an invalid key (exists rejects)', async () => {const storage = dstor({ exists: vi.fn().mockRejectedValue(new Error('invalid storage key')) });- expect(await rejected(new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'))).toEqual({- status: 404,- body: { error: 'File not found' },- });+ expect(await rejected(new FilesDownloadController(dsvc(), storage, addonsOn).download(req, res, '5', '9'))).toEqual(+ {+ status: 404,+ body: { error: 'File not found' },+ },+ );});it('streams a regular file through storage with no wallet headers', async () => {const storage = dstor();- await new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9');+ await new FilesDownloadController(dsvc(), storage, addonsOn).download(req, res, '5', '9');expect(storage.exists).toHaveBeenCalledWith('files', 'x.pdf');expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'x.pdf', res, undefined);});@@ -494,7 +538,7 @@ describe('FilesDownloadController', () => {it('tolerates a stray prefixed row via basename(), same as the download controller', async () => {const storage = dstor();const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'files/x.pdf', original_name: 'x.pdf' }) });- await new FilesDownloadController(s, storage).download(req, res, '5', '9');+ await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'x.pdf', res, undefined);});@@ -503,7 +547,7 @@ describe('FilesDownloadController', () => {const s = dsvc({getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: 'BoardingPass.pkpass' }),});- await new FilesDownloadController(s, storage).download(req, res, '5', '9');+ await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, {contentType: 'application/vnd.apple.pkpass',disposition: 'inline; filename="BoardingPass.pkpass"',@@ -515,7 +559,7 @@ describe('FilesDownloadController', () => {const s = dsvc({getFileById: vi.fn().mockReturnValue({ filename: 'passes.pkpasses', original_name: 'BoardingPasses.pkpasses' }),});- await new FilesDownloadController(s, storage).download(req, res, '5', '9');+ await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'passes.pkpasses', res, {contentType: 'application/vnd.apple.pkpasses',disposition: 'inline; filename="BoardingPasses.pkpasses"',@@ -525,7 +569,7 @@ describe('FilesDownloadController', () => {it('falls back to the stored basename when a .pkpass has no original name', async () => {const storage = dstor();const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: null }) });- await new FilesDownloadController(s, storage).download(req, res, '5', '9');+ await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, {contentType: 'application/vnd.apple.pkpass',disposition: 'inline; filename="pass.pkpass"',@@ -540,7 +584,7 @@ describe('FilesDownloadController', () => {const s = dsvc({getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: '搭乗券.pkpass' }),});- await new FilesDownloadController(s, storage).download(req, res, '5', '9');+ await new FilesDownloadController(s, storage, addonsOn).download(req, res, '5', '9');expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, {contentType: 'application/vnd.apple.pkpass',disposition: 'inline; filename="download.pkpass"; filename*=UTF-8\'\'%E6%90%AD%E4%B9%97%E5%88%B8.pkpass',diff --git a/server/tests/unit/nest/hike-plan.mcp.test.ts b/server/tests/unit/nest/hike-plan.mcp.test.tsindex 3a80f1fec..ccc4c5751 100644--- a/server/tests/unit/nest/hike-plan.mcp.test.ts+++ b/server/tests/unit/nest/hike-plan.mcp.test.ts@@ -264,10 +264,10 @@ describe('HikePlanMcp: the tools and their gates', () => {expect(tools[1].description).toContain('route_pending');expect(tools[2].description).toContain('expected_revision');expect(tools[3].description).toContain('skipped');- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');- const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');+ const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })));expect(gated).toEqual([true, true, true, true]);- expect(isAddonEnabled).toHaveBeenCalledWith('tours');+ expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');});it('HIKE-MCP-002: an outsider is refused every tool, and the writes are refused without place_edit, as REST refuses them', async () => {diff --git a/server/tests/unit/nest/integrations/airtrailImport.test.ts b/server/tests/unit/nest/integrations/airtrailImport.test.tsindex ed845d654..d1f73a5fa 100644--- a/server/tests/unit/nest/integrations/airtrailImport.test.ts+++ b/server/tests/unit/nest/integrations/airtrailImport.test.ts@@ -25,6 +25,7 @@ import { createUser, createTrip } from '../../../helpers/factories';import { findRow, findRows } from '../../../helpers/factories/rows';import { createTestBudgetItemsRepo } from '../../../helpers/files-repos';import { notificationsStub } from '../../../helpers/notifications';+import { createTestAddonsService } from '../../../helpers/test-addons';import {createTestUnitOfWork,createTestAppSettingsRepo,@@ -89,6 +90,7 @@ async function makeImportService(): Promise<AirtrailImportService> {await createTestUsersRepo(db),await createTestTripsRepo(db),await createTestBudgetItemsRepo(db),+ await createTestAddonsService(db),),{ listFlights } as unknown as AirtrailClient,{diff --git a/server/tests/unit/nest/notification-preferences.service.test.ts b/server/tests/unit/nest/notification-preferences.service.test.tsindex 7d8ed0b22..998675e95 100644--- a/server/tests/unit/nest/notification-preferences.service.test.ts+++ b/server/tests/unit/nest/notification-preferences.service.test.ts@@ -483,6 +483,25 @@ describe('listed events follow the features that are on', () => {}});+ it('NPREF-LIST-003: a trip addon a trip of the user switched on lists its rows for that user, not in the defaults', async () => {+ const { user: chatty } = createUser(testDb);+ const { user: quiet } = createUser(testDb);+ const { user: admin } = createAdmin(testDb);+ const all = { ...features };+ Object.assign(features, {+ isAddonEnabled: async (id: string) => id !== 'collab',+ isEnabledForUserAnywhere: async (userId: number, id: string) => id === 'collab' && userId === chatty.id,+ });+ try {+ expect((await svc.getPreferencesMatrix(chatty.id, 'user')).event_types).toContain('collab_message');+ expect((await svc.getPreferencesMatrix(quiet.id, 'user')).event_types).not.toContain('collab_message');+ expect((await svc.getPreferencesMatrix(quiet.id, 'user')).event_types).not.toContain('packing_tagged');+ expect((await svc.getInstanceDefaults(admin.id)).event_types).not.toContain('collab_message');+ } finally {+ Object.assign(features, all);+ }+ });+it('NPREF-LIST-002: the flight events are listed only while live flight status is on', async () => {const flights = ['flight_departed', 'flight_delayed', 'flight_landed'];const { user } = createUser(testDb);diff --git a/server/tests/unit/nest/paddle-obstacles/paddle-obstacles.controller.test.ts b/server/tests/unit/nest/paddle-obstacles/paddle-obstacles.controller.test.tsindex a80432858..0caf8cbe3 100644--- a/server/tests/unit/nest/paddle-obstacles/paddle-obstacles.controller.test.ts+++ b/server/tests/unit/nest/paddle-obstacles/paddle-obstacles.controller.test.ts@@ -50,7 +50,7 @@ const region: PaddleRegion = {describe('PaddleObstaclesController', () => {it('PADCTL-001: GET api/paddle/obstacles sits behind the Tours addon ahead of the session check', () => {expect(Reflect.getMetadata(PATH_METADATA, PaddleObstaclesController)).toBe('api/paddle');- expect(Reflect.getMetadata(GUARDS_METADATA, PaddleObstaclesController)).toEqual([AddonGuard, JwtAuthGuard]);+ expect(Reflect.getMetadata(GUARDS_METADATA, PaddleObstaclesController)).toEqual([JwtAuthGuard, AddonGuard]);expect(Reflect.getMetadata(REQUIRE_ADDON, PaddleObstaclesController)).toEqual({ addonId: 'tours', label: 'Tours' });const handler = PaddleObstaclesController.prototype.inBox;expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.GET);diff --git a/server/tests/unit/nest/paddle-routing/paddle-routing.controller.test.ts b/server/tests/unit/nest/paddle-routing/paddle-routing.controller.test.tsindex af5fd5739..3298ef7e4 100644--- a/server/tests/unit/nest/paddle-routing/paddle-routing.controller.test.ts+++ b/server/tests/unit/nest/paddle-routing/paddle-routing.controller.test.ts@@ -7,9 +7,9 @@import { ADDON_IDS } from '../../../../src/addons';import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';-import { AddonGuard } from '../../../../src/nest/addons/addon.guard';import type { AddonsService } from '../../../../src/nest/addons/addons.service';import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';import { PaddleRoutingController } from '../../../../src/nest/paddle-routing/paddle-routing.controller';@@ -56,9 +56,9 @@ describe('PaddleRoutingController', () => {it('PADROUTE-CTL-001: POST api/trips/:tripId/paddle/route sits behind Tours, the session and the trip, answers 200 on the contract', () => {expect(Reflect.getMetadata(PATH_METADATA, PaddleRoutingController)).toBe('api/trips/:tripId/paddle');expect(Reflect.getMetadata(GUARDS_METADATA, PaddleRoutingController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, PaddleRoutingController)).toEqual({ addonId: 'tours', label: 'Tours' });const handler = PaddleRoutingController.prototype.route;@@ -97,15 +97,16 @@ function makeMcp(accessible: boolean) {}describe('PaddleRoutingMcp', () => {- it('PADROUTE-MCP-001: plan_paddle_route is read only, gated on Tours and scoped to reading trips', () => {+ it('PADROUTE-MCP-001: plan_paddle_route is read only, gated on Tours and scoped to reading trips', async () => {const options = toolOptions();expect(options.name).toBe('plan_paddle_route');expect(options.annotations?.readOnlyHint).toBe(true);expect(options.access).toEqual({ group: 'trips', mode: 'read' });- const isAddonEnabled = vi.fn((id: string) => id === ADDON_IDS.TOURS);- const self = { addons: { isAddonEnabled } } as unknown as PaddleRoutingMcp;- expect(options.when?.(ctx, self)).toBe(true);- expect(isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.TOURS);+ // Tours is a trip addon: the tool is offered while it is on for the instance or any trip of the caller.+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === ADDON_IDS.TOURS);+ const self = { addons: { isEnabledForUserAnywhere } } as unknown as PaddleRoutingMcp;+ expect(await options.when?.(ctx, self)).toBe(true);+ expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);});it('PADROUTE-MCP-002: takes the REST contract plus the trip, with the same defaults and limits', () => {diff --git a/server/tests/unit/nest/receipt-scan.controller.test.ts b/server/tests/unit/nest/receipt-scan.controller.test.tsindex c944cd3dd..e1cfba122 100644--- a/server/tests/unit/nest/receipt-scan.controller.test.ts+++ b/server/tests/unit/nest/receipt-scan.controller.test.ts@@ -23,7 +23,7 @@ function make(over: { readsImages?: boolean; trip?: unknown; addon?: boolean; alfindAccessible: vi.fn(async () => ('trip' in over ? over.trip : { user_id: 5 })),} as unknown as TripsRepository),{ checkPermission } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(async () => over.addon ?? true) } as unknown as AddonsService,+ { isEnabledForTrip: vi.fn(async () => over.addon ?? true) } as unknown as AddonsService,);return { c, startReceipt, checkPermission };}diff --git a/server/tests/unit/nest/reminder-jobs.service.test.ts b/server/tests/unit/nest/reminder-jobs.service.test.tsindex 2ef800bbb..5a2b2916f 100644--- a/server/tests/unit/nest/reminder-jobs.service.test.ts+++ b/server/tests/unit/nest/reminder-jobs.service.test.ts@@ -12,6 +12,7 @@ import { Trips } from '../../../src/db/entities/Trips.entity';import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';import type { TodoItemsRepository } from '../../../src/db/repositories/TodoItems.repository';import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';+import type { AddonsService } from '../../../src/nest/addons/addons.service';import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';import { ReminderJobsService } from '../../../src/nest/notifications/reminder-jobs.service';import type { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';@@ -23,7 +24,9 @@ import {setNotificationChannels,} from '../../helpers/factories';import { findRow, updateRows } from '../../helpers/factories/rows';+import { setTripAddon } from '../../helpers/factories/settings';import { notificationsStub } from '../../helpers/notifications';+import { createTestAddonsService } from '../../helpers/test-addons';import { createTestAppSettingsRepo, createTestTripsRepo } from '../../helpers/test-uow';import { sharedTestOrm } from '../../helpers/test-uow';import { createTestTodoItemsRepo } from '../../helpers/todo-repos';@@ -69,6 +72,7 @@ interface Registered {let appSettingsRepo: AppSettingsRepository;let tripsRepo: TripsRepository;let todoItemsRepo: TodoItemsRepository;+let addonsSvc: AddonsService;function makeJobs(overrides: { notifications?: NotificationsService } = {}) {const registered: Registered[] = [];@@ -94,6 +98,7 @@ function makeJobs(overrides: { notifications?: NotificationsService } = {}) {todoItemsRepo,overrides.notifications ?? notificationsStub(send),registrar as unknown as CronRegistrarService,+ addonsSvc,);return { svc, registered, registrar, send };}@@ -122,6 +127,7 @@ beforeAll(async () => {appSettingsRepo = await createTestAppSettingsRepo(testDb);tripsRepo = await createTestTripsRepo(testDb);todoItemsRepo = await createTestTodoItemsRepo(testDb);+ addonsSvc = await createTestAddonsService(testDb);});beforeEach(() => {@@ -347,6 +353,19 @@ describe('todo reminder tick', () => {expect(send).not.toHaveBeenCalled();});+ it('RJOB-018: a trip that has Lists off is reminded of no todo, and the todo stays unclaimed', async () => {+ const { user } = createUser(testDb);+ const trip = createTrip(testDb, user.id, { title: 'Porto' });+ const todo = createTodoItem(testDb, trip.id, { name: 'Book ferry' });+ await setTodo(todo.id, { due_date: dayFromToday(1) });+ await setTripAddon(await orm(), trip.id, 'packing', false);++ const { svc, send } = makeJobs();+ await svc.todoTick();+ expect(send).not.toHaveBeenCalled();+ expect(await remindedAtOf(todo.id)).toBeNull();+ });+it('RJOB-009 — an assigned todo notifies the assignee (user scope)', async () => {const { user } = createUser(testDb);const { user: assignee } = createUser(testDb, { email: '[email protected]', username: 'assignee' });diff --git a/server/tests/unit/nest/reservations.service.test.ts b/server/tests/unit/nest/reservations.service.test.tsindex 15e5fb370..b62bdce6a 100644--- a/server/tests/unit/nest/reservations.service.test.ts+++ b/server/tests/unit/nest/reservations.service.test.ts@@ -67,6 +67,8 @@ import { countRows, deleteRows, findRow, findRows, insertRow, updateRows } fromimport { makeReservation } from '../../helpers/factories/reservations';import { makeTrip, readTripDays } from '../../helpers/factories/trips';import { makeUser } from '../../helpers/factories/users';+import { setTripAddon } from '../../helpers/factories/settings';+import { createTestAddonsService } from '../../helpers/test-addons';import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';import { DayAccommodations } from '../../../src/db/entities/DayAccommodations.entity';import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';@@ -84,7 +86,7 @@ const broadcast = realtime.broadcastMock;let svc: ReservationsService;let orm: TestOrm;beforeAll(async () => {- svc = new ReservationsService(permissionsStub, budget as unknown as BudgetService, realtime, notificationsStub(notif.send), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await makeAccommodationsService(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb));+ svc = new ReservationsService(permissionsStub, budget as unknown as BudgetService, realtime, notificationsStub(notif.send), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), await makeAccommodationsService(testDb, realtime), await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb));});beforeEach(async () => {@@ -843,6 +845,22 @@ describe('ReservationsService (DI-native, real SQL)', () => {svc.announceCost(String(trip.id), out.costEvents, 'sock');expect(broadcast).toHaveBeenCalledWith(String(trip.id), 'budget:updated', { item: { id: item.id } }, 'sock');});++ it('RESV-TX-008: with Costs off for the trip an edit leaves the linked cost as it is, cleared price and new type alike', async () => {+ const { trip, res, item } = await linkedItem({ total_price: 100, category: 'other' });+ await updateRows(orm, Reservations, { id: res.id }, { title: 'Old', type: 'other' });+ await setTripAddon(orm, trip.id, 'budget', false);+ const current = await svc.getReservation(String(res.id), String(trip.id));+ if (!current) throw new Error('the booking was not written');++ const out = await svc.updateWithCost(String(res.id), String(trip.id), { title: 'New', type: 'flight' } as never, current, { total_price: 0 });++ expect(out.costEvents).toEqual([]);+ expect(budget.deleteBudgetItem).not.toHaveBeenCalled();+ expect(budget.updateBudgetItem).not.toHaveBeenCalled();+ expect(await findRow(orm, BudgetItems, { id: item.id })).toMatchObject({ total_price: 100, category: 'other' });+ expect(await findRow(orm, Reservations, { id: res.id })).toMatchObject({ title: 'New', type: 'flight' });+ });});describe('createWithCost', () => {@@ -868,6 +886,17 @@ describe('ReservationsService (DI-native, real SQL)', () => {expect(broadcast).not.toHaveBeenCalled();});+ it('RESV-TX-009: with Costs off for the trip the booking is written without its cost', async () => {+ const { trip } = ownerTrip();+ await setTripAddon(orm, trip.id, 'budget', false);++ const out = await svc.createWithCost(String(trip.id), { title: 'Hotel', type: 'other' } as never, { total_price: 200 });++ expect(out.reservation.id).toBeGreaterThan(0);+ expect(out.costEvents).toEqual([]);+ expect(budget.linkBudgetItemToReservation).not.toHaveBeenCalled();+ });+it('RESV-TX-005: without a price there is no cost and no event', async () => {const { trip } = ownerTrip();const out = await svc.createWithCost(String(trip.id), { title: 'Dinner' } as never, undefined);diff --git a/server/tests/unit/nest/roadtrip-planning.test.ts b/server/tests/unit/nest/roadtrip-planning.test.tsindex 51db78d2d..6f5b07ba1 100644--- a/server/tests/unit/nest/roadtrip-planning.test.ts+++ b/server/tests/unit/nest/roadtrip-planning.test.ts@@ -337,7 +337,7 @@ describe('browser-independent roadtrip calculation', () => {expect(body.undatedRides).toEqual([]);expect(body.days.length).toBeGreaterThan(0);// And the tool says what the field is, or an assistant has no reason to read it.- const addons = { isAddonEnabled: vi.fn(() => true) };+ const addons = { isEnabledForUserAnywhere: vi.fn(async () => true) };const registry = createTestRegistry([new RoadtripPlanningMcp(s.plans, {} as never, addons as never)], {accessPolicy: trekMcpAccessPolicy,validateAccess: trekMcpValidateAccess,@@ -397,7 +397,7 @@ describe('Roadtrip MCP registration and search', () => {});it('hides addon tools when disabled and separates settings reads from writes', async () => {const s = setup();- const addons = { isAddonEnabled: vi.fn(() => true) };+ const addons = { isEnabledForUserAnywhere: vi.fn(async () => true) };const registry = createTestRegistry([new RoadtripPreferencesMcp(s.preferences, addons as never, s.tripsRepo as never, {} as never),@@ -415,7 +415,7 @@ describe('Roadtrip MCP registration and search', () => {expect(names).toContain('get_roadtrip_settings');expect(names).not.toContain('update_roadtrip_settings');names.length = 0;- addons.isAddonEnabled.mockReturnValue(false);+ addons.isEnabledForUserAnywhere.mockResolvedValue(false);await registry.attach(registrar as never, { ...ctx, scopes: null });expect(names).toEqual([]);});@@ -425,11 +425,11 @@ describe('Roadtrip MCP registration and search', () => {[new RoadtripPreferencesMcp(s.preferences,- { isAddonEnabled: () => true } as never,+ { isEnabledForUserAnywhere: async () => true } as never,s.tripsRepo as never,{} as never,),- new RoadtripPlanningMcp(s.plans, {} as never, { isAddonEnabled: () => true } as never),+ new RoadtripPlanningMcp(s.plans, {} as never, { isEnabledForUserAnywhere: async () => true } as never),],{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },);diff --git a/server/tests/unit/nest/roadtrip-read-tools.test.ts b/server/tests/unit/nest/roadtrip-read-tools.test.tsindex 70de00400..aec394343 100644--- a/server/tests/unit/nest/roadtrip-read-tools.test.ts+++ b/server/tests/unit/nest/roadtrip-read-tools.test.ts@@ -102,7 +102,7 @@ describe('roadtrip read tools', () => {{} as never,{} as never,{} as never,- { isAddonEnabled: () => true } as never,+ { isEnabledForUserAnywhere: async () => true } as never,);const registry = createTestRegistry([tool], {accessPolicy: trekMcpAccessPolicy,diff --git a/server/tests/unit/nest/roadtrip.controller.test.ts b/server/tests/unit/nest/roadtrip.controller.test.tsindex 46dcd7a19..724f60c47 100644--- a/server/tests/unit/nest/roadtrip.controller.test.ts+++ b/server/tests/unit/nest/roadtrip.controller.test.ts@@ -10,7 +10,7 @@* The guard chain is asserted through the decorator metadata rather than by* booting Nest: the controller's own comment calls the ORDER load-bearing, and* a class-level assertion is the only thing that fails when somebody removes- * AddonGuard again. `@RequireAddon` is metadata and does nothing on its own, so+ * TripAddonGuard again. `@RequireAddon` is metadata and does nothing on its own, so* dropping the guard from the list is a silent regression that opens all seven* routes on an instance that switched the addon off.*@@ -18,7 +18,7 @@* siblings, pinned in roadtrip.service.test.ts); here only that every write* hands it the REST writer of this trip, user and socket.*/-import { AddonGuard } from '../../../src/nest/addons/addon.guard';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import type { TripWriter } from '../../../src/nest/common/trip-writer';import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';@@ -64,17 +64,17 @@ async function thrown(fn: () => unknown): Promise<{ status: number; body: unknow}describe('RoadtripController — the guard chain', () => {- it('ROADTRIP-CTL-001: the addon gate leads, and the auth and trip guards follow', () => {+ it('ROADTRIP-CTL-001: auth and the trip lead, and the addon gate of the trip follows', () => {const guards = Reflect.getMetadata(GUARDS_METADATA, RoadtripController) as unknown[];- // AddonGuard first, and present at all: @RequireAddon is metadata and inert+ // TripAddonGuard present at all: @RequireAddon is metadata and inert// without it, and the guard is not registered globally either. Without this// line all seven routes answered on an instance that had the addon off,// which is the bug this branch fixed once already.- expect(guards).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);- // It leads because a disabled addon owes an anonymous caller a 404 rather- // than a 401 that tells them the route exists.- expect(guards[0]).toBe(AddonGuard);+ expect(guards).toEqual([JwtAuthGuard, TripAccessGuard, TripAddonGuard]);+ // It follows TripAccessGuard because what applies is the trip's own choice,+ // which only somebody who may see the trip gets to learn.+ expect(guards[guards.length - 1]).toBe(TripAddonGuard);});});diff --git a/server/tests/unit/nest/share.service.test.ts b/server/tests/unit/nest/share.service.test.tsindex eb2aef381..4d2592140 100644--- a/server/tests/unit/nest/share.service.test.ts+++ b/server/tests/unit/nest/share.service.test.ts@@ -42,6 +42,7 @@ import {import { deleteRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows';import { setAppSetting, setUserSetting } from '../../helpers/factories/settings';import { shareServiceRepoArgs } from '../../helpers/share-repos';+import { createTestAddonsService } from '../../helpers/test-addons';import { resetTestDb } from '../../helpers/test-db';import { createTestModule, type TestModule } from '../../helpers/test-module';import type { TestOrm } from '../../helpers/test-orm';@@ -102,6 +103,7 @@ beforeAll(async () => {photoCacheStub,await createTestUnitOfWork(testDb),...(await shareServiceRepoArgs(testDb)),+ await createTestAddonsService(testDb),);});diff --git a/server/tests/unit/nest/ski-routing/ski-routing.controller.test.ts b/server/tests/unit/nest/ski-routing/ski-routing.controller.test.tsindex ea0b362d0..d8706c0d4 100644--- a/server/tests/unit/nest/ski-routing/ski-routing.controller.test.ts+++ b/server/tests/unit/nest/ski-routing/ski-routing.controller.test.ts@@ -7,9 +7,9 @@import { ADDON_IDS } from '../../../../src/addons';import type { McpContext, McpTextResult, ToolOptions } from '../../../../src/nest-mcp';import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';-import { AddonGuard } from '../../../../src/nest/addons/addon.guard';import type { AddonsService } from '../../../../src/nest/addons/addons.service';import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';import { TripAccessGuard } from '../../../../src/nest/permissions/trip-access.guard';@@ -96,9 +96,9 @@ describe('SkiRoutingController', () => {it('SKICTL-001: the routes sit behind Tours, the session and the trip, each on its contract', () => {expect(Reflect.getMetadata(PATH_METADATA, SkiRoutingController)).toBe('api/trips/:tripId/ski');expect(Reflect.getMetadata(GUARDS_METADATA, SkiRoutingController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, SkiRoutingController)).toEqual({ addonId: 'tours', label: 'Tours' });const { route, areaNear, network } = SkiRoutingController.prototype;@@ -160,15 +160,16 @@ function makeMcp(accessible: boolean) {}describe('SkiRoutingMcp', () => {- it('SKIMCP-001: plan_ski_route is read only, gated on Tours and scoped to reading trips', () => {+ it('SKIMCP-001: plan_ski_route is read only, gated on Tours and scoped to reading trips', async () => {const options = toolOptions();expect(options.name).toBe('plan_ski_route');expect(options.annotations?.readOnlyHint).toBe(true);expect(options.access).toEqual({ group: 'trips', mode: 'read' });- const isAddonEnabled = vi.fn((id: string) => id === ADDON_IDS.TOURS);- const self = { addons: { isAddonEnabled } } as unknown as SkiRoutingMcp;- expect(options.when?.(ctx, self)).toBe(true);- expect(isAddonEnabled).toHaveBeenCalledWith(ADDON_IDS.TOURS);+ // Tours is a trip addon: the tool is offered while it is on for the instance or any trip of the caller.+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === ADDON_IDS.TOURS);+ const self = { addons: { isEnabledForUserAnywhere } } as unknown as SkiRoutingMcp;+ expect(await options.when?.(ctx, self)).toBe(true);+ expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(7, ADDON_IDS.TOURS);});it('SKIMCP-002: takes the REST contract plus the trip, with the same defaults and limits', () => {diff --git a/server/tests/unit/nest/tour-activities.controller.test.ts b/server/tests/unit/nest/tour-activities.controller.test.tsindex 165cd5e1b..f37dbbf35 100644--- a/server/tests/unit/nest/tour-activities.controller.test.ts+++ b/server/tests/unit/nest/tour-activities.controller.test.ts@@ -6,8 +6,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import { TourActivitiesController } from '../../../src/nest/tours/tour-activities.controller';@@ -32,9 +32,9 @@ describe('TourActivitiesController', () => {'api/trips/:tripId/tours/:placeId/activities',);expect(Reflect.getMetadata(GUARDS_METADATA, TourActivitiesController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourActivitiesController)).toEqual({ addonId: 'tours', label: 'Tours' });});diff --git a/server/tests/unit/nest/tour-activity-stats.controller.test.ts b/server/tests/unit/nest/tour-activity-stats.controller.test.tsindex 16c299af9..8b38d2431 100644--- a/server/tests/unit/nest/tour-activity-stats.controller.test.ts+++ b/server/tests/unit/nest/tour-activity-stats.controller.test.ts@@ -28,7 +28,7 @@ const answer = { entries: [], uncounted: { unassigned: 0, undated: 0 } };describe('TourActivityStatsController', () => {it('STA2-CTL-001: sits behind the addon and auth guards, not under a trip', () => {expect(Reflect.getMetadata(PATH_METADATA, TourActivityStatsController)).toBe('api/tours/activity-stats');- expect(Reflect.getMetadata(GUARDS_METADATA, TourActivityStatsController)).toEqual([AddonGuard, JwtAuthGuard]);+ expect(Reflect.getMetadata(GUARDS_METADATA, TourActivityStatsController)).toEqual([JwtAuthGuard, AddonGuard]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourActivityStatsController)).toEqual({addonId: 'tours',label: 'Tours',diff --git a/server/tests/unit/nest/tour-change-save.mcp.test.ts b/server/tests/unit/nest/tour-change-save.mcp.test.tsindex 385e54fdc..c51216af8 100644--- a/server/tests/unit/nest/tour-change-save.mcp.test.ts+++ b/server/tests/unit/nest/tour-change-save.mcp.test.ts@@ -419,9 +419,9 @@ describe('TourChangeMcp.saveTourChange (MCP-T03)', () => {const confirmed = z.object(options.inputSchema as ZodRawShape).pick({ confirmed: true });const yes = [true, false, undefined].map((value) => confirmed.safeParse({ confirmed: value }).success);expect(yes).toEqual([true, false, false]);- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');- expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true);- expect(isAddonEnabled).toHaveBeenCalledWith('tours');+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');+ expect(await options.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })).toBe(true);+ expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');});it('TCHG-SAVE-010: a save sent again once saved writes nothing and answers the step it was saved as', async () => {diff --git a/server/tests/unit/nest/tour-change-undo.mcp.test.ts b/server/tests/unit/nest/tour-change-undo.mcp.test.tsindex ced6579f4..574c842d5 100644--- a/server/tests/unit/nest/tour-change-undo.mcp.test.ts+++ b/server/tests/unit/nest/tour-change-undo.mcp.test.ts@@ -500,11 +500,11 @@ describe('TourChangeUndoMcp (MCP-T04)', () => {]);expect(Object.keys(options.inputSchema as object)).toEqual([...fields]);expect(options.description).toContain('planner');- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');- return { isAddonEnabled, open: options.when?.(ctx(1), { addons: { isAddonEnabled } }) };+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');+ return { isEnabledForUserAnywhere, open: options.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } }) };});expect(await Promise.all(gates.map((gate) => gate.open))).toEqual([true, true, true]);- for (const { isAddonEnabled } of gates) expect(isAddonEnabled).toHaveBeenCalledWith('tours');+ for (const { isEnabledForUserAnywhere } of gates) expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');const entry = getEntry(TourChangeUndoMcp as unknown as ClassRef, 'undoTourChange');if (!entry || entry.kind !== 'tool') throw new Error('undoTourChange is no MCP tool');// The fields are zod schemas from @trek/shared, read here by what they answer.diff --git a/server/tests/unit/nest/tour-change.mcp.test.ts b/server/tests/unit/nest/tour-change.mcp.test.tsindex c45b0629a..113fac275 100644--- a/server/tests/unit/nest/tour-change.mcp.test.ts+++ b/server/tests/unit/nest/tour-change.mcp.test.ts@@ -292,8 +292,8 @@ describe('TourChangeMcp (MCP-T02)', () => {]);const terms = ['revision', 'spontaneous stop', 'protected', 'visited or skipped', 'data_gaps', 'create_place'];for (const term of terms) expect(options.description).toContain(term);- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');- expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true);- expect(isAddonEnabled).toHaveBeenCalledWith('tours');+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');+ expect(await options.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })).toBe(true);+ expect(isEnabledForUserAnywhere).toHaveBeenCalledWith(1, 'tours');});});diff --git a/server/tests/unit/nest/tour-drafts.controller.test.ts b/server/tests/unit/nest/tour-drafts.controller.test.tsindex 09cc3cb7a..52283421a 100644--- a/server/tests/unit/nest/tour-drafts.controller.test.ts+++ b/server/tests/unit/nest/tour-drafts.controller.test.ts@@ -4,8 +4,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import { TourDraftsController } from '../../../src/nest/tours/tour-drafts.controller';@@ -33,9 +33,9 @@ describe('TourDraftsController', () => {it('TDRAFT-CTL-001: sits behind the addon guard before auth and trip access; only keeping a draft needs place_edit', () => {expect(Reflect.getMetadata(PATH_METADATA, TourDraftsController)).toBe('api/trips/:tripId/tour-draft');expect(Reflect.getMetadata(GUARDS_METADATA, TourDraftsController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourDraftsController)).toEqual({ addonId: 'tours', label: 'Tours' });const routes = [diff --git a/server/tests/unit/nest/tour-horse-routes.controller.test.ts b/server/tests/unit/nest/tour-horse-routes.controller.test.tsindex 211e9f5a9..7b034aa7d 100644--- a/server/tests/unit/nest/tour-horse-routes.controller.test.ts+++ b/server/tests/unit/nest/tour-horse-routes.controller.test.ts@@ -1,6 +1,6 @@import { ADDON_IDS } from '../../../src/addons';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';@@ -70,9 +70,9 @@ describe('TourHorseRoutesController (HOR-01)', () => {it('HORSE-CTRL-004: sits behind the Tours addon, the session and the trip access, and declares its contract', () => {expect(Reflect.getMetadata(GUARDS_METADATA, TourHorseRoutesController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourHorseRoutesController)).toEqual({addonId: ADDON_IDS.TOURS,diff --git a/server/tests/unit/nest/tour-packing-link.controller.test.ts b/server/tests/unit/nest/tour-packing-link.controller.test.tsindex c91d6f3c0..21c17d7a8 100644--- a/server/tests/unit/nest/tour-packing-link.controller.test.ts+++ b/server/tests/unit/nest/tour-packing-link.controller.test.ts@@ -6,8 +6,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import { TourPackingLinkController } from '../../../src/nest/tours/tour-packing-link.controller';@@ -34,9 +34,9 @@ describe('TourPackingLinkController', () => {it('TPL-CTL-001: sits behind the addon guard before auth and trip access; only the writes need place_edit', () => {expect(Reflect.getMetadata(PATH_METADATA, TourPackingLinkController)).toBe('api/trips/:tripId/tours');expect(Reflect.getMetadata(GUARDS_METADATA, TourPackingLinkController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourPackingLinkController)).toEqual({ addonId: 'tours', label: 'Tours' });const routes = [diff --git a/server/tests/unit/nest/tour-packing.mcp.test.ts b/server/tests/unit/nest/tour-packing.mcp.test.tsindex ae31e15be..963359790 100644--- a/server/tests/unit/nest/tour-packing.mcp.test.ts+++ b/server/tests/unit/nest/tour-packing.mcp.test.ts@@ -133,14 +133,14 @@ describe('TourPackingMcp', () => {if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);return entry.options;};- const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);+ const enabled = vi.spyOn(t.get(AddonsService), 'isEnabledForUserAnywhere').mockResolvedValue(true);const gates = ['getTourPacking', 'linkTourPacking', 'unlinkTourPacking'].map((name) => options(name).when);const open = () => Promise.all(gates.map((gate) => gate?.(ctx(1), mcp)));enabled.mockResolvedValue(true);expect(await open()).toEqual([true, true, true]);- enabled.mockImplementation(async (id: string) => id !== 'packing');+ enabled.mockImplementation(async (_userId: number, id: string) => id !== 'packing');expect(await open()).toEqual([false, false, false]);- enabled.mockImplementation(async (id: string) => id !== 'tours');+ enabled.mockImplementation(async (_userId: number, id: string) => id !== 'tours');expect(await open()).toEqual([false, false, false]);const allowed = (name: string, scopes: string[]) => {diff --git a/server/tests/unit/nest/tour-plan.mcp.test.ts b/server/tests/unit/nest/tour-plan.mcp.test.tsindex 77a21152f..fc545f074 100644--- a/server/tests/unit/nest/tour-plan.mcp.test.ts+++ b/server/tests/unit/nest/tour-plan.mcp.test.ts@@ -246,8 +246,8 @@ describe('TourPlanMcp: the tools and their gates', () => {expect(tools[1].description).toContain('run_pace_seconds_per_km');expect(tools[2].description).toContain('water_context');expect(tools[3].description).toContain('discipline');- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');- const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');+ const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })));expect(gated).toEqual([true, true, true, true]);});diff --git a/server/tests/unit/nest/tour-ski.controller.test.ts b/server/tests/unit/nest/tour-ski.controller.test.tsindex 959d6750b..2efa85d86 100644--- a/server/tests/unit/nest/tour-ski.controller.test.ts+++ b/server/tests/unit/nest/tour-ski.controller.test.ts@@ -5,8 +5,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';@@ -22,9 +22,9 @@ describe('TourSkiController', () => {it('TOUR-SKI-CTL-001: sits behind the addon guard before auth and trip access, and needs place_edit', () => {expect(Reflect.getMetadata(PATH_METADATA, TourSkiController)).toBe('api/trips/:tripId/tours/:placeId/ski');expect(Reflect.getMetadata(GUARDS_METADATA, TourSkiController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourSkiController)).toEqual({ addonId: 'tours', label: 'Tours' });const handler = TourSkiController.prototype.classify;diff --git a/server/tests/unit/nest/tour-stops.mcp.test.ts b/server/tests/unit/nest/tour-stops.mcp.test.tsindex cc85adfed..da68dc42b 100644--- a/server/tests/unit/nest/tour-stops.mcp.test.ts+++ b/server/tests/unit/nest/tour-stops.mcp.test.ts@@ -133,8 +133,8 @@ describe('TourStopsMcp', () => {['remove_tour_stop', false, { group: 'trips', mode: 'write' }],]);expect(tools[0].description).toContain('after_key');- const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');- const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));+ const isEnabledForUserAnywhere = vi.fn(async (_userId: number, id: string) => id === 'tours');+ const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isEnabledForUserAnywhere } })));expect(gated).toEqual([true, true]);});diff --git a/server/tests/unit/nest/tour-visits.controller.test.ts b/server/tests/unit/nest/tour-visits.controller.test.tsindex 41cc166f4..6922bbca2 100644--- a/server/tests/unit/nest/tour-visits.controller.test.ts+++ b/server/tests/unit/nest/tour-visits.controller.test.ts@@ -5,8 +5,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import { TourVisitsController } from '../../../src/nest/tours/tour-visits.controller';@@ -30,9 +30,9 @@ describe('TourVisitsController', () => {it('TOUR-VISITS-CTL-001: sits behind the addon guard before auth and trip access; only a write needs day_edit', () => {expect(Reflect.getMetadata(PATH_METADATA, TourVisitsController)).toBe('api/trips/:tripId/tour-visits');expect(Reflect.getMetadata(GUARDS_METADATA, TourVisitsController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourVisitsController)).toEqual({ addonId: 'tours', label: 'Tours' });const routes = [diff --git a/server/tests/unit/nest/tour-walk-import.controller.test.ts b/server/tests/unit/nest/tour-walk-import.controller.test.tsindex f332ee4b2..2144fe891 100644--- a/server/tests/unit/nest/tour-walk-import.controller.test.ts+++ b/server/tests/unit/nest/tour-walk-import.controller.test.ts@@ -4,8 +4,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import { TourWalkImportController } from '../../../src/nest/tours/tour-walk-import.controller';@@ -28,9 +28,9 @@ describe('TourWalkImportController', () => {it('WALK-IMPORT-CTL-001: sits behind the addon guard before auth and trip access, and needs place_edit', () => {expect(Reflect.getMetadata(PATH_METADATA, TourWalkImportController)).toBe('api/trips/:tripId/tours');expect(Reflect.getMetadata(GUARDS_METADATA, TourWalkImportController)).toEqual([- AddonGuard,JwtAuthGuard,TripAccessGuard,+ TripAddonGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, TourWalkImportController)).toEqual({ addonId: 'tours', label: 'Tours' });const handler = TourWalkImportController.prototype.preview;diff --git a/server/tests/unit/nest/tours-wanderer.mcp.test.ts b/server/tests/unit/nest/tours-wanderer.mcp.test.tsindex e191bf543..7bb9c4a35 100644--- a/server/tests/unit/nest/tours-wanderer.mcp.test.ts+++ b/server/tests/unit/nest/tours-wanderer.mcp.test.ts@@ -31,7 +31,7 @@ const preview = vi.fn<ToursWandererService['preview']>();const importTrail = vi.fn<ToursWandererService['import']>();const checkSource = vi.fn<ToursWandererService['checkSource']>();const hasTripPermission = vi.fn<McpToolGuardsService['hasTripPermission']>();-const isWandererAvailable = vi.fn<AddonsService['isWandererAvailable']>();+const isWandererAllowed = vi.fn<AddonsService['isWandererAllowed']>();let t: TestModule;let mcp: ToursWandererMcp;const orm = () => t.get(MikroORM);@@ -66,12 +66,12 @@ beforeAll(async () => {],});mcp = t.get(ToursWandererMcp);- vi.spyOn(t.get(AddonsService), 'isWandererAvailable').mockImplementation(isWandererAvailable);+ vi.spyOn(t.get(AddonsService), 'isWandererAllowed').mockImplementation(isWandererAllowed);});beforeEach(() => {resetTestDb(db);hasTripPermission.mockReset().mockResolvedValue(true);- isWandererAvailable.mockReset().mockResolvedValue(true);+ isWandererAllowed.mockReset().mockResolvedValue(true);search.mockReset().mockResolvedValue({ trails: [TRAIL], total: 1, page: 1, pageSize: 20 });preview.mockReset().mockResolvedValue({trail: TRAIL,@@ -190,7 +190,7 @@ describe('wanderer over MCP', () => {]);const gate = options[0]?.when;expect(await gate?.(ctx(1), mcp)).toBe(true);- isWandererAvailable.mockResolvedValue(false);+ isWandererAllowed.mockResolvedValue(false);expect(await gate?.(ctx(1), mcp)).toBe(false);});});diff --git a/server/tests/unit/nest/tours.controller.test.ts b/server/tests/unit/nest/tours.controller.test.tsindex 9ed516659..5f3d0ecb6 100644--- a/server/tests/unit/nest/tours.controller.test.ts+++ b/server/tests/unit/nest/tours.controller.test.ts@@ -8,9 +8,9 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import type { AddonsService } from '../../../src/nest/addons/addons.service';import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';import type { PlacesService } from '../../../src/nest/places/places.service';@@ -86,7 +86,7 @@ async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: numberfunction importFixture(o: { addon?: boolean; trip?: typeof trip | undefined; canEdit?: boolean; result?: unknown } = {},) {- const addons = { isAddonEnabled: vi.fn(async () => o.addon ?? true) };+ const addons = { isEnabledForTrip: vi.fn(async () => o.addon ?? true) };const places = {verifyTripAccess: vi.fn(async () => ('trip' in o ? o.trip : trip)),canEdit: vi.fn(async () => o.canEdit ?? true),@@ -110,9 +110,13 @@ describe('ToursController planner routes', () => {expect(legacyDatabaseAccess).not.toHaveBeenCalled();});- it('TOURS-CTL-001: hides every Tours route behind the addon guard before auth', () => {+ it('TOURS-CTL-001: hides every Tours route behind the trip addon guard, after trip access', () => {expect(Reflect.getMetadata(PATH_METADATA, ToursController)).toBe('api/trips/:tripId/tours');- expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);+ expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([+ JwtAuthGuard,+ TripAccessGuard,+ TripAddonGuard,+ ]);expect(Reflect.getMetadata(REQUIRE_ADDON, ToursController)).toEqual({ addonId: 'tours', label: 'Tours' });});@@ -226,15 +230,15 @@ describe('ToursImportController (POST /api/trips/:tripId/tours/import/gpx)', ()expect(await controller.importGpx(user, '7', file)).toBe(allSkipped);});- it('TOURS-IMP-004: addon off is the AddonGuard 404 before any trip lookup', async () => {+ it('TOURS-IMP-004: Tours off for the trip is the TripAddonGuard 404, after the trip lookup', async () => {const { controller, places, tours, addons } = importFixture({ addon: false });expect(await thrownAsync(() => controller.importGpx(user, '7', file))).toEqual({status: 404,body: { error: 'Tours addon is not enabled' },});- expect(addons.isAddonEnabled).toHaveBeenCalledWith('tours');- expect(places.verifyTripAccess).not.toHaveBeenCalled();+ expect(places.verifyTripAccess).toHaveBeenCalledWith('7', user.id);+ expect(addons.isEnabledForTrip).toHaveBeenCalledWith(trip.id, 'tours');expect(tours.importGpxAsTour).not.toHaveBeenCalled();});diff --git a/server/tests/unit/nest/tours.permissions.test.ts b/server/tests/unit/nest/tours.permissions.test.tsindex 1430244ca..3903efbdc 100644--- a/server/tests/unit/nest/tours.permissions.test.ts+++ b/server/tests/unit/nest/tours.permissions.test.ts@@ -7,8 +7,8 @@*/import 'reflect-metadata';-import { AddonGuard } from '../../../src/nest/addons/addon.guard';import type { AddonsService } from '../../../src/nest/addons/addons.service';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';import { extractToken, verifyJwtAndLoadUser } from '../../../src/nest/auth-core/jwt-verify';import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';@@ -95,7 +95,7 @@ function importFixture(canEdit: boolean, canAssign: boolean) {const controller = new ToursImportController({ importGpxAsTour } as unknown as ToursService,places as unknown as PlacesService,- { isAddonEnabled: vi.fn(async () => true) } as unknown as AddonsService,+ { isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,);return { controller, access, permission, importGpxAsTour };}@@ -117,8 +117,12 @@ describe('Tours permission contract (mock-only, no DB)', () => {expect(legacyDatabaseAccess).not.toHaveBeenCalled();});- it('retains addon/JWT/trip guard order and exact write metadata', () => {- expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);+ it('retains JWT/trip/addon guard order and exact write metadata', () => {+ expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([+ JwtAuthGuard,+ TripAccessGuard,+ TripAddonGuard,+ ]);expect(Reflect.getMetadata(GUARDS_METADATA, ToursImportController)).toEqual([JwtAuthGuard]);for (const handler of ['create', 'update'] as const) {expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, ToursController.prototype[handler])).toBe('place_edit');@@ -173,13 +177,8 @@ describe('Tours permission contract (mock-only, no DB)', () => {expect(test.importGpxAsTour).not.toHaveBeenCalled();});- it('preserves addon and JWT refusal without reaching trip resolution', async () => {+ it('refuses without a session before trip resolution, and Tours off for the trip only after it', async () => {const test = fixture('create', true, true);- const addon = new AddonGuard(- { isAddonEnabled: vi.fn(async () => false) } as unknown as AddonsService,- new Reflector(),- );- await expectStatus(() => addon.canActivate(test.context), 404);const jwt = new JwtAuthGuard({ getRepository: vi.fn() } as unknown as EntityManager);vi.mocked(extractToken).mockReturnValue(null);await expectStatus(() => jwt.canActivate(test.context), 401);@@ -187,5 +186,11 @@ describe('Tours permission contract (mock-only, no DB)', () => {vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(null);await expectStatus(() => jwt.canActivate(test.context), 401);expect(test.access).not.toHaveBeenCalled();++ expect(await test.guard.canActivate(test.context)).toBe(true);+ const isEnabledForTrip = vi.fn(async () => false);+ const addon = new TripAddonGuard({ isEnabledForTrip } as unknown as AddonsService, new Reflector());+ await expectStatus(() => addon.canActivate(test.context), 404);+ expect(isEnabledForTrip).toHaveBeenCalledWith(trip.id, 'tours');});});diff --git a/server/tests/unit/nest/trip-addon-tool-gate.test.ts b/server/tests/unit/nest/trip-addon-tool-gate.test.tsnew file mode 100644index 000000000..eadd08c55--- /dev/null+++ b/server/tests/unit/nest/trip-addon-tool-gate.test.ts@@ -0,0 +1,185 @@+/**+ * TRIPADDON-MCP-001..012: the MCP side of the per-trip addons.+ *+ * Two halves. A tool's `when:` gate (addonGate and its siblings) runs once, at+ * attach: it registers a trip addon's tools while the instance or any trip of+ * the user has the addon on, or, for a session pinned to one trip, while that+ * trip has it on. The host's tool gate (trekTripAddonToolGate) runs on every+ * call and asks the trip the call names, so a trip that has the addon off+ * refuses with the REST text and one that switched it on lets the call through.+ */+import type { McpContext, ToolOptions } from '../../../src/nest-mcp';+import { combineToolGates, errorResult } from '../../../src/nest-mcp';+import {+ addonGate,+ addonOffResource,+ addonsOfGate,+ allAddonsGate,+ collabFeatureGate,+ gateOnAddons,+ instanceAddonGate,+ type HasAddons,+} from '../../../src/nest/addons/addon-gate';+import type { AddonsService } from '../../../src/nest/addons/addons.service';+import { trekTripAddonToolGate } from '../../../src/nest/addons/trip-addon-tool-gate';+import type { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';++import { describe, it, expect, vi } from 'vitest';++const ctx = (extra: Partial<McpContext> = {}): McpContext => ({+ userId: 7,+ scopes: null,+ isStaticToken: false,+ ...extra,+});++/**+ * The instance has `instance` on; trip 5 chose `trip5`; the user's trips have+ * `anywhere` on somewhere. Trip 5 is the user's, trip 9 is not.+ */+function addonsStub(o: { instance?: string[]; trip5?: Record<string, boolean>; anywhere?: string[] } = {}) {+ const instance = new Set(o.instance ?? []);+ const anywhere = new Set([...(o.anywhere ?? []), ...instance]);+ return {+ isAddonEnabled: vi.fn(async (id: string) => instance.has(id)),+ isEnabledForTrip: vi.fn(async (tripId: number, id: string) =>+ tripId === 5 ? (o.trip5?.[id] ?? instance.has(id)) : instance.has(id),+ ),+ isEnabledForUserAnywhere: vi.fn(async (_userId: number, id: string) => anywhere.has(id)),+ getCollabFeatures: vi.fn(async () => ({ chat: true, notes: false, links: true, polls: true, whatsnext: true })),+ };+}++const self = (addons: ReturnType<typeof addonsStub>): HasAddons => ({ addons: addons as unknown as AddonsService });++const trips = {+ findAccessible: vi.fn(async (tripId: number, userId: number) =>+ tripId === 5 && userId === 7 ? { id: 5 } : undefined,+ ),+} as unknown as TripAccessService;++const tool = (when?: unknown): ToolOptions => ({ name: 'some_tool', when }) as unknown as ToolOptions;++describe('the attach-time gates', () => {+ it('TRIPADDON-MCP-001: a trip addon is offered while it is on anywhere for the user, any other addon on the instance', async () => {+ const off = addonsStub({ anywhere: ['packing'] });+ expect(await addonGate('packing')(ctx(), self(off))).toBe(true);+ expect(off.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, 'packing');+ expect(await addonGate('budget')(ctx(), self(off))).toBe(false);+ // Vacay has no trip side: only the instance switch counts.+ expect(await addonGate('vacay')(ctx(), self(addonsStub({ anywhere: ['vacay'] })))).toBe(false);+ expect(await addonGate('vacay')(ctx(), self(addonsStub({ instance: ['vacay'] })))).toBe(true);+ });++ it('TRIPADDON-MCP-002: a session pinned to one trip asks that trip alone', async () => {+ const addons = addonsStub({ instance: ['budget'], trip5: { budget: false, roadtrip: true } });+ expect(await addonGate('budget')(ctx({ tripId: 5 }), self(addons))).toBe(false);+ expect(await addonGate('roadtrip')(ctx({ tripId: 5 }), self(addons))).toBe(true);+ expect(addons.isEnabledForUserAnywhere).not.toHaveBeenCalled();+ });++ it('TRIPADDON-MCP-003: allAddonsGate needs every addon, collabFeatureGate the addon and its instance-wide flag', async () => {+ const addons = addonsStub({ anywhere: ['tours'], instance: ['collab'] });+ expect(await allAddonsGate('tours', 'packing')(ctx(), self(addons))).toBe(false);+ expect(await allAddonsGate('tours', 'collab')(ctx(), self(addons))).toBe(true);+ expect(await collabFeatureGate('chat')(ctx(), self(addons))).toBe(true);+ expect(await collabFeatureGate('notes')(ctx(), self(addons))).toBe(false);+ expect(await collabFeatureGate('chat')(ctx({ tripId: 5 }), self(addonsStub({ trip5: { collab: false } })))).toBe(+ false,+ );+ });++ it('TRIPADDON-MCP-004: instanceAddonGate reads the instance switch alone, a trip that switched it on aside', async () => {+ expect(await instanceAddonGate('documents')(ctx(), self(addonsStub({ anywhere: ['documents'] })))).toBe(false);+ expect(await instanceAddonGate('documents')(ctx(), self(addonsStub({ instance: ['documents'] })))).toBe(true);+ });++ it('TRIPADDON-MCP-005: every gate names the addons it stands for; anything else names none', () => {+ expect(addonsOfGate(addonGate('packing'))).toEqual(['packing']);+ expect(addonsOfGate(allAddonsGate('tours', 'packing'))).toEqual(['tours', 'packing']);+ expect(addonsOfGate(collabFeatureGate('polls'))).toEqual(['collab']);+ expect(addonsOfGate(instanceAddonGate('documents'))).toEqual(['documents']);+ expect(addonsOfGate(gateOnAddons(['tours'], async () => true))).toEqual(['tours']);+ expect(addonsOfGate(async () => true)).toEqual([]);+ expect(addonsOfGate(undefined)).toEqual([]);+ expect(addonsOfGate(Object.assign(async () => true, { addonIds: 'tours' }))).toEqual([]);+ });++ it('TRIPADDON-MCP-006: a trip resource whose addon is off answers with the REST text', () => {+ const uri = new URL('trek://trips/5/budget');+ expect(addonOffResource(uri, 'budget')).toEqual({+ contents: [+ { uri: uri.href, mimeType: 'application/json', text: JSON.stringify({ error: 'Costs addon is not enabled' }) },+ ],+ });+ });+});++describe('trekTripAddonToolGate, on every call', () => {+ it('TRIPADDON-MCP-007: a trip that has the addon off refuses the call; one that switched it on lets it through', async () => {+ const addons = addonsStub({ instance: ['budget'], trip5: { budget: false, roadtrip: true } });+ const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);+ expect(await gate(tool(addonGate('budget')), ctx(), { tripId: 5 })).toEqual(+ errorResult('Costs addon is not enabled'),+ );+ expect(await gate(tool(addonGate('roadtrip')), ctx(), { tripId: '5' })).toBeUndefined();+ expect(addons.isEnabledForTrip).toHaveBeenCalledWith(5, 'roadtrip');+ });++ it('TRIPADDON-MCP-008: of several addons the first one off answers', async () => {+ const addons = addonsStub({ instance: ['tours', 'packing'], trip5: { packing: false } });+ const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);+ expect(await gate(tool(allAddonsGate('tours', 'packing')), ctx(), { tripId: 5 })).toEqual(+ errorResult('Packing addon is not enabled'),+ );+ });++ it('TRIPADDON-MCP-009: a tool of no trip addon, or one gated some other way, is left alone', async () => {+ const addons = addonsStub();+ const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);+ expect(await gate(tool(undefined), ctx(), { tripId: 5 })).toBeUndefined();+ expect(await gate(tool(addonGate('vacay')), ctx(), { tripId: 5 })).toBeUndefined();+ expect(+ await gate(+ tool(async () => true),+ ctx(),+ { tripId: 5 },+ ),+ ).toBeUndefined();+ expect(addons.isEnabledForTrip).not.toHaveBeenCalled();+ });++ it('TRIPADDON-MCP-010: a trip the caller cannot see is left to the tool, which answers not found', async () => {+ const addons = addonsStub({ trip5: { budget: false } });+ const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);+ expect(await gate(tool(addonGate('budget')), ctx(), { tripId: 9 })).toBeUndefined();+ expect(addons.isEnabledForTrip).not.toHaveBeenCalled();+ });++ it('TRIPADDON-MCP-011: a call that names no trip asks the pinned trip, else the user anywhere', async () => {+ const addons = addonsStub({ trip5: { packing: false }, anywhere: ['packing'] });+ const gate = trekTripAddonToolGate(addons as unknown as AddonsService, trips);+ expect(await gate(tool(addonGate('packing')), ctx(), {})).toBeUndefined();+ expect(await gate(tool(addonGate('packing')), ctx(), undefined)).toBeUndefined();+ expect(addons.isEnabledForUserAnywhere).toHaveBeenCalledWith(7, 'packing');+ expect(await gate(tool(addonGate('packing')), ctx({ tripId: 5 }), {})).toEqual(+ errorResult('Packing addon is not enabled'),+ );+ expect(await gate(tool(addonGate('budget')), ctx(), {})).toEqual(errorResult('Costs addon is not enabled'));+ });+});++describe('combineToolGates', () => {+ it('TRIPADDON-MCP-012: asks the gates in order, answers with the first refusal and stops there', async () => {+ const first = vi.fn(async () => undefined);+ const second = vi.fn(() => errorResult('no'));+ const third = vi.fn(async () => errorResult('never asked'));+ const gate = combineToolGates(first, second, third);+ const options = tool();+ expect(await gate(options, ctx(), { tripId: 5 })).toEqual(errorResult('no'));+ expect(first).toHaveBeenCalledWith(options, ctx(), { tripId: 5 });+ expect(third).not.toHaveBeenCalled();+ expect(await combineToolGates(first)(options, ctx())).toBeUndefined();+ expect(await combineToolGates()(options, ctx())).toBeUndefined();+ });+});diff --git a/server/tests/unit/nest/trip-addon.guard.test.ts b/server/tests/unit/nest/trip-addon.guard.test.tsnew file mode 100644index 000000000..02380bfef--- /dev/null+++ b/server/tests/unit/nest/trip-addon.guard.test.ts@@ -0,0 +1,108 @@+/**+ * TRIPADDON-GUARD-001..006: TripAddonGuard, the trip-scoped twin of AddonGuard.+ *+ * It answers @RequireAddon with what applies to the one trip TripAccessGuard+ * parked on the request: the owner's choice for the trip, else the instance+ * switch. Both directions are pinned, the trip on although the instance is+ * off and the trip off although the instance is on, with the 404 body+ * AddonGuard has always sent.+ */+import type { AddonsService } from '../../../src/nest/addons/addons.service';+import { RequireAddon } from '../../../src/nest/addons/require-addon.decorator';+import { TripAddonGuard } from '../../../src/nest/addons/trip-addon.guard';+import { TRIP_REQUEST_KEY } from '../../../src/nest/permissions/trip-access.guard';+import { type ExecutionContext, HttpException } from '@nestjs/common';+import { Reflector } from '@nestjs/core';++import { describe, it, expect, vi } from 'vitest';++/** A route group carrying @RequireAddon, as the controllers declare it. */+function decorated(addonId: string | readonly string[], label: string): object {+ @RequireAddon(addonId, label)+ class Gated {}+ return Gated;+}++function ctxFor(cls: object, trip?: { id: number; user_id: number }): ExecutionContext {+ return {+ getHandler: () => () => {},+ getClass: () => cls,+ switchToHttp: () => ({ getRequest: () => (trip ? { [TRIP_REQUEST_KEY]: trip } : {}) }),+ } as unknown as ExecutionContext;+}++/** `chosen` is what applies to each addon on trip 5. */+function addons(chosen: Record<string, boolean>) {+ return {+ isEnabledForTrip: vi.fn(async (_tripId: number, id: string) => chosen[id] ?? false),+ } as unknown as AddonsService & { isEnabledForTrip: ReturnType<typeof vi.fn> };+}++async function refusal(run: () => Promise<unknown>): Promise<{ status: number; body: unknown }> {+ try {+ await run();+ } catch (err) {+ const e = err as HttpException;+ return { status: e.getStatus(), body: e.getResponse() };+ }+ throw new Error('expected a refusal');+}++const TRIP = { id: 5, user_id: 1 };++describe('TripAddonGuard', () => {+ it('TRIPADDON-GUARD-001: a route that did not ask for an addon is never gated, and nothing is read', async () => {+ const svc = addons({});+ expect(await new TripAddonGuard(svc, new Reflector()).canActivate(ctxFor(class {}))).toBe(true);+ expect(svc.isEnabledForTrip).not.toHaveBeenCalled();+ });++ it('TRIPADDON-GUARD-002: a trip that switched the addon on answers, whatever the instance says', async () => {+ const svc = addons({ roadtrip: true });+ const guard = new TripAddonGuard(svc, new Reflector());+ expect(await guard.canActivate(ctxFor(decorated('roadtrip', 'Road trip'), TRIP))).toBe(true);+ expect(svc.isEnabledForTrip).toHaveBeenCalledWith(5, 'roadtrip');+ });++ it('TRIPADDON-GUARD-003: a trip that has the addon off gets the AddonGuard 404 body', async () => {+ const guard = new TripAddonGuard(addons({ budget: false }), new Reflector());+ expect(await refusal(() => guard.canActivate(ctxFor(decorated('budget', 'Costs'), TRIP)))).toEqual({+ status: 404,+ body: { error: 'Costs addon is not enabled' },+ });+ });++ it('TRIPADDON-GUARD-004: of several addons one is enough, as with AddonGuard', async () => {+ const guard = new TripAddonGuard(addons({ tours: false, roadtrip: true }), new Reflector());+ expect(await guard.canActivate(ctxFor(decorated(['tours', 'roadtrip'], 'Tours'), TRIP))).toBe(true);+ const none = new TripAddonGuard(addons({}), new Reflector());+ expect(+ (await refusal(() => none.canActivate(ctxFor(decorated(['tours', 'roadtrip'], 'Tours'), TRIP)))).status,+ ).toBe(404);+ });++ it('TRIPADDON-GUARD-005: without a trip parked by TripAccessGuard it fails closed instead of opening', async () => {+ const svc = addons({ packing: true });+ const guard = new TripAddonGuard(svc, new Reflector());+ await expect(guard.canActivate(ctxFor(decorated('packing', 'Packing')))).rejects.toThrow(/TripAccessGuard/);+ expect(svc.isEnabledForTrip).not.toHaveBeenCalled();+ });++ it('TRIPADDON-GUARD-006: a handler-level requirement overrides the class one', async () => {+ @RequireAddon('tours', 'Tours')+ class Routes {+ @RequireAddon('packing', 'Packing')+ handler() {}+ }+ const svc = addons({ tours: true, packing: false });+ const context = {+ getHandler: () => Routes.prototype.handler,+ getClass: () => Routes,+ switchToHttp: () => ({ getRequest: () => ({ [TRIP_REQUEST_KEY]: TRIP }) }),+ } as unknown as ExecutionContext;+ expect(await refusal(() => new TripAddonGuard(svc, new Reflector()).canActivate(context))).toEqual({+ status: 404,+ body: { error: 'Packing addon is not enabled' },+ });+ });+});diff --git a/server/tests/unit/nest/trip-addons.controller.test.ts b/server/tests/unit/nest/trip-addons.controller.test.tsnew file mode 100644index 000000000..779494b2b--- /dev/null+++ b/server/tests/unit/nest/trip-addons.controller.test.ts@@ -0,0 +1,71 @@+/**+ * TripAddonsController: the route shapes, the guard chain and the owner+ * refusal it declares, and that each handler hands the guard-resolved trip and+ * the caller straight to TripAddonsService. The behaviour behind it is pinned+ * in trip-addons.service.test.ts and over HTTP in trip-addons.e2e.test.ts.+ */+import type { TripAccess } from '../../../src/db/repositories/Trips.repository';+import { TripAddonsController, TripAddonUpdateDto } from '../../../src/nest/addons/trip-addons.controller';+import { TRIP_ADDON_OWNER_ONLY, type TripAddonsService } from '../../../src/nest/addons/trip-addons.service';+import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';+import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';+import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';+import { TRIP_OWNER_KEY, TripOwnerGuard } from '../../../src/nest/permissions/trip-owner.guard';+import type { User } from '../../../src/types';+import { RequestMethod } from '@nestjs/common';+import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';+import { tripAddonsResponseSchema, tripAddonUpdateRequestSchema, type TripAddon } from '@trek/shared';++import { describe, expect, it, vi } from 'vitest';++const trip: TripAccess = { id: 7, user_id: 3, currency: 'EUR' };+const user = { id: 3 } as User;+const addons: TripAddon[] = [+ { id: 'budget', name: 'Costs', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },+];++function makeController() {+ const service = {+ effectiveTripAddons: vi.fn().mockResolvedValue(addons),+ setTripOverride: vi.fn().mockResolvedValue(addons),+ };+ return { service, controller: new TripAddonsController(service as unknown as TripAddonsService) };+}++const proto = TripAddonsController.prototype;++describe('TripAddonsController', () => {+ it('TRIPADDON-CTRL-001: lives under the trip, behind auth and trip access, with no addon gate', () => {+ expect(Reflect.getMetadata(PATH_METADATA, TripAddonsController)).toBe('api/trips/:tripId/addons');+ expect(Reflect.getMetadata(GUARDS_METADATA, TripAddonsController)).toEqual([JwtAuthGuard, TripAccessGuard]);+ });++ it('TRIPADDON-CTRL-002: GET / answers the trip list, declared by the shared response schema', async () => {+ expect(Reflect.getMetadata(METHOD_METADATA, proto.list)).toBe(RequestMethod.GET);+ expect(Reflect.getMetadata(PATH_METADATA, proto.list)).toBe('/');+ expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.list)).toBe(tripAddonsResponseSchema);+ expect(Reflect.getMetadata(GUARDS_METADATA, proto.list)).toBeUndefined();++ const { service, controller } = makeController();+ expect(await controller.list(trip)).toEqual({ tripId: 7, addons });+ expect(service.effectiveTripAddons).toHaveBeenCalledWith(7);+ });++ it('TRIPADDON-CTRL-003: PUT /:addonId is owner-only with the REST refusal text and the shared body', () => {+ expect(Reflect.getMetadata(METHOD_METADATA, proto.update)).toBe(RequestMethod.PUT);+ expect(Reflect.getMetadata(PATH_METADATA, proto.update)).toBe(':addonId');+ expect(Reflect.getMetadata(GUARDS_METADATA, proto.update)).toEqual([TripOwnerGuard]);+ expect(Reflect.getMetadata(TRIP_OWNER_KEY, proto.update)).toEqual({ message: TRIP_ADDON_OWNER_ONLY });+ expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.update)).toBe(tripAddonsResponseSchema);+ expect(TripAddonUpdateDto.schema).toBe(tripAddonUpdateRequestSchema);+ });++ it('TRIPADDON-CTRL-004: PUT hands trip, caller, addon, choice and socket id to the service', async () => {+ const { service, controller } = makeController();+ expect(await controller.update(user, trip, 'budget', { enabled: false }, 'sock-9')).toEqual({ tripId: 7, addons });+ expect(service.setTripOverride).toHaveBeenCalledWith(7, 3, 'budget', false, 'sock-9');++ await controller.update(user, trip, 'budget', { enabled: null });+ expect(service.setTripOverride).toHaveBeenLastCalledWith(7, 3, 'budget', null, undefined);+ });+});diff --git a/server/tests/unit/nest/trip-addons.service.test.ts b/server/tests/unit/nest/trip-addons.service.test.tsnew file mode 100644index 000000000..03c1e7988--- /dev/null+++ b/server/tests/unit/nest/trip-addons.service.test.ts@@ -0,0 +1,263 @@+/**+ * TripAddonsService: whether a trip addon applies to one trip, and the owner's+ * switch for it. Real in-memory SQLite over the container (the service comes+ * out of AddonsModule), the broadcasts recorded by the FakeRealtimeService.+ */+import { TripAddonOverrides } from '../../../src/db/entities/TripAddonOverrides.entity';+import { sessions, type McpSession } from '../../../src/mcp/sessionManager';+import { AddonsModule } from '../../../src/nest/addons/addons.module';+import { AddonsService } from '../../../src/nest/addons/addons.service';+import {+ TRIP_ADDON_NOT_FOUND,+ TRIP_ADDON_OWNER_ONLY,+ TripAddonsService,+} from '../../../src/nest/addons/trip-addons.service';+import { DomainError } from '../../../src/nest/common/domain-error';+import { createSnapshotTestDb } from '../../helpers/db-mock';+import { countRows } from '../../helpers/factories/rows';+import { setAddonEnabled } from '../../helpers/factories/settings';+import { addTripMember, makeTrip } from '../../helpers/factories/trips';+import { makeAdmin, makeUser } from '../../helpers/factories/users';+import { oneByOne } from '../../helpers/one-by-one';+import { resetTestDb } from '../../helpers/test-db';+import { createTestModule, type TestModule } from '../../helpers/test-module';+import { MikroORM } from '@mikro-orm/core';++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';++const db = createSnapshotTestDb();+let t: TestModule;+let svc: TripAddonsService;+let addons: AddonsService;+const orm = () => t.get(MikroORM);++beforeAll(async () => {+ t = await createTestModule({ db, imports: [AddonsModule] });+ svc = t.get(TripAddonsService);+ addons = t.get(AddonsService);+});+beforeEach(() => {+ resetTestDb(db);+ t.realtime.reset();+});+afterAll(async () => {+ await t.close();+ db.close();+});++async function ownedTrip() {+ const { user: owner } = await makeUser(orm());+ const trip = await makeTrip(orm(), owner.id);+ return { owner, trip };+}++async function refusal(work: Promise<unknown>): Promise<DomainError> {+ const error = await work.then(+ () => null,+ (e: unknown) => e,+ );+ expect(error).toBeInstanceOf(DomainError);+ return error as DomainError;+}++describe('TripAddonsService: what applies to a trip', () => {+ it('TRIPADDON-SVC-001: without a choice the trip follows the instance switch', async () => {+ const { trip } = await ownedTrip();+ await setAddonEnabled(orm(), 'roadtrip', false);+ await setAddonEnabled(orm(), 'budget', true);+ expect(await addons.isEnabledForTrip(trip.id, 'roadtrip')).toBe(false);+ expect(await addons.isEnabledForTrip(trip.id, 'budget')).toBe(true);+ });++ it('TRIPADDON-SVC-002: the owner may switch an addon on although the instance has it off, and off although on', async () => {+ const { owner, trip } = await ownedTrip();+ await setAddonEnabled(orm(), 'roadtrip', false);+ await setAddonEnabled(orm(), 'budget', true);+ await svc.setTripOverride(trip.id, owner.id, 'roadtrip', true);+ await svc.setTripOverride(trip.id, owner.id, 'budget', false);+ expect(await addons.isEnabledForTrip(trip.id, 'roadtrip')).toBe(true);+ expect(await addons.isEnabledForTrip(trip.id, 'budget')).toBe(false);+ });++ it('TRIPADDON-SVC-003: a global addon and an unknown id answer with the instance switch alone', async () => {+ const { trip } = await ownedTrip();+ await setAddonEnabled(orm(), 'vacay', true);+ expect(await addons.isEnabledForTrip(trip.id, 'vacay')).toBe(true);+ expect(await addons.isEnabledForTrip(trip.id, 'no_such_addon')).toBe(false);+ });++ it('TRIPADDON-SVC-004: the list holds every trip addon in order, the legacy photo row and other types left out', async () => {+ const { owner, trip } = await ownedTrip();+ await svc.setTripOverride(trip.id, owner.id, 'budget', false);+ const list = await svc.effectiveTripAddons(trip.id);+ const ids = list.map((a) => a.id);+ expect(ids).toEqual(expect.arrayContaining(['packing', 'budget', 'documents', 'collab', 'roadtrip', 'tours']));+ expect(ids).not.toContain('memories');+ expect(ids).not.toContain('vacay');+ expect(ids).not.toContain('mcp');+ const budget = list.find((a) => a.id === 'budget');+ expect(budget).toMatchObject({ enabled: false, instanceEnabled: true, overridden: true });+ expect(typeof budget?.name).toBe('string');+ const packing = list.find((a) => a.id === 'packing');+ expect(packing).toMatchObject({ overridden: false });+ expect(packing?.enabled).toBe(packing?.instanceEnabled);+ });+});++describe('TripAddonsService: routes without a trip', () => {+ it('TRIPADDON-SVC-010: open while the instance has the addon on', async () => {+ const { owner } = await ownedTrip();+ await setAddonEnabled(orm(), 'tours', true);+ expect(await addons.isEnabledForUserAnywhere(owner.id, 'tours')).toBe(true);+ });++ it('TRIPADDON-SVC-011: off for the instance, open once a trip the user owns or belongs to switched it on', async () => {+ const { owner, trip } = await ownedTrip();+ const { user: member } = await makeUser(orm());+ const { user: stranger } = await makeUser(orm());+ await addTripMember(orm(), trip.id, member.id, owner.id);+ await setAddonEnabled(orm(), 'tours', false);+ expect(await addons.isEnabledForUserAnywhere(owner.id, 'tours')).toBe(false);++ await svc.setTripOverride(trip.id, owner.id, 'tours', true);+ expect(await addons.isEnabledForUserAnywhere(owner.id, 'tours')).toBe(true);+ expect(await addons.isEnabledForUserAnywhere(member.id, 'tours')).toBe(true);+ expect(await addons.isEnabledForUserAnywhere(stranger.id, 'tours')).toBe(false);+ });++ it('TRIPADDON-SVC-012: a global addon that is off and an unknown id stay closed', async () => {+ const { owner } = await ownedTrip();+ await setAddonEnabled(orm(), 'vacay', false);+ expect(await addons.isEnabledForUserAnywhere(owner.id, 'vacay')).toBe(false);+ expect(await addons.isEnabledForUserAnywhere(owner.id, 'no_such_addon')).toBe(false);+ });++ it('TRIPADDON-SVC-013: tripsWithAddon keeps the trips the addon applies to, in their order, each as isEnabledForTrip says', async () => {+ const { owner, trip: off } = await ownedTrip();+ const on = await makeTrip(orm(), owner.id);+ const follows = await makeTrip(orm(), owner.id);+ const ids = [on.id, off.id, follows.id];+ await setAddonEnabled(orm(), 'tours', true);+ await svc.setTripOverride(off.id, owner.id, 'tours', false);+ expect(await addons.tripsWithAddon(ids, 'tours')).toEqual([on.id, follows.id]);++ await setAddonEnabled(orm(), 'tours', false);+ await svc.setTripOverride(on.id, owner.id, 'tours', true);+ expect(await addons.tripsWithAddon(ids, 'tours')).toEqual([on.id]);+ expect(await addons.tripsWithAddon([], 'tours')).toEqual([]);+ });++ it('TRIPADDON-SVC-014: tripsWithAddon answers a global addon with its instance switch and an unknown id with none', async () => {+ const { trip } = await ownedTrip();+ await setAddonEnabled(orm(), 'vacay', true);+ expect(await addons.tripsWithAddon([trip.id], 'vacay')).toEqual([trip.id]);+ await setAddonEnabled(orm(), 'vacay', false);+ expect(await addons.tripsWithAddon([trip.id], 'vacay')).toEqual([]);+ expect(await addons.tripsWithAddon([trip.id], 'no_such_addon')).toEqual([]);+ });+});++describe('TripAddonsService: the owner switch', () => {+ it('TRIPADDON-SVC-020: answers the whole list and broadcasts it to the trip, the saving tab left out', async () => {+ const { owner, trip } = await ownedTrip();+ const addons = await svc.setTripOverride(trip.id, owner.id, 'budget', false, 'sock-1');+ expect(addons.find((a) => a.id === 'budget')).toMatchObject({ enabled: false, overridden: true });+ expect(t.realtime.broadcastMock).toHaveBeenCalledTimes(1);+ expect(t.realtime.broadcastMock).toHaveBeenCalledWith(String(trip.id), 'tripAddons:changed', { addons }, 'sock-1');+ });++ it('TRIPADDON-SVC-021: null drops the choice, so the instance setting applies again', async () => {+ const { owner, trip } = await ownedTrip();+ await svc.setTripOverride(trip.id, owner.id, 'budget', false);+ const addons = await svc.setTripOverride(trip.id, owner.id, 'budget', null);+ expect(addons.find((a) => a.id === 'budget')).toMatchObject({ enabled: true, overridden: false });+ expect(await countRows(orm(), TripAddonOverrides, { trip: trip.id })).toBe(0);+ });++ it('TRIPADDON-SVC-022: a member and an admin who does not own the trip are refused, and nothing is written', async () => {+ const { owner, trip } = await ownedTrip();+ const { user: member } = await makeUser(orm());+ const { user: admin } = await makeAdmin(orm());+ await addTripMember(orm(), trip.id, member.id, owner.id);+ await addTripMember(orm(), trip.id, admin.id, owner.id);+ const refused = await oneByOne([member.id, admin.id], (userId) =>+ refusal(svc.setTripOverride(trip.id, userId, 'budget', false)),+ );+ for (const e of refused) {+ expect(e.getStatus()).toBe(403);+ expect(e.publicMessage).toBe(TRIP_ADDON_OWNER_ONLY);+ }+ expect(await countRows(orm(), TripAddonOverrides, { trip: trip.id })).toBe(0);+ expect(t.realtime.broadcastMock).not.toHaveBeenCalled();+ });++ it('TRIPADDON-SVC-023: somebody who cannot see the trip gets a 404', async () => {+ const { trip } = await ownedTrip();+ const { user: stranger } = await makeUser(orm());+ const e = await refusal(svc.setTripOverride(trip.id, stranger.id, 'budget', false));+ expect(e.getStatus()).toBe(404);+ expect(e.publicMessage).toBe('Trip not found');+ });++ it('TRIPADDON-SVC-024: an id that names no trip addon is a 404 and writes nothing', async () => {+ const { owner, trip } = await ownedTrip();+ const unknown = await oneByOne(['vacay', 'memories', 'no_such_addon'], (addonId) =>+ refusal(svc.setTripOverride(trip.id, owner.id, addonId, true)),+ );+ for (const e of unknown) {+ expect(e.getStatus()).toBe(404);+ expect(e.publicMessage).toBe(TRIP_ADDON_NOT_FOUND);+ }+ expect(await countRows(orm(), TripAddonOverrides, { trip: trip.id })).toBe(0);+ expect(t.realtime.broadcastMock).not.toHaveBeenCalled();+ });++ it('TRIPADDON-SVC-025: copyOverrides gives a copied trip the choices of its source', async () => {+ const { owner, trip } = await ownedTrip();+ const copy = await makeTrip(orm(), owner.id);+ await svc.setTripOverride(trip.id, owner.id, 'budget', false);+ await svc.copyOverrides(trip.id, copy.id);+ expect(await addons.isEnabledForTrip(copy.id, 'budget')).toBe(false);+ });+});++describe('TripAddonsService: open MCP sessions', () => {+ /** A live MCP session of `userId`, as the transport keeps it; `closed` says whether it was ended. */+ function liveSession(sid: string, userId: number) {+ const state = { closed: false };+ sessions.set(sid, {+ userId,+ server: { close: () => undefined },+ transport: { close: () => (state.closed = true) },+ } as unknown as McpSession);+ return state;+ }+ afterEach(() => sessions.clear());++ it('TRIPADDON-SVC-030: switching on an addon the instance has off ends the sessions of everyone on the trip', async () => {+ const { owner, trip } = await ownedTrip();+ const { user: member } = await makeUser(orm());+ const { user: stranger } = await makeUser(orm());+ await addTripMember(orm(), trip.id, member.id, owner.id);+ await setAddonEnabled(orm(), 'roadtrip', false);+ const own = liveSession('own', owner.id);+ const asMember = liveSession('member', member.id);+ const other = liveSession('other', stranger.id);++ await svc.setTripOverride(trip.id, owner.id, 'roadtrip', true);+ // Their tools were attached while Road trip was off everywhere for them; a new session offers them.+ expect([own.closed, asMember.closed, other.closed]).toEqual([true, true, false]);+ expect(sessions.has('other')).toBe(true);+ });++ it('TRIPADDON-SVC-031: switching off, or on while the instance has it on, leaves every session alone', async () => {+ const { owner, trip } = await ownedTrip();+ await setAddonEnabled(orm(), 'budget', true);+ const own = liveSession('own', owner.id);+ await svc.setTripOverride(trip.id, owner.id, 'budget', false);+ await svc.setTripOverride(trip.id, owner.id, 'budget', true);+ await setAddonEnabled(orm(), 'roadtrip', false);+ await svc.setTripOverride(trip.id, owner.id, 'roadtrip', false);+ expect(own.closed).toBe(false);+ });+});diff --git a/server/tests/unit/nest/trip-read-model.service.test.ts b/server/tests/unit/nest/trip-read-model.service.test.tsindex 162ad42f3..4a12ab1c3 100644--- a/server/tests/unit/nest/trip-read-model.service.test.ts+++ b/server/tests/unit/nest/trip-read-model.service.test.ts@@ -84,6 +84,7 @@ import {createTestPluginUserErasureQueueRepo,} from '../../helpers/share-repos';import { makeStorageFixture } from '../../helpers/storage-fixture';+import { createTestAddonsService } from '../../helpers/test-addons';import { resetTestDb } from '../../helpers/test-db';import {createTestUnitOfWork,@@ -314,6 +315,7 @@ const buildReadModel = async (tripsRepo: TripsRepository, roster: TripMembersSerawait createTestUsersRepo(testDb),await createTestTripsRepo(testDb),await createTestBudgetItemsRepo(testDb),+ await createTestAddonsService(testDb),),new CollabService(// Plan 4 Task 2 — CollabService's own DatabaseService param is gone:@@ -364,6 +366,7 @@ const buildReadModel = async (tripsRepo: TripsRepository, roster: TripMembersSerawait createTestBudgetItemsRepo(testDb),{ releaseValues: async () => [] } as never, // StorageReleaseService),+ await createTestAddonsService(testDb),);let svc: Awaited<ReturnType<typeof buildReadModel>>;@@ -542,7 +545,7 @@ describe('bundle shaping', () => {members: undefined,} as never);try {- const result = (await svc.bundle(String(trip.id), { user_id: owner.id }, owner.id)) as any;+ const result = (await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, owner.id)) as any;expect(result.members).toEqual([{ id: owner.id, username: 'solo' }]);} finally {roster.mockRestore();@@ -561,7 +564,7 @@ describe('bundle shaping', () => {members: [{ id: 42, username: 'left-behind' }],} as never);try {- const result = (await svc.bundle(String(trip.id), { user_id: owner.id }, owner.id)) as any;+ const result = (await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, owner.id)) as any;expect(result.members).toEqual([{ id: 42, username: 'left-behind' }]);} finally {roster.mockRestore();@@ -586,7 +589,7 @@ describe('private packing items stay viewer-scoped (#858)', () => {expect(asViewer.packing.items.map((i: any) => i.name)).toEqual(['Tent']);expect(asViewer.packing.total).toBe(1);- const bundled = (await svc.bundle(String(trip.id), { user_id: owner.id }, viewer.id)) as any;+ const bundled = (await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, viewer.id)) as any;expect(bundled.packingItems.map((i: any) => i.name)).toEqual(['Tent']);// The owner still sees their own private item through both paths, so the@@ -596,7 +599,7 @@ describe('private packing items stay viewer-scoped (#858)', () => {'Tent',]);expect(- ((await svc.bundle(String(trip.id), { user_id: owner.id }, owner.id)) as any).packingItems.map(+ ((await svc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, owner.id)) as any).packingItems.map((i: any) => i.name,),).toEqual(['Ring', 'Tent']);diff --git a/server/tests/unit/nest/trips.service.test.ts b/server/tests/unit/nest/trips.service.test.tsindex 7798db050..7697c3cb4 100644--- a/server/tests/unit/nest/trips.service.test.ts+++ b/server/tests/unit/nest/trips.service.test.ts@@ -54,6 +54,7 @@ import { buildPlaceImportService } from '../../helpers/place-import';import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';import { TripMembersService } from '../../../src/nest/trip-members/trip-members.service';import { TripReadModelService } from '../../../src/nest/trip-read-model/trip-read-model.service';+import { createTestAddonsService } from '../../helpers/test-addons';import { AccommodationsService } from '../../../src/nest/accommodations/accommodations.service';import { accommodationsOver, makeAccommodationsService } from '../../helpers/accommodations-service';import { buildMapsService } from '../../helpers/maps-service';@@ -284,7 +285,7 @@ beforeAll(async () => {// which comes out of its own module instead of a constructor call here.membership = await createTestModule({ db: testDb, imports: [TripMembershipModule] });svc = new TripsService(- new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),+ new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb)),daysSvc,new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),budgetSvc,@@ -302,7 +303,7 @@ beforeAll(async () => {{ releaseValues: async () => [] } as never, // StorageReleaseService: the cover release has its own suiteawait createTestUnitOfWork(testDb),(await sharedTestOrm(testDb)).em,- new SettingsService(await createTestUnitOfWork(testDb), await createTestAppSettingsRepo(testDb), await createTestSettingsRepo(testDb), membership.get(TripMembershipService)),+ new SettingsService(await createTestUnitOfWork(testDb), await createTestAppSettingsRepo(testDb), await createTestSettingsRepo(testDb), membership.get(TripMembershipService)), { copyOverrides: async () => {} } as never,);membersSvc = new TripMembersService(budgetSvc, new UserCleanupService(new MaintenanceRepository(dbsEm!), budgetSvc, await createTestUnitOfWork(testDb), await createTestUsersRepo(testDb), await createTestTripMembersRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestBudgetSettlementsRepo(testDb), await createTestJourneyShareTokensRepo(testDb), await createTestJourneysRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestJourneyContributorsRepo(testDb), await createTestShareTokensRepo(testDb), await createTestPluginsRepo(testDb), await createTestPluginUserErasureQueueRepo(testDb), { releaseValues: async () => [] } as never), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), realtime, notificationsStub(), await createTestUnitOfWork(testDb), await createTestTripsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb));readModelSvc = new TripReadModelService(@@ -313,7 +314,7 @@ beforeAll(async () => {await createTestPackingCategoryAssigneesRepo(testDb), await createTestPackingTemplatesRepo(testDb), await createTestPackingTemplateCategoriesRepo(testDb),await createTestPackingTemplateItemsRepo(testDb), await createTestTripsRepo(testDb), await createTestTripMembersRepo(testDb),),- new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb)),+ new ReservationsService(new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), budgetSvc, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb)), accommodationsSvc, await createTestUnitOfWork(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb), await createTestReservationTravelersRepo(testDb), await createTestReservationDayPositionsRepo(testDb), await createTestDayAccommodationsRepo(testDb), await createTestDaysRepo(testDb), await createTestPlacesRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestTripMembersRepo(testDb), await createTestUsersRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), await createTestAddonsService(testDb)),new CollabService(// Plan 4 Task 2 — CollabService's own DatabaseService param is gone:// canAccessTrip now reads through the TripsRepository at the end.@@ -333,19 +334,15 @@ beforeAll(async () => {// Plan 4 Task 2 — canAccessTrip is TripsRepository.findAccessible, in the same constructor slot.new TripAccessService(await createTestTripsRepo(testDb)),new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),- realtime,- new EphemeralTokenService(),- coversFx.storage,+ realtime, new EphemeralTokenService(), coversFx.storage,(await sharedTestOrm(testDb)).em,await createTestUnitOfWork(testDb),- await createTestTripFilesRepo(testDb),- await createTestFileLinksRepo(testDb),- await createTestReservationsRepo(testDb),- await createTestPlacesRepo(testDb),- await createTestDayAssignmentsRepo(testDb),- await createTestBudgetItemsRepo(testDb),+ await createTestTripFilesRepo(testDb), await createTestFileLinksRepo(testDb),+ await createTestReservationsRepo(testDb), await createTestPlacesRepo(testDb),+ await createTestDayAssignmentsRepo(testDb), await createTestBudgetItemsRepo(testDb),{ releaseValues: async () => [] } as never, // StorageReleaseService),+ await createTestAddonsService(testDb), // what the bundle sends follows the trip's addons);});@@ -1505,7 +1502,7 @@ describe('TripsService wrapper helpers', () => {await insertRow(await orm(), PackingItems, { trip: trip.id, name: 'Secret', is_private: 1, owner: owner.id });await insertRow(await orm(), PackingItems, { trip: trip.id, name: 'Shared' });- const result = (await readModelSvc.bundle(String(trip.id), { user_id: owner.id }, viewer.id)) as any;+ const result = (await readModelSvc.bundle(String(trip.id), { id: trip.id, user_id: owner.id }, viewer.id)) as any;expect(result.days).toHaveLength(2);expect(result.members.map((m: any) => m.id).sort()).toEqual([owner.id, viewer.id].sort());expect(result.packingItems.map((p: any) => p.name)).toEqual(['Shared']);diff --git a/server/tests/unit/nest/wanderer-watch.controller.test.ts b/server/tests/unit/nest/wanderer-watch.controller.test.tsindex 6eb44c398..be5c76dc5 100644--- a/server/tests/unit/nest/wanderer-watch.controller.test.ts+++ b/server/tests/unit/nest/wanderer-watch.controller.test.ts@@ -35,11 +35,12 @@ function watchService() {}describe('WandererWatchController', () => {- it('WWCTL-001: sits beside the connection, behind Tours, auth and the wanderer switch', () => {+ it('WWCTL-001: sits beside the connection, behind auth, Tours for the caller and the wanderer switch', () => {expect(Reflect.getMetadata(PATH_METADATA, WandererWatchController)).toBe('api/integrations/wanderer/watch');+ // Auth first: the watch belongs to no one trip, so Tours opens once the caller is known (any trip of theirs).expect(Reflect.getMetadata(GUARDS_METADATA, WandererWatchController)).toEqual([- AddonGuard,JwtAuthGuard,+ AddonGuard,WandererEnabledGuard,]);expect(Reflect.getMetadata(REQUIRE_ADDON, WandererWatchController)).toEqual({ addonId: 'tours', label: 'Tours' });diff --git a/server/tests/unit/packing/packing.rpc.test.ts b/server/tests/unit/packing/packing.rpc.test.tsindex 7cc418108..f117fcac5 100644--- a/server/tests/unit/packing/packing.rpc.test.ts+++ b/server/tests/unit/packing/packing.rpc.test.ts@@ -85,7 +85,7 @@ function build(opts: { canEdit?: boolean; before?: Item | undefined; updated?: I),} as unknown as TripsRepository,{ checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,);const rpc = new PackingRpc(packing, realtime, guards);diff --git a/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts b/server/tests/unit/plugins/addon-domains-errors.rpc.test.tsindex e02a32b7e..f6204a244 100644--- a/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts+++ b/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts@@ -53,7 +53,7 @@ function build(const guards = new PluginGuards(db,{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,);const realtime = { broadcast: vi.fn() } as never;diff --git a/server/tests/unit/plugins/addon-gates.rpc.test.ts b/server/tests/unit/plugins/addon-gates.rpc.test.tsindex 3545b432d..3e5aa78bb 100644--- a/server/tests/unit/plugins/addon-gates.rpc.test.ts+++ b/server/tests/unit/plugins/addon-gates.rpc.test.ts@@ -74,7 +74,7 @@ function build(addonOn: boolean) {const guards = new PluginGuards(db,{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(() => addonOn) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => addonOn), isEnabledForTrip: vi.fn(async () => addonOn) } as unknown as AddonsService,{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,);const registry = createTestPluginRegistry([@@ -168,8 +168,10 @@ describe('every addon-gated plugin method refuses when its addon is off', () =>expect(res.ok).toBe(false);expect(res.error.code).toBe('RESOURCE_FORBIDDEN');expect(res.error.message).toBe(`the ${addon} addon is disabled`);- // The gate has to come before the service, not after it.- expect(f.calls).toEqual([]);+ // The gate has to come before the service, not after it. listMine first reads which trips the+ // user has, since a trip of theirs may have switched Costs on while the instance has it off.+ const reads = method === 'costs.listMine' ? ['membership.listAccessibleTripIds'] : [];+ expect(f.calls).toEqual(reads);});}diff --git a/server/tests/unit/plugins/plugin-event-addons.test.ts b/server/tests/unit/plugins/plugin-event-addons.test.tsnew file mode 100644index 000000000..a4c23a8c5--- /dev/null+++ b/server/tests/unit/plugins/plugin-event-addons.test.ts@@ -0,0 +1,61 @@+/**+ * PEVADDON-001..004: the plugin event sink with the trip's addons in front.+ *+ * A trip that has an addon off shows none of its rows, so a subscribed plugin+ * gets none of that family's events either; every other event goes out at once.+ */+import type { AddonsService } from '../../../src/nest/addons/addons.service';+import { tripAddonOfEvent, tripEventSink } from '../../../src/nest/plugins/plugin-event-addons';++import { describe, it, expect, vi } from 'vitest';++/** Lets the sink's pending addon read settle. */+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++describe('the plugin event sink per trip', () => {+ it('PEVADDON-001: an event names its trip addon by family; a trip event names none', () => {+ expect(tripAddonOfEvent('budget:created')).toBe('budget');+ expect(tripAddonOfEvent('packing:updated')).toBe('packing');+ expect(tripAddonOfEvent('todo:deleted')).toBe('packing');+ expect(tripAddonOfEvent('file:created')).toBe('documents');+ expect(tripAddonOfEvent('collab:message:created')).toBe('collab');+ expect(tripAddonOfEvent('roadtripVia:created')).toBe('roadtrip');+ expect(tripAddonOfEvent('tours:updated')).toBe('tours');+ expect(tripAddonOfEvent('place:created')).toBeNull();+ expect(tripAddonOfEvent('toString:x')).toBeNull();+ });++ it('PEVADDON-002: an event of no addon goes out at once, without asking', () => {+ const deliver = vi.fn();+ const addons = { isEnabledForTrip: vi.fn() } as unknown as AddonsService;+ tripEventSink(addons, undefined, deliver)(5, 'place:created', undefined);+ expect(deliver).toHaveBeenCalledWith(5, 'place:created', undefined);+ expect(addons.isEnabledForTrip).not.toHaveBeenCalled();+ });++ it('PEVADDON-003: an addon event goes out only for a trip that has the addon on', async () => {+ const deliver = vi.fn();+ const addons = {+ isEnabledForTrip: vi.fn(async (tripId: number, id: string) => !(tripId === 5 && id === 'budget')),+ } as unknown as AddonsService;+ const sink = tripEventSink(addons, undefined, deliver);+ sink(5, 'budget:created', undefined);+ sink(6, 'budget:created', undefined);+ sink(5, 'packing:created', undefined);+ await settle();+ expect(deliver.mock.calls.map(([tripId, event]) => `${tripId} ${event}`)).toEqual([+ '6 budget:created',+ '5 packing:created',+ ]);+ });++ it('PEVADDON-004: an addon that cannot be read sends nothing', async () => {+ const deliver = vi.fn();+ const addons = {+ isEnabledForTrip: vi.fn(async () => Promise.reject(new Error('db gone'))),+ } as unknown as AddonsService;+ tripEventSink(addons, undefined, deliver)(5, 'file:created', undefined);+ await settle();+ expect(deliver).not.toHaveBeenCalled();+ });+});diff --git a/server/tests/unit/plugins/rpc-fallbacks.test.ts b/server/tests/unit/plugins/rpc-fallbacks.test.tsindex f33bfb73d..e5331646f 100644--- a/server/tests/unit/plugins/rpc-fallbacks.test.ts+++ b/server/tests/unit/plugins/rpc-fallbacks.test.ts@@ -83,7 +83,7 @@ function guardsFor() {guards: new PluginGuards(db,{ checkPermission: vi.fn(() => true) } as unknown as PermissionsService,- { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,),};diff --git a/server/tests/unit/plugins/view-contributions.controller.test.ts b/server/tests/unit/plugins/view-contributions.controller.test.tsindex aa30294a1..2d2fd3812 100644--- a/server/tests/unit/plugins/view-contributions.controller.test.ts+++ b/server/tests/unit/plugins/view-contributions.controller.test.ts@@ -6,6 +6,7 @@* length/count caps.*/import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';+import type { AddonsService } from '../../../src/nest/addons/addons.service';import { ViewContributionsController } from '../../../src/nest/plugins/contributions/view-contributions.controller';import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';import { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';@@ -23,7 +24,7 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;-function controller(invoke: (id: string) => unknown, providers = ['p1']) {+function controller(invoke: (id: string) => unknown, providers = ['p1'], offForTrip: readonly string[] = []) {const runtime = {providersOf: vi.fn(() => providers),tableContributions: vi.fn(async (id: string) => invoke(id)),@@ -32,6 +33,9 @@ function controller(invoke: (id: string) => unknown, providers = ['p1']) {c: new ViewContributionsController(runtime,new TripAccessService({ findAccessible: canAccessTrip } as unknown as TripsRepository),+ {+ isEnabledForTrip: vi.fn(async (_tripId: number, id: string) => !offForTrip.includes(id)),+ } as unknown as AddonsService,),runtime,};@@ -152,4 +156,13 @@ describe('ViewContributionsController', () => {expect(out.map((o) => o.id)).toEqual(['from-p1']);expect(runtime.tableContributions).toHaveBeenCalledWith('p1', 'reservations', 1, 5);});++ it('VIEWCONTRIB-ADDON: a view whose addon is off for the trip gets nothing, the other views still do', async () => {+ const { c, runtime } = controller(() => [col()], ['p1'], ['budget', 'packing']);+ const off = await Promise.all(['costs', 'packing', 'todos'].map((view) => c.get(view, '1', req(5))));+ expect(off.map((answer) => answer.contributions)).toEqual([[], [], []]);+ expect(runtime.tableContributions).not.toHaveBeenCalled();+ expect((await c.get('files', '1', req(5))).contributions).toHaveLength(1);+ expect((await c.get('reservations', '1', req(5))).contributions).toHaveLength(1);+ });});diff --git a/server/tests/unit/todo/todo.rpc.test.ts b/server/tests/unit/todo/todo.rpc.test.tsindex e3f81fb15..4f602680f 100644--- a/server/tests/unit/todo/todo.rpc.test.ts+++ b/server/tests/unit/todo/todo.rpc.test.ts@@ -44,7 +44,7 @@ function build(canEdit = true) {),} as unknown as TripsRepository,permissions,- { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,+ { isAddonEnabled: vi.fn(() => true), isEnabledForTrip: vi.fn(async () => true) } as unknown as AddonsService,{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,);const rpc = new TodoRpc(todos, realtime, guards);diff --git a/shared/src/addons/trip-addons.schema.spec.ts b/shared/src/addons/trip-addons.schema.spec.tsnew file mode 100644index 000000000..a7975bb9d--- /dev/null+++ b/shared/src/addons/trip-addons.schema.spec.ts@@ -0,0 +1,36 @@+import { tripAddonIdSchema, tripAddonUpdateRequestSchema, tripAddonsResponseSchema } from './trip-addons.schema';++import { describe, expect, it } from 'vitest';++describe('trip addon contracts', () => {+ it('TRIPADDON-SCHEMA-001: the update body takes on, off or null and nothing else', () => {+ expect(tripAddonUpdateRequestSchema.parse({ enabled: true })).toEqual({ enabled: true });+ expect(tripAddonUpdateRequestSchema.parse({ enabled: false })).toEqual({ enabled: false });+ expect(tripAddonUpdateRequestSchema.parse({ enabled: null })).toEqual({ enabled: null });+ expect(tripAddonUpdateRequestSchema.safeParse({}).success).toBe(false);+ expect(tripAddonUpdateRequestSchema.safeParse({ enabled: 1 }).success).toBe(false);+ expect(tripAddonUpdateRequestSchema.safeParse({ enabled: 'true' }).success).toBe(false);+ expect(tripAddonUpdateRequestSchema.safeParse({ enabled: true, extra: 1 }).success).toBe(false);+ });++ it('TRIPADDON-SCHEMA-002: an addon id is a lower-case word', () => {+ expect(tripAddonIdSchema.safeParse('packing').success).toBe(true);+ expect(tripAddonIdSchema.safeParse('naver_list_import').success).toBe(true);+ expect(tripAddonIdSchema.safeParse('').success).toBe(false);+ expect(tripAddonIdSchema.safeParse('Packing').success).toBe(false);+ expect(tripAddonIdSchema.safeParse('../x').success).toBe(false);+ expect(tripAddonIdSchema.safeParse('a'.repeat(65)).success).toBe(false);+ });++ it('TRIPADDON-SCHEMA-003: the response lists each addon with its effective and instance state', () => {+ const body = {+ tripId: 4,+ addons: [+ { id: 'budget', name: 'Costs', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },+ ],+ };+ expect(tripAddonsResponseSchema.parse(body)).toEqual(body);+ expect(tripAddonsResponseSchema.safeParse({ tripId: 4, addons: [{ id: 'budget' }] }).success).toBe(false);+ expect(tripAddonsResponseSchema.safeParse({ tripId: 0, addons: [] }).success).toBe(false);+ });+});diff --git a/shared/src/addons/trip-addons.schema.ts b/shared/src/addons/trip-addons.schema.tsnew file mode 100644index 000000000..9c8e4cee4--- /dev/null+++ b/shared/src/addons/trip-addons.schema.ts@@ -0,0 +1,47 @@+import { z } from 'zod';++/**+ * Per-trip addons: the trip owner switches a trip addon (lists, costs, files,+ * collab, road trip, tours) on or off for one trip, whatever the instance says.+ *+ * Routes: `GET /api/trips/:tripId/addons` (every member) and+ * `PUT /api/trips/:tripId/addons/:addonId` (the owner only). The MCP tools+ * `get_trip_addons` and `set_trip_addon` answer with the same list.+ */++/** An addon id as the addons table spells it (`packing`, `budget`, ...). */+export const tripAddonIdSchema = z+ .string()+ .min(1)+ .max(64)+ .regex(/^[a-z][a-z0-9_]*$/, 'Expected an addon id such as packing or budget');++/**+ * One trip addon as this trip sees it.+ *+ * `enabled` is what applies here, `instanceEnabled` the admin's switch for the+ * whole instance, and `overridden` says the trip owner chose `enabled`+ * themselves instead of following the instance.+ */+export const tripAddonSchema = z.object({+ id: z.string(),+ name: z.string(),+ icon: z.string().nullable(),+ enabled: z.boolean(),+ instanceEnabled: z.boolean(),+ overridden: z.boolean(),+});+export type TripAddon = z.infer<typeof tripAddonSchema>;++export const tripAddonListSchema = z.array(tripAddonSchema);++/** The body of `PUT /api/trips/:tripId/addons/:addonId`: on, off, or null for the instance setting. */+export const tripAddonUpdateRequestSchema = z.object({ enabled: z.boolean().nullable() }).strict();+export type TripAddonUpdateRequest = z.infer<typeof tripAddonUpdateRequestSchema>;++/** What both routes answer: every trip addon of the trip, in the admin's order. */+export const tripAddonsResponseSchema = z.object({+ tripId: z.number().int().positive(),+ addons: tripAddonListSchema,+});+export type TripAddonsResponse = z.infer<typeof tripAddonsResponseSchema>;diff --git a/shared/src/index.ts b/shared/src/index.tsindex efd3d9881..17da81138 100644--- a/shared/src/index.ts+++ b/shared/src/index.ts@@ -299,3 +299,5 @@ export * from './demo/demo-account';export * from './ferratas/ferratas.schema';// The 0.05 degree tile grid both ends load, cache and persist the layer on.export * from './ferratas/ferrataGrid';+// Per-trip addons: GET/PUT /api/trips/:tripId/addons and the tripAddons:changed event.+export * from './addons/trip-addons.schema';diff --git a/shared/src/realtime/events.schema.spec.ts b/shared/src/realtime/events.schema.spec.tsindex b1ad180c2..1e617161c 100644--- a/shared/src/realtime/events.schema.spec.ts+++ b/shared/src/realtime/events.schema.spec.ts@@ -16,6 +16,9 @@ import { describe, it, expect } from 'vitest';*/const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {'roadtripPreferences:changed': { preferences: { roadtrip_day_start: '08:00' } },+ 'tripAddons:changed': {+ addons: [{ id: 'budget', name: 'Costs', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true }],+ },'place:created': { place: { id: 3, name: 'Louvre' } },'place:updated': { place: { id: 3, name: 'Louvre' } },'place:deleted': { placeId: 3 },@@ -200,7 +203,7 @@ const DRIFT_VARIANTS: Partial<Record<TrekWsEventName, Record<string, unknown>[]>};describe('@trek/shared realtime event registry', () => {- it('WSEVT-REG-001: pins the authoritative inventory counts (79 trip + 43 user = 122)', () => {+ it('WSEVT-REG-001: pins the authoritative inventory counts (82 trip + 43 user = 125)', () => {// 67th to 69th trip event: the three collab:link:* a shared link emits.// 70th and 71st: the road trip's vias and tracks, which used to be written silently.// 74th: docsync:changed, so a sync run that moved documents refreshes the@@ -222,9 +225,11 @@ describe('@trek/shared realtime event registry', () => {// inbox of forwarded booking mails and its settings card.// 81st trip event: tripTags:changed, so a tag a member adds to the trip,// renames or deletes shows the same for everyone on it.- expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(81);+ // 82nd trip event: tripAddons:changed, so a trip addon its owner switches on+ // or off for the trip shows or hides for every member at once.+ expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(82);expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(43);- expect(TREK_WS_EVENT_NAMES).toHaveLength(124);+ expect(TREK_WS_EVENT_NAMES).toHaveLength(125);});it('WSEVT-REG-002: every name is domain:action shaped and outside the reserved plugin: namespace', () => {diff --git a/shared/src/realtime/events.schema.ts b/shared/src/realtime/events.schema.tsindex cfdea3541..141693719 100644--- a/shared/src/realtime/events.schema.ts+++ b/shared/src/realtime/events.schema.ts@@ -1,3 +1,4 @@+import { tripAddonListSchema } from '../addons/trip-addons.schema';import { flightLiveLegSchema } from '../flight-live/flight-live.schema';import { roadtripDayBoundaryListSchema } from '../roadtrip/day-boundary.schema';import { roadtripPreferencesSchema } from '../roadtrip/preferences.schema';@@ -293,6 +294,10 @@ export const TREK_WS_EVENTS = {'roadtripPreferences:changed': { scope: 'trip', payload: z.object({ preferences: roadtripPreferencesSchema }) },+ // The trip owner switched a trip addon on or off for this trip, or back to the+ // instance setting: every trip addon as the trip now sees it.+ 'tripAddons:changed': { scope: 'trip', payload: z.object({ addons: tripAddonListSchema }) },+// ── Notifications (user-scoped) ──────────────────────────────────────────'notification:new': { scope: 'user', payload: z.object({ notification: entity }) },'notification:updated': { scope: 'user', payload: z.object({ notification: entity }) },