mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
feat(server): let a trip owner switch trip addons for one trip
A trip can now turn a trip addon (lists, costs, documents, collab, road trip, tours) on or off for itself, whatever the instance switch says. No row in the new trip_addon_overrides table means the trip follows the instance; a row is the owner's choice. Going back to the instance setting deletes the row, and no addon data is touched either way. - GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the owner writes) and the MCP tools get_trip_addons and set_trip_addon, on the shared tripAddons contract; tripAddons:changed tells the members. - Every trip-scoped addon surface asks the trip: REST through TripAddonGuard, MCP through a per-call gate on the named or pinned trip, plugin RPC and events, the share link, the offline bundle, reminders, doc sync, the assistant (tools, keep_attached_file), booking costs, the trip summary prompt, and the cross-trip tour reads (library, Atlas stats, collection save). - Routes without a trip open while the addon is on in any of the user's trips. Switching an addon on that the instance has off ends the members' MCP sessions so they reconnect with its tools. - A copied trip takes its owner's choices along. Behaviour changes: an anonymous call to an addon route that is off now gets 401 instead of 404, and with an instance switch off the packing, todo and files plugin RPC methods, the files MCP tools, todo reminder mails, core plugin events, plugin view contributions, the share link's lists, costs and chat sections and the offline bundle's lists follow it.
This commit is contained in:
@@ -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') {
|
||||
return async (_ctx: McpContext, self: HasAddons): Promise<boolean> =>
|
||||
(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) }) },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 {}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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));
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user