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:
Maurice
2026-11-21 13:23:02 +01:00
parent 2f7b8357ce
commit 3f38621024
203 changed files with 3710 additions and 498 deletions
+1
View File
@@ -145,6 +145,7 @@
"TrekPhotoCacheMeta": "memories",
"TrekPhotoSignals": "photos",
"TrekPhotos": "photos",
"TripAddonOverrides": "addons",
"TripAlbumLinks": "memories",
"TripDocumentLinks": "doc-sync",
"TripFiles": "files",
+1 -1
View File
@@ -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
}
+2 -2
View File
@@ -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
}
+4 -1
View File
@@ -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(),
},
});
@@ -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`),
},
});
+3
View File
@@ -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(),
+2
View File
@@ -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,
@@ -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>;
}
+2
View File
@@ -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;
@@ -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',
],
});
}
}
@@ -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;
}
}
+14
View File
@@ -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));
}
+1
View File
@@ -1,5 +1,6 @@
export { McpController, Prompt, Resource, ResourceTemplate, Tool } from './decorators';
export {
combineToolGates,
demoDenied,
errorResult,
ok,
+1 -1
View File
@@ -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);
};
}
+13 -5
View File
@@ -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
+47 -5
View File
@@ -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;
}
/**
+81 -7
View File
@@ -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) }) },
],
};
}
+14 -1
View File
@@ -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;
}
+28 -4
View File
@@ -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 {}
+70 -1
View File
@@ -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 };
}
}
+66
View File
@@ -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);
}
}
+14 -3
View File
@@ -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,
@@ -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>;
}
@@ -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): Ag
if (!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 };
@@ -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. */
@@ -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');
@@ -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))) {
@@ -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');
@@ -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 },
),
);
@@ -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');
}
}
@@ -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) => {
@@ -6,6 +6,7 @@ import { ReservationsRepository } from '../../db/repositories/Reservations.repos
import { 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;
+7 -2
View File
@@ -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,
+4 -1
View File
@@ -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.
+15 -11
View File
@@ -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. */
+33 -18
View File
@@ -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) {
+4 -1
View File
@@ -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);
}
+13 -12
View File
@@ -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 });
}
}
@@ -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);
+4 -2
View File
@@ -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.
+7 -7
View File
@@ -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);
}
@@ -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) {
+24 -10
View File
@@ -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(
+17
View File
@@ -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();
+3
View File
@@ -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,
],
+19 -9
View File
@@ -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);
@@ -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;
@@ -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 scope
const 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,
@@ -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) {
@@ -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,
+3 -1
View File
@@ -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: [
+18 -10
View File
@@ -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') : [];
@@ -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(
@@ -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) {}
@@ -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(
@@ -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,
);
};
}
@@ -38,6 +38,7 @@ import { NotificationChannelPreferences } from '../../db/entities/NotificationCh
import 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, OnModuleDes
await 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.
@@ -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(
@@ -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;
@@ -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,
@@ -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);
@@ -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) {}
@@ -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) {}
@@ -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(
@@ -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,
@@ -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) {}
@@ -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) {}
@@ -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) {}
+3
View File
@@ -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,
+9 -3
View File
@@ -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,
};
@@ -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) {}
+7 -2
View File
@@ -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) {}
+2 -1
View File
@@ -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: [
+9 -4
View File
@@ -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}`);
}
@@ -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) {}
@@ -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 the
@@ -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);
@@ -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) {}
@@ -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) {}
@@ -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/r
import 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);
@@ -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) {}
@@ -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) {}
@@ -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) {}
@@ -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);
}
@@ -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) {}
@@ -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,
+2 -7
View File
@@ -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,
@@ -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) {}
+2 -2
View File
@@ -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) {}
@@ -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) {}
@@ -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) {}
@@ -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) {}
@@ -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);
}
@@ -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(
+12 -3
View File
@@ -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): the

Some files were not shown because too many files have changed in this diff Show More