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