Finish the plugin RPC decorator rollout

The last 20 wire methods move onto the decorators: db.* and the three
unconditional methods (DbRpc), meta.* (MetaRpc) and the host-mediated surface
of users/broadcasts/notify/ai/oauth/scheduler (HostSurfaceRpc). That closes the
ledger at 113/113, so the legacy has() blocks in rpc-host.ts are gone and the
router is down to what was never domain-specific: build the granted subset of
the dispatch map, dispatch, audit, map errors.

PluginHostDepsFactory was the 26-argument wiring sheet behind those blocks. With
the handlers in the domains it has two dependencies left, so it is now
PluginRpcHostFactory: the plugin's own sqlite handle, the inter-plugin router
bound with this plugin as the caller, and the audit sink.

The 18 host-to-plugin hook calls get the same treatment. They used to spell out
the fn name and the timeout at each controller, which meant nothing checked that
a hook:* grant on the consent screen had a consumer behind it, that the fn
matched what the SDK documents, or that two call sites agreed on the budget.
PluginHooks declares all 18 with @PluginHook and performs them, and the
controllers call it by name.

With both halves complete, requireTotalCoverage goes on: a KNOWN_METHOD without
a handler, or a hook without a consumer, now fails app boot instead of surfacing
as a PERMISSION_DENIED nobody can explain.
This commit is contained in:
Maurice
2026-08-09 17:15:53 +02:00
committed by Maurice
parent 611f94e820
commit f72aba0c91
74 changed files with 1942 additions and 2164 deletions
+10
View File
@@ -38,6 +38,16 @@ remains as the platform underneath `@nestjs/platform-express`.
(`services/tripAccess.ts` and the dead `middleware/tripAccess.ts` are gone);
`queryHelpers` and `tripMembership` are providers; the scheduler takes its
dependencies from the container.
- **Plugin RPC surface (BE-7, complete):** all 113 wire methods are
`@PluginMethod` / `@PluginOpenMethod` handlers on `@PluginController()` providers
in their own domains (`<domain>/<domain>.rpc.ts`; the three that belong to no
domain live in `plugins/host/rpc/`), and all 18 host-to-plugin hook contracts are
`@PluginHook` declarations on `PluginHooks`. `PluginRpcHost` no longer holds a
handler: it builds the granted subset of the dispatch map from the registry,
dispatches, audits and maps errors. `PluginHostDepsFactory` — the 26-argument
wiring sheet named throughout the log below — is now
`PluginRpcHostFactory` and injects two things. See
`plugins/host/rpc-kit/README.md`.
- **Guards (BE-Phase 2, in progress):** the JWT verify lives in `auth/`, and
`middleware/auth.ts`, `validate.ts` and `idempotency.ts` are deleted; the three
addon guards are one `AddonGuard` + `@RequireAddon`; the demo-mode block is one
@@ -12,7 +12,7 @@ import { TrekPhotosRepository } from '../photos/trek-photos.repository';
* the Nest container (the legacy places and reservations MCP registrars in
* src/mcp/tools/places.ts and src/mcp/tools/reservations.ts; the assignment
* MCP tools moved to the DI-discovered assignments.mcp.ts, and the plugin RPC
* host injects AssignmentsService via PluginHostDepsFactory). Exports only the
* surface, ItineraryRpc, injects AssignmentsService directly). Exports only the
* legacy services/assignmentService names still consumed outside the
* container, 1:1, so repointing a consumer is an import-path-only diff. Inside
* the container, inject AssignmentsService instead. Delete this file when
@@ -15,7 +15,7 @@ import { AuthModule } from '../auth/auth.module';
* Assignments domain (S7 — Phase 2 trip sub-domain). The day-assignments mount
* sits under the /api/trips/:tripId/days prefix (S6); the per-assignment ops use
* the /api/trips/:tripId/assignments prefix. AssignmentsService is exported for
* the plugin RPC host (PluginHostDepsFactory injects it).
* the plugin RPC surface (ItineraryRpc injects it).
*/
@Module({
// DaysModule: AssignmentsMcp injects DaysService for the target-day checks.
+1 -1
View File
@@ -7,7 +7,7 @@ import { AtlasMcp } from './atlas.mcp';
/**
* Atlas addon domain (L7 leaf module). Registered in AppModule. Exports
* AtlasService for the plugin RPC host (PluginHostDepsFactory injects it).
* AtlasService for the plugin RPC surface (AtlasRpc injects it).
* AtlasMcp is a provider (not a controller) — the nest-mcp registry discovers
* it after app.init().
*/
+1 -1
View File
@@ -11,7 +11,7 @@ import { ExchangeRatesService } from './exchange-rates.service';
* because BudgetModule imports AuthModule for BudgetMcp's demo guard, so
* AuthModule cannot import BudgetModule back — see the note there. (The budget MCP
* tools and resources moved to the DI-discovered budget.mcp.ts, the plugin
* RPC host injects BudgetService via PluginHostDepsFactory, and the trip
* surface, CostsRpc, injects BudgetService directly, and the trip
* domain folded into the DI-native TripsService, which injects BudgetService —
* its bridge exports were pruned with it). Exports only the legacy
* services/budgetService names still consumed outside the container, 1:1, so
+1 -1
View File
@@ -16,7 +16,7 @@ import { AuthModule } from '../auth/auth.module';
imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [BudgetController],
providers: [BudgetService, ExchangeRatesService, BudgetMcp, ExchangeRatesRpc, CostsRpc],
// For in-container consumers (PluginHostDepsFactory, TripsService,
// For in-container consumers (CostsRpc, TripsService,
// ReservationsService, BookingImportService).
exports: [BudgetService, ExchangeRatesService],
})
@@ -8,7 +8,7 @@ import { CategoriesRpc } from './categories.rpc';
@Module({
controllers: [CategoriesController],
providers: [CategoriesService, CategoriesMcp, CategoriesRpc],
// For in-container consumers (PluginHostDepsFactory).
// For in-container consumers (CategoriesRpc).
exports: [CategoriesService],
})
export class CategoriesModule {}
@@ -6,7 +6,7 @@ import { DatabaseService } from '../database/database.service';
* Categories domain service — owns the category SQL (moved 1:1 from the legacy
* services/categoryService.ts: identical statements, the #6366f1/📍 defaults
* and the COALESCE update semantics). All consumers are in-container now — the
* plugin RPC host injects this class via PluginHostDepsFactory.
* plugin RPC surface injects this class into CategoriesRpc.
*/
@Injectable()
export class CategoriesService {
+1 -1
View File
@@ -12,7 +12,7 @@ import { AuthModule } from '../auth/auth.module';
imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [CollabController],
providers: [CollabService, CollabMcp, CollabRpc],
// For in-container consumers (PluginHostDepsFactory).
// For in-container consumers (CollabRpc).
exports: [CollabService],
})
export class CollabModule {}
+1 -1
View File
@@ -11,7 +11,7 @@ import { QueryHelpersService } from '../query-helpers/query-helpers.service';
* the day MCP tools and resources moved to the DI-discovered days.mcp.ts,
* the transit tools to the DI-discovered transit.mcp.ts (which injects
* DaysService), the plugin RPC host injects DaysService via
* PluginHostDepsFactory, and the trip domain folded into the DI-native
* DaysRpc / AccommodationsRpc, and the trip domain folded into the DI-native
* TripsService, which injects DaysService — its bridge exports were pruned
* with it). Exports only the legacy services/dayService names still consumed
* outside the container, 1:1, so repointing a consumer is an import-path-only
+1 -1
View File
@@ -20,7 +20,7 @@ import { AuthModule } from '../auth/auth.module';
* /api/trips/:tripId/days covers both the days mount and the nested
* /days/:dayId/notes mount. DaysMcp/DayNotesMcp carry the
* decorator-registered MCP tools + resources. DaysService and DayNotesService
* are exported for in-container consumers (PluginHostDepsFactory,
* are exported for in-container consumers (DaysRpc, DayNotesRpc,
* AccommodationsService, TripsService, the assignments/reservations MCP
* controllers).
*/
@@ -8,7 +8,7 @@ import { AddonsModule } from '../addons/addons.module';
/**
* Provides the LLM booking-import fallback; imported by BookingImportModule.
* Exports LlmConfigResolver for the plugin host wiring (PluginHostDepsFactory).
* Exports LlmConfigResolver for the plugin host surface (HostSurfaceRpc).
*/
@Module({
imports: [SettingsModule, AddonsModule],
@@ -14,7 +14,7 @@ import { AuthModule } from '../auth/auth.module';
* mail without AuthModule and NotificationsModule importing each other.
* NotificationsService and NotificationPreferencesService are exported for
* in-container consumers (AdminController's dev test send and preferences tab,
* the plugin RPC host's PluginHostDepsFactory). */
* the plugin RPC surface, HostSurfaceRpc). */
@Module({
imports: [AuthModule, MailerModule],
controllers: [NotificationsController],
@@ -299,7 +299,7 @@ function shouldSendToUser(
* Non-Nest consumers (scheduler, legacy adminService/memories, the lazy
* fire-and-forget sends in migrated Nest services) go through
* `notifications.bridge.ts`; the plugin RPC host injects this service via
* `PluginHostDepsFactory`.
* `HostSurfaceRpc`.
*/
@Injectable()
export class NotificationsService {
+1 -1
View File
@@ -9,7 +9,7 @@ import { PermissionsService } from '../permissions/permissions.service';
* Nest container (the legacy packing-list prompt registrar in
* src/mcp/tools/prompts.ts; the packing MCP tools and resources moved to the
* DI-discovered packing.mcp.ts, the plugin RPC host injects PackingService
* via PluginHostDepsFactory, and the trip domain folded into the DI-native
* via PackingRpc, and the trip domain folded into the DI-native
* TripsService, which injects PackingService). Exports only the legacy
* services/packingService names still consumed outside the container, 1:1, so
* repointing a consumer is an import-path-only diff. Inside the container,
+1 -1
View File
@@ -10,7 +10,7 @@ import { AuthModule } from '../auth/auth.module';
/** Packing domain (S2 — Phase 2 trip sub-domain). Registered in AppModule.
* Exports PackingService for in-container consumers (TripsService bundle,
* PluginHostDepsFactory). */
* PackingRpc). */
@Module({
imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [PackingController],
+1 -1
View File
@@ -19,7 +19,7 @@ import { AuthModule } from '../auth/auth.module';
* Tags for the joined projections, and on MapsModule for places.mcp.ts's
* search_place tool. Exports PlacesService for the in-container consumers —
* TripsService's trip summary, DaysMcp's place-accommodation creation,
* BookingImportService and the plugin RPC host's PluginHostDepsFactory. There
* BookingImportService and the plugin RPC surface, PlacesRpc. There
* is no places.bridge.ts: nothing outside the container consumes this domain.
*/
@Module({
+1 -1
View File
@@ -96,7 +96,7 @@ export interface PlaceUpdateInput {
* places.helpers.ts. Nothing outside the Nest container consumes this domain
* any more, so there is no places.bridge.ts: the MCP surface is the
* DI-discovered places.mcp.ts, and TripsService / DaysMcp /
* BookingImportService / PluginHostDepsFactory all inject this class.
* BookingImportService / PlacesRpc all inject this class.
*/
@Injectable()
export class PlacesService {
@@ -2,7 +2,7 @@ import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -78,7 +78,7 @@ function normalize(pluginId: string, raw: unknown): AtlasLayer[] {
@Controller('api/atlas-layers')
@UseGuards(JwtAuthGuard)
export class AtlasLayersController {
constructor(private readonly runtime: PluginRuntimeService) {}
constructor(private readonly hooks: PluginHooks) {}
@Get()
async get(@Req() req: Request & { user?: { id: number } }): Promise<{ layers: AtlasLayer[] }> {
@@ -86,11 +86,11 @@ export class AtlasLayersController {
const userId = req.user?.id;
if (userId == null) return { layers: [] };
const ids = this.runtime.providersOf('atlasLayerProvider');
const ids = this.hooks.providersOf('atlasLayerProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<AtlasLayer[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'atlasLayerProvider', 'getLayers', [], userId, 5000);
const raw = await this.hooks.atlasLayers(id, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -79,7 +79,7 @@ function normalize(pluginId: string, tripDayIds: ReadonlySet<number>, raw: unkno
@UseGuards(JwtAuthGuard)
export class DayScheduleController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -93,7 +93,7 @@ export class DayScheduleController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { items: [] };
const ids = this.runtime.providersOf('dayScheduleProvider');
const ids = this.hooks.providersOf('dayScheduleProvider');
if (ids.length === 0) return { items: [] };
const dayRows = this.dbs.connection.prepare('SELECT id FROM days WHERE trip_id = ?').all(tripId) as Array<{ id: number }>;
const tripDayIds: ReadonlySet<number> = new Set(dayRows.map((d) => d.id));
@@ -101,7 +101,7 @@ export class DayScheduleController {
const perProvider = await Promise.all(
ids.map(async (id): Promise<DayScheduleItem[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'dayScheduleProvider', 'getSchedule', [tripId], userId, 5000);
const raw = await this.hooks.daySchedule(id, tripId, userId);
return normalize(id, tripDayIds, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -156,7 +156,7 @@ function normalize(pluginId: string, tripDayIds: ReadonlySet<number>, raw: unkno
@UseGuards(JwtAuthGuard)
export class DayTintsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -170,7 +170,7 @@ export class DayTintsController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { tints: [] };
const ids = this.runtime.providersOf('dayTintProvider');
const ids = this.hooks.providersOf('dayTintProvider');
if (ids.length === 0) return { tints: [] };
const dayRows = this.dbs.connection.prepare('SELECT id FROM days WHERE trip_id = ?').all(tripId) as Array<{ id: number }>;
const tripDayIds: ReadonlySet<number> = new Set(dayRows.map((d) => d.id));
@@ -178,7 +178,7 @@ export class DayTintsController {
const perProvider = await Promise.all(
ids.map(async (id): Promise<DayTint[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'dayTintProvider', 'getDayTints', [tripId], userId, 5000);
const raw = await this.hooks.dayTints(id, tripId, userId);
return normalize(id, tripDayIds, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -8,7 +8,7 @@ import type { PluginRpcContext } from './rpc-kit/types';
/**
* The resource gates every plugin RPC handler needs, lifted out of PluginRpcHost's
* private methods and PluginHostDepsFactory's canEditTripAs / requireAddon so that
* private methods and the host factory's canEditTripAs / requireAddon so that
* decorated *.rpc.ts handlers get them by injection instead of through a closure.
*
* Every message string is character-identical to what the legacy router produced.
@@ -1,384 +0,0 @@
import { Injectable } from '@nestjs/common';
import { readEnv } from '../../../app-config';
import { RealtimeService } from '../../realtime/realtime.service';
import { BLOCKED_EXTENSIONS, filesDir } from '../../files/files.constants';
import { TripMembershipService } from '../../trip-membership/trip-membership.service';
import { NotificationsService } from '../../notifications/notifications.service';
import { createLlmClient } from '../../llm-parse/llm-client.factory';
import { readUserSettingDecrypted } from '../plugins.service';
import { PluginOAuthService } from '../plugin-oauth.service';
import fsMod from 'node:fs';
import pathMod from 'node:path';
import { randomUUID } from 'node:crypto';
import { PermissionsService } from '../../permissions/permissions.service';
import { TripsService, NotFoundError, ValidationError } from '../../trips/trips.service';
import { PlacesService, type PlaceCreateInput, type PlaceUpdateInput } from '../../places/places.service';
import { AddonsService } from '../../addons/addons.service';
import { isDemoEmail } from '../../common/demo';
import { ADDON_IDS } from '../../../addons';
import { JourneyDomainService } from '../../journey/journey-domain.service';
import { AtlasService } from '../../atlas/atlas.service';
import { CollectionsService } from '../../collections/collections.service';
import { BudgetService } from '../../budget/budget.service';
import { ExchangeRatesService } from '../../budget/exchange-rates.service';
import { ReservationsService } from '../../reservations/reservations.service';
import { TagsService } from '../../tags/tags.service';
import { CategoriesService } from '../../categories/categories.service';
import { TodoService } from '../../todo/todo.service';
import { PackingService } from '../../packing/packing.service';
import { DayNotesService } from '../../days/day-notes.service';
import { DaysService } from '../../days/days.service';
import { AssignmentsService } from '../../assignments/assignments.service';
import { LlmConfigResolver } from '../../llm-parse/llm-config.resolver';
import { DatabaseService } from '../../database/database.service';
import { FilesService } from '../../files/files.service';
import { CollabService } from '../../collab/collab.service';
import { VacayService } from '../../vacay/vacay.service';
import { PluginRpcHost, ForbiddenResource, BadParams } from './rpc-host';
import { PluginRpcRegistryService } from './rpc-kit/registry.service';
import { appendAudit } from './plugin-audit';
import { getPluginDataDb, budgetFor } from './plugin-host-state';
// collectionsService self-gates per-collection role by THROWING status-tagged errors
// (assertAccess 404, assertCanEdit 403, validation 400). Map them onto the RPC error
// classes so a plugin sees RESOURCE_FORBIDDEN / BAD_PARAMS instead of HOST_ERROR.
function mapCollectionError<T>(fn: () => T): T {
try {
return fn();
} catch (e) {
const status = (e as { status?: number })?.status;
const msg = e instanceof Error ? e.message : 'collection error';
if (status === 403 || status === 404) throw new ForbiddenResource(msg);
if (status === 400 || status === 409) throw new BadParams(msg);
throw e;
}
}
// Journey mirroring is best-effort on every other path that triggers it
// (places.service wraps the same hooks, assignments.service wraps the reconcile),
// so a broken journey link can never turn a successful write into an RPC error.
function mirrorJourneys(run: () => void): void {
try { run(); } catch { /* non-fatal */ }
}
// The #858 privacy-scoped packing broadcasts used to be copied here, with a comment
// asking for the copy to be kept in lockstep with packing.controller.ts and
// packing.service.ts by hand. They now live once, in PackingService, and both the
// REST controller and PackingRpc call them there.
// Quotas for plugin entity metadata (db:meta) — a cheap disk-DoS guard on the
// shared trek.db volume. Generous for real use, small enough to bound abuse.
const META_VALUE_MAX = 64 * 1024; // serialized JSON bytes per value
const META_KEY_MAX = 256; // key string length (the key is attacker-controlled too)
const META_KEYS_MAX = 100; // keys per (plugin, entity)
/** Routes inter-plugin calls/events; supplied by PluginRuntimeService (owns the supervisor). */
export interface PluginCallRouter {
callPlugin(callerId: string, targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
emitPluginEvent(sourceId: string, event: string, payload: unknown): void;
}
/**
* Wires a plugin's capability host to the REAL privileged modules (#plugins,
* M1). This is the ONLY plugin file that touches the realtime broadcast facade
* — it runs in the host (parent), never in the child. Broadcasts are
* force-namespaced to `plugin:{id}:{event}` so a plugin can't forge a core event.
*
* DI-native domain services (budget, exchange-rates, reservations, tags,
* categories, todo, packing, day-notes, assignments, oauth, files, collab,
* vacay, trips, places, collections, atlas, notifications, the LLM config
* resolver) and the DatabaseService (all inline SQL + the trip-access helper) are
* constructor-injected; legacy `services/*` domains stay plain function
* imports until their own migration lands (DI-MIGRATION.md), at which point
* each swaps one import for one injected service.
*/
@Injectable()
export class PluginHostDepsFactory {
constructor(
private readonly budget: BudgetService,
private readonly reservations: ReservationsService,
private readonly tags: TagsService,
private readonly categories: CategoriesService,
private readonly todos: TodoService,
private readonly packing: PackingService,
private readonly oauth: PluginOAuthService,
private readonly dayNotes: DayNotesService,
private readonly assignments: AssignmentsService,
private readonly llmConfig: LlmConfigResolver,
private readonly db: DatabaseService,
private readonly files: FilesService,
private readonly collab: CollabService,
private readonly vacay: VacayService,
private readonly days: DaysService,
private readonly permissions: PermissionsService,
private readonly exchangeRates: ExchangeRatesService,
private readonly addons: AddonsService,
private readonly realtime: RealtimeService,
private readonly trips: TripsService,
private readonly places: PlacesService,
private readonly collections: CollectionsService,
private readonly atlas: AtlasService,
private readonly notifications: NotificationsService,
private readonly membership: TripMembershipService,
private readonly journey: JourneyDomainService,
// Appended last and OPTIONAL so the hand-wired 26-arg construction in
// plugin-host-deps.factory.test.ts keeps compiling. Handed to every host it
// builds, which is how decorated *.rpc.ts handlers reach the dispatch map.
private readonly rpcRegistry?: PluginRpcRegistryService,
) {}
/**
* The trip-access + role gate used by every planner write, mirroring the app's
* per-domain `canEdit` (canAccessTrip + checkPermission for the entity's *_edit
* action). Returns false — never throws — so the caller maps it to a clean
* RESOURCE_FORBIDDEN.
*/
private canEditTripAs(action: string, tripId: number, userId: number): boolean {
const trip = this.db.canAccessTrip(tripId, userId);
if (!trip) return false;
const u = this.db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
if (!u) return false;
return this.permissions.checkPermission(action, u.role ?? 'user', trip.user_id, userId, trip.user_id !== userId);
}
// The booking notification the REST controller sends after a create/update/delete
// is fire-and-forget, so it never blocks the plugin write.
private notifyBooking(actingUserId: number, tripId: number, booking: string, type: string): void {
this.reservations.notifyBookingChange(tripId, actingUserId, booking, type);
}
create(id: string, granted: ReadonlySet<string>, router: PluginCallRouter): PluginRpcHost {
// A subsystem read is refused when its addon is off — parity with the app, where a
// disabled addon means there is simply nothing to read (same shape as the Costs gate).
const requireAddon = (addonId: string, noun: string): void => {
if (!this.addons.isAddonEnabled(addonId)) throw new ForbiddenResource(`the ${noun} addon is disabled`);
};
return new PluginRpcHost(id, granted, {
// Resolve the data handle lazily on every access rather than capturing it once.
// disable()/uninstall() drop the entry from `running` BEFORE awaiting the kill grace
// and calling dispose(), so a re-enable in that window builds a NEW host. A captured
// handle would let the OLD host's dispose() close the DB out from under the NEW one
// (every db.* call then throws 'database connection is not open'). Resolving per call
// means the new host always uses the current, open handle — getPluginDataDb recreates
// one the moment a stale dispose closes it. Safe because db.* is synchronous, so no
// call is ever mid-flight when a dispose from another tick closes the handle.
get data() { return getPluginDataDb(id); },
db: this.db.connection,
canAccessTrip: (tripId, userId) => this.db.canAccessTrip(tripId, userId),
// The router binds this host's plugin id as the caller/source.
callPlugin: (targetId, fn, args, actingUserId) => router.callPlugin(id, targetId, fn, args, actingUserId),
emitPluginEvent: (event, payload) => router.emitPluginEvent(id, event, payload),
// Two users "share a trip" when both are owner-or-member of the same trip.
canSeeUser: (actingUserId, targetUserId) =>
!!this.db
.prepare(
`SELECT 1 FROM trips t
LEFT JOIN trip_members m1 ON m1.trip_id = t.id AND m1.user_id = ?
LEFT JOIN trip_members m2 ON m2.trip_id = t.id AND m2.user_id = ?
WHERE (t.user_id = ? OR m1.user_id IS NOT NULL)
AND (t.user_id = ? OR m2.user_id IS NOT NULL)
LIMIT 1`,
)
.get(actingUserId, targetUserId, actingUserId, targetUserId),
broadcastToTrip: (tripId, event, payload) => this.realtime.broadcast(tripId, `plugin:${id}:${event}`, payload),
broadcastToUser: (userId, payload) => this.realtime.broadcastToUser(userId, { type: `plugin:${id}`, ...payload }),
audit: (entry) => appendAudit(this.db.connection, entry),
// --- Costs (budget items) ---
// Same gate as a REST/MCP budget mutation: the acting user must have trip
// access AND the 'budget_edit' permission for their global role.
// --- Read scopes (packing/files). Membership is checked by the host (tripRead);
// these just delegate to the same services the REST paths use. ---
// A file's bytes as base64, size-capped BEFORE the read so a 500MB video can't
// be pulled (~667MB base64) through the IPC pipe. 10MB matches the plugin upload
// cap; trashed files (deleted_at set) are refused like the download path.
// --- Files write. Bytes arrive as bounded base64; the extension is validated
// against the central blocklist BEFORE anything touches disk, and link targets
// must live on the same trip (findForeignLinkTarget). Same events as the app. ---
// --- Collab reads (collab addon; membership checked by the host). Same hydrated
// shapes as the REST GETs, so a collab plugin can finally read what it writes. ---
// --- Collab content (collab addon). The services validate + self-report errors. ---
// --- Member add (member_manage). Grants trip access — the target must exist;
// the acting user is recorded as the inviter. Owner/duplicate adds are no-ops. ---
// --- Host-mediated notifications. Recipient resolution + channel fan-out +
// per-user preferences are all owned by NotificationsService.send; the plugin
// supplies only the target (host-scoped by the router) + plain text. actorId is
// null (no user sender), so the message body carries the plugin's content. ---
canAccessTripForNotify: (tripId, userId) => !!this.db.canAccessTrip(tripId, userId),
sendPluginNotification: async (_pluginId, input) => {
if (!budgetFor(id).take('notify', Date.now())) throw new BadParams('daily notification budget exhausted (resets at UTC midnight)');
await this.notifications.send({
event: 'plugin_notification',
actorId: null,
params: { title: input.title, body: input.body, ...(input.link ? { link: input.link } : {}) },
scope: input.scope,
targetId: input.targetId,
inApp: input.link ? { navigateTarget: input.link } : undefined,
});
return { sent: true };
},
// --- Host-mediated LLM. The host holds the credential (LlmConfigResolver, encrypted
// apiKey) and runs the call under the acting user's provider config; caps + the
// provider-availability check live at the router. Reuses the extraction client:
// complete() wraps it with a {text} schema; extract() passes the plugin's schema. ---
aiConfigured: (userId) => this.llmConfig.resolve(userId) !== null,
aiComplete: async (userId, prompt, system) => {
const config = this.llmConfig.resolve(userId);
if (!config) throw new BadParams('no AI provider is configured for this user');
if (!budgetFor(id).take('ai', Date.now())) throw new BadParams('daily AI budget exhausted (resets at UTC midnight)');
const results = await createLlmClient(config).extract({
prompt: system || 'You are a helpful assistant. Reply with a JSON object of the form {"text": "..."} whose "text" field holds your answer.',
jsonSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
model: config.model, baseUrl: config.baseUrl, apiKey: config.apiKey, text: prompt,
});
const first = results[0] as { text?: unknown } | undefined;
return { text: typeof first?.text === 'string' ? first.text : '' };
},
aiExtract: async (userId, text, jsonSchema, prompt) => {
const config = this.llmConfig.resolve(userId);
if (!config) throw new BadParams('no AI provider is configured for this user');
if (!budgetFor(id).take('ai', Date.now())) throw new BadParams('daily AI budget exhausted (resets at UTC midnight)');
const results = await createLlmClient(config).extract({
prompt: prompt || 'Extract structured data from the text into the given JSON schema.',
jsonSchema, model: config.model, baseUrl: config.baseUrl, apiKey: config.apiKey, text,
});
return { results };
},
// The acting user's own decrypted value for one of this plugin's user-scope settings.
getUserSetting: (pluginId, userId, key) => readUserSettingDecrypted(pluginId, userId, key),
// A short-lived OAuth access token for the acting user (host-brokered; refreshes).
getOAuthToken: (pluginId, userId) => this.oauth.getAccessToken(pluginId, userId, Date.now()),
// Persistent scheduler (jobs:run). Caps bound the abuse surface: a plugin can't
// hoard timers, name-bomb, ship a huge payload, or busy-loop a recurring task.
schedulerSet: (name, dueAt, everyMs, payload) => {
const SCHED_MAX = 100; // entries per plugin
const NAME_MAX = 128;
const PAYLOAD_MAX = 8 * 1024; // 8 KB JSON
const EVERY_MIN = 60_000; // 1 min floor for recurring
const DUE_MAX = Date.now() + 366 * 24 * 60 * 60 * 1000; // <= ~1 year out
if (!name || name.length > NAME_MAX) throw new BadParams(`scheduler name is required (max ${NAME_MAX} chars)`);
if (!Number.isFinite(dueAt) || dueAt > DUE_MAX) throw new BadParams('scheduler dueAt out of range');
if (everyMs !== undefined && (!Number.isFinite(everyMs) || everyMs < EVERY_MIN)) throw new BadParams(`recurring interval must be >= ${EVERY_MIN} ms`);
const json = JSON.stringify(payload ?? null);
if (json.length > PAYLOAD_MAX) throw new BadParams(`scheduler payload too large (max ${PAYLOAD_MAX} bytes)`);
const existing = this.db.prepare('SELECT id FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?').get(id, name) as { id: number } | undefined;
if (!existing) {
const n = (this.db.prepare('SELECT COUNT(*) AS c FROM plugin_scheduled_tasks WHERE plugin_id = ?').get(id) as { c: number }).c;
if (n >= SCHED_MAX) throw new BadParams(`too many scheduled tasks (max ${SCHED_MAX})`);
}
// Upsert by (plugin, name): re-scheduling the same name replaces it.
this.db.prepare(
`INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at, payload, every_ms) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (plugin_id, name) DO UPDATE SET due_at = excluded.due_at, payload = excluded.payload, every_ms = excluded.every_ms`,
).run(id, name, Math.max(dueAt, Date.now()), json, everyMs ?? null);
return { scheduled: true };
},
schedulerCancel: (name) => {
const r = this.db.prepare('DELETE FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?').run(id, name);
return { cancelled: r.changes > 0 };
},
// Cross-trip: every accessible trip's budget items (membership predicate is
// baked into listTrips). Reuses the hydrated list so members/payers come too.
// Reuses BudgetService.create (frozen FX + members/payers), then broadcasts
// the same 'budget:created' event the controller emits so the web app updates
// live. No X-Socket-Id — a plugin has no originating socket.
// Reuses BudgetService.update (re-frozen FX on a currency change), then
// broadcasts the same 'budget:updated' event the REST controller emits. A
// missing item is a clean RESOURCE_FORBIDDEN (parity with updatePlace).
// Reuses BudgetService.remove, then broadcasts 'budget:deleted' with the
// numeric id — same payload the REST controller sends.
// --- Places (place_edit). Delegate to the same PlacesService the REST/MCP paths
// use, then broadcast the same events so open web sessions update live, and run
// the journey hooks places.controller runs on the same three writes: a journey
// linked to the trip carries a skeleton entry per day-assigned place, and
// without the hooks it keeps the old title/location — or a dead entry — until
// somebody reloads it. ---
// Consumed by the db:meta gate; the trip writes themselves have moved.
canEditTrip: (tripId, userId) => this.canEditTripAs('trip_edit', tripId, userId),
canEditReservations: (tripId, userId) => this.canEditTripAs('reservation_edit', tripId, userId),
canEditPlaces: (tripId, userId) => this.canEditTripAs('place_edit', tripId, userId),
// --- Days (day_edit). getDay scopes the row to the trip before any write. ---
canEditDays: (tripId, userId) => this.canEditTripAs('day_edit', tripId, userId),
// --- Itinerary (day_edit). Both the day AND the place must belong to the trip,
// so a plugin can't cross-link another trip's rows (AssignmentsService doesn't
// self-check this — the controllers do, so we reproduce it here). ---
// --- Trip creation (trip_create; owner = acting user). No broadcast — a new trip
// is only visible to its owner, who refetches (same as the REST POST). ---
// --- Exchange rates: the same cached upstream feed the budget uses (tenant-free). ---
// --- Trip (trip_edit). Only the schema-writable fields reach updateTrip; its
// NotFound/Validation errors are mapped to clean RPC codes. ---
// --- Cross-trip reads. The membership predicate is baked into listTrips, so a
// plugin only ever sees the acting user's own trips/reservations (no raw
// cross-tenant SELECT). Reuses the same hydrated services as the REST paths. ---
// --- Trip-scoped hydrated reads (membership already checked by tripRead). Same
// services as the REST GETs, so plugins see the exact planner shapes. ---
// --- Accommodations (lodging blocks, day_edit). Delegates to DaysService so the
// partner hotel reservation, the metadata sync and the delete cascade behave
// exactly like the accommodations REST controller, cascade broadcasts included. ---
// --- User-scoped addon reads (the acting user's own data across all trips). Each
// reuses the same service the addon's REST/MCP path uses; the addon-enabled gate
// mirrors the app (a disabled addon has nothing to read). ---
// --- Collections write. The service self-gates per-collection role (assertAccess/
// assertCanEdit throw status-tagged errors) — map those to the RPC error codes. ---
// --- Atlas write: plain uid-scoped rows, no broadcasts in the service. ---
// --- Vacay write: the plan is the ACTING USER's active plan (resolved host-side);
// the service broadcasts to plan users itself. ---
// --- Journal write: journeyService.canEdit self-gates each call (owner/contributor). ---
// Day notes are core (no addon) and trip-scoped; membership is enforced by the host.
// --- Day notes write (day_edit). The day must belong to the trip; broadcasts the
// same dayNote:* events the REST controller emits so open sessions update live. ---
// --- Reservations (bookings, reservation_edit). Delegates to ReservationsService
// so the accommodation/budget-sync/notification/broadcast side effects match the
// web app EXACTLY. socketId is undefined — a plugin has no originating socket. ---
// --- Plugin metadata (db:meta). A per-plugin namespaced key/value store keyed
// to a core entity; the plugin only ever sees rows tagged with its own id. ---
metaEntityTrip: (entityType, entityId) => {
if (entityType === 'trip') {
return (this.db.prepare('SELECT id FROM trips WHERE id = ?').get(entityId) as { id: number } | undefined)?.id;
}
// Each of these tables has a NOT NULL trip_id, so the metadata gate resolves to
// the owning trip and reuses the standard canAccessTrip / *_edit checks.
const table = entityType === 'place' ? 'places'
: entityType === 'day' ? 'days'
: entityType === 'reservation' ? 'reservations'
: 'day_accommodations'; // accommodation
return (this.db.prepare(`SELECT trip_id FROM ${table} WHERE id = ?`).get(entityId) as { trip_id: number } | undefined)?.trip_id;
},
metaGet: (entityType, entityId, key) => {
const row = this.db.prepare('SELECT value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
.get(id, entityType, entityId, key) as { value: string } | undefined;
if (!row) return null;
try { return JSON.parse(row.value); } catch { return null; }
},
metaSet: (entityType, entityId, key, value) => {
if (key.length > META_KEY_MAX) throw new BadParams(`metadata key too long (>${META_KEY_MAX} chars)`);
const json = JSON.stringify(value ?? null);
if (json.length > META_VALUE_MAX) throw new BadParams(`metadata value too large (>${META_VALUE_MAX} bytes)`);
const exists = this.db.prepare('SELECT 1 FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
.get(id, entityType, entityId, key);
if (!exists) {
const { n } = this.db.prepare('SELECT COUNT(*) AS n FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=?')
.get(id, entityType, entityId) as { n: number };
if (n >= META_KEYS_MAX) throw new BadParams(`too many metadata keys on this ${entityType} (max ${META_KEYS_MAX})`);
}
this.db.prepare(`INSERT INTO plugin_entity_metadata (plugin_id, entity_type, entity_id, key, value, updated_at)
VALUES (?, ?, ?, ?, ?, datetime('now'))
ON CONFLICT(plugin_id, entity_type, entity_id, key)
DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`)
.run(id, entityType, entityId, key, json);
return { key, value: value ?? null };
},
metaList: (entityType, entityId) => {
const list = this.db.prepare('SELECT key, value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? ORDER BY key')
.all(id, entityType, entityId) as Array<{ key: string; value: string }>;
const out: Record<string, unknown> = {};
for (const r of list) { try { out[r.key] = JSON.parse(r.value); } catch { out[r.key] = null; } }
return out;
},
metaDelete: (entityType, entityId, key) => {
const res = this.db.prepare('DELETE FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
.run(id, entityType, entityId, key);
return { deleted: res.changes > 0 };
},
}, this.rpcRegistry);
}
}
@@ -0,0 +1,59 @@
import { Inject, Injectable } from '@nestjs/common';
import { DatabaseService } from '../../database/database.service';
import { PluginRpcHost } from './rpc-host';
import type { PluginRpcRegistry } from './rpc-kit/registry';
import { PluginRpcRegistryService } from './rpc-kit/registry.service';
import { appendAudit } from './plugin-audit';
import { getPluginDataDb } from './plugin-host-state';
/** Routes inter-plugin calls/events; supplied by PluginRuntimeService (owns the supervisor). */
export interface PluginCallRouter {
callPlugin(callerId: string, targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
emitPluginEvent(sourceId: string, event: string, payload: unknown): void;
}
/**
* Builds a plugin's capability host (#plugins, M1).
*
* This used to be a 900-line wiring sheet: every privileged domain service was
* injected here and handed to the router as a closure. The domains now own their own
* plugin surface — one `@PluginController()` provider per domain, discovered at boot
* by PluginRpcRegistryService — so all that is left is the three things that are
* genuinely per-plugin and belong to nobody else: the plugin's own sqlite handle, the
* inter-plugin router bound with this plugin as the caller, and the audit sink.
*/
@Injectable()
export class PluginRpcHostFactory {
constructor(
private readonly db: DatabaseService,
// Injected by its concrete token, held as the base class: a no-Nest test can then
// hand in a createTestPluginRegistry() built from the instances it cares about.
@Inject(PluginRpcRegistryService) private readonly registry: PluginRpcRegistry,
) {}
create(id: string, granted: ReadonlySet<string>, router: PluginCallRouter): PluginRpcHost {
return new PluginRpcHost(
id,
granted,
{
// Resolve the data handle lazily on every access rather than capturing it once.
// disable()/uninstall() drop the entry from `running` BEFORE awaiting the kill
// grace and calling dispose(), so a re-enable in that window builds a NEW host.
// A captured handle would let the OLD host's dispose() close the DB out from
// under the NEW one (every db.* call then throws 'database connection is not
// open'). Resolving per call means the new host always uses the current, open
// handle — getPluginDataDb recreates one the moment a stale dispose closes it.
// Safe because db.* is synchronous, so no call is ever mid-flight when a dispose
// from another tick closes the handle.
get data() {
return getPluginDataDb(id);
},
// The router binds this host's plugin id as the caller/source.
callPlugin: (targetId, fn, args, actingUserId) => router.callPlugin(id, targetId, fn, args, actingUserId),
emitPluginEvent: (event, payload) => router.emitPluginEvent(id, event, payload),
audit: (entry) => appendAudit(this.db.connection, entry),
},
this.registry,
);
}
}
+27 -444
View File
@@ -1,16 +1,3 @@
import {
budgetCreateItemRequestSchema, type BudgetCreateItemRequest,
budgetUpdateItemRequestSchema, type BudgetUpdateItemRequest,
placeCreateRequestSchema, placeUpdateRequestSchema,
dayCreateRequestSchema, dayUpdateRequestSchema,
tripUpdateRequestSchema, tripCreateRequestSchema,
reservationCreateRequestSchema, reservationUpdateRequestSchema,
reservationEndpointsInputSchema,
accommodationCreateRequestSchema, accommodationUpdateRequestSchema,
packingCreateItemRequestSchema, packingUpdateItemRequestSchema,
collectionCreateRequestSchema, collectionUpdateRequestSchema,
collectionSavePlaceRequestSchema, collectionCopyToTripRequestSchema,
} from '@trek/shared';
import {
KNOWN_METHODS,
type KnownMethod,
@@ -19,10 +6,8 @@ import {
type RpcResponse,
} from '../protocol/envelope';
import type { PluginDataDb } from './plugin-data.service';
import { stripEmoji } from '../text-sanitize';
import { auditResource, isAuditable } from './plugin-audit';
import { BadParams, ForbiddenResource } from './rpc-errors';
import { asArgs, asPayload, asTxOps, num, str } from './rpc-params';
import type { PluginRpcRegistry } from './rpc-kit/registry';
// Both used to be declared here. They now live in rpc-errors.ts so decorated
@@ -38,145 +23,35 @@ export { BadParams, ForbiddenResource };
* plugin cannot "call it anyway" — there is no shared object, only messages, and
* the host is the sole holder of the trek.db handle and the broadcast fns.
*
* The handlers themselves no longer live here. Every one of the 113 wire methods is
* a `@PluginMethod` / `@PluginOpenMethod` on a `@PluginController()` provider in its
* own domain, and the registry binds the granted subset into the map below. What is
* left is the part that was never domain-specific: build the map, dispatch into it,
* audit the call, and map a thrown error onto a wire code.
*
* Runs in the HOST (parent) process.
*/
interface CoreDb {
prepare(sql: string): {
all(...args: unknown[]): unknown[];
get(...args: unknown[]): unknown;
};
}
/** What the router needs that is neither a domain service nor a permission check. */
export interface HostDeps {
/** The plugin's own sqlite (db:own). */
/**
* The plugin's own sqlite (db:own). A GETTER on the factory side, resolved per
* access: disable()/re-enable builds a NEW host while the old one's dispose() may
* still be closing the handle, so a captured one leaves the new host throwing
* 'database connection is not open'.
*/
data: PluginDataDb;
/** Read-only handle to the core trek.db, used ONLY through the typed readers here. */
db: CoreDb;
/** Returns the trip row if the user may access it, else undefined. */
canAccessTrip(tripId: number, userId: number): unknown;
/** True if the target user is the acting user or co-members a trip with them. */
canSeeUser(actingUserId: number, targetUserId: number): boolean;
/** Namespaced trip broadcast (host forces the plugin:{id}:{event} event type). */
broadcastToTrip(tripId: number, eventType: string, payload: Record<string, unknown>): void;
/** Namespaced per-user broadcast. */
broadcastToUser(userId: number, payload: Record<string, unknown>): void;
// --- Host-mediated notifications (recipient resolution + channel fan-out owned
// by the host; the plugin supplies only target + plain text). ---
canAccessTripForNotify(tripId: number, userId: number): boolean;
sendPluginNotification(pluginId: string, input: { title: string; body: string; link?: string; scope: 'user' | 'trip'; targetId: number }): Promise<unknown>;
// --- Host-mediated LLM (the host owns the credential; output is DATA the plugin
// must still push through the gated write methods). ---
aiConfigured(userId: number): boolean;
aiComplete(userId: number, prompt: string, system: string | undefined): Promise<unknown>;
aiExtract(userId: number, text: string, jsonSchema: object, prompt: string | undefined): Promise<unknown>;
/** The acting user's own value for one of this plugin's `scope:'user'` settings (decrypted). */
getUserSetting(pluginId: string, userId: number, key: string): unknown;
/** A short-lived OAuth access token for the acting user (host-brokered; refreshes if
* expiring). Null when the user hasn't connected. The plugin never sees the refresh token. */
getOAuthToken(pluginId: string, userId: number): Promise<string | null>;
/** Schedule (upsert by name) a userless future callback; everyMs set = recurring. Caps enforced here. */
schedulerSet(name: string, dueAt: number, everyMs: number | undefined, payload: unknown): { scheduled: boolean };
/** Cancel a scheduled callback by name. */
schedulerCancel(name: string): { cancelled: boolean };
/** Optional sink for the capability audit log (host-side, hash-chained). */
audit?(entry: { pluginId: string; actingUserId?: number; method: string; resource: string | null; code: string }): void;
/** Call an export on another plugin (this host's plugin is the caller). Authorizes
* the dependency edge + the target's `provides` allowlist, forwards the acting user. */
callPlugin(targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
/** Publish an event from this host's plugin to its subscribed dependents. */
emitPluginEvent(event: string, payload: unknown): void;
/** True when the Costs (budget) addon is enabled — gates all costs.* methods. */
/** True if the acting user may create costs on the trip (the 'budget_edit' permission). */
/** A trip's packing items visible to `userId` (#858 private-item filter), for `packing.list`. */
/** A trip's files (trash excluded), for `files.list`. */
/** One trip file's bytes as base64 (size-capped), for `files.getContent`. Throws if it's not on the trip or exceeds the cap. */
// --- Files write (the app's file_upload / file_edit / file_delete permissions) ---
/** Store a bounded base64 payload as a trip file (extension + size validated); broadcasts file:created. */
/** Link an existing trip file to a reservation/place/assignment on the SAME trip. */
/** Update a file's description/links (same-trip targets enforced); broadcasts file:updated. */
/** Move a trip file to the trash; broadcasts file:deleted. */
// --- Collab reads (membership + collab addon; no separate right, like the REST GETs) ---
// --- Collab content (the app's collab_edit permission; collab addon gated) ---
// --- Member add (the DISTINCT member_manage permission — never bundled) ---
/** The acting user's own journals (journey addon must be enabled). */
/** The entries of one of the acting user's journeys (journey addon; access-checked). */
/** The acting user's visited countries + regions (atlas addon must be enabled). */
/** The acting user's bucket-list items (atlas addon must be enabled). */
/** The acting user's vacation plan data (vacay addon must be enabled). */
/** The acting user's saved-place collections (collections addon must be enabled). */
/** One of the acting user's collections by id (collections addon must be enabled). */
// --- Collections write (the service enforces per-collection role itself) ---
// --- Atlas write (all rows are the acting user's own; atlas addon gated) ---
// --- Vacay write (plan resolved from the acting user; vacay addon gated) ---
// --- Journal write (journeyService.canEdit self-gates; journey addon gated) ---
/** Create/delete a JOURNAL itself (owned by the acting user) — lets an importer
* bootstrap the journal it then fills, and clean it up. */
/** A trip day's notes (trip-scoped), for `daynotes.list`. */
/** Create a day note (the day must be on the trip); broadcasts dayNote:created. */
/** Update a day note (scoped to the day+trip); broadcasts dayNote:updated. */
/** Delete a day note (scoped to the day+trip); broadcasts dayNote:deleted. */
/** All budget items of one trip, hydrated with members/payers. */
/** All budget items across every trip the acting user can access. */
/** Create a budget item on a trip (and broadcast); returns the created item. */
/** Update a budget item on a trip (and broadcast); returns the updated item. */
/** Delete a budget item from a trip (and broadcast); returns { deleted: true }. */
// --- Places (the 'place_edit' permission) ---
/** Still needed by the db:meta gate, which has not moved yet. */
canEditTrip(tripId: number, userId: number): boolean;
/** Also still needed by the db:meta gate. */
canEditReservations(tripId: number, userId: number): boolean;
canEditPlaces(tripId: number, userId: number): boolean;
// --- Days + itinerary (the 'day_edit' permission) ---
canEditDays(tripId: number, userId: number): boolean;
/** Assign a place to a day (both trip-scoped by the wiring); returns the assignment. */
/** Remove a day-assignment (trip-scoped by the wiring). */
// --- Trip (the 'trip_edit' permission) ---
// --- Trip creation (the 'trip_create' permission; owner = acting user) ---
// --- Exchange rates (tenant-free, like weather) ---
// --- Cross-trip reads (membership baked in — every trip the acting user can access) ---
/** Every trip the acting user owns or is a member of (the listTrips baseline). */
/** Every reservation across the acting user's accessible trips. */
/** A trip's days with their assignments + day notes — the planner GET's shape. */
/** A trip's reservations, hydrated like the REST list (endpoints, day_positions, joins). */
/** A trip's lodging blocks (day_accommodations) with the joined place fields. */
// --- Accommodations write (the 'day_edit' permission, like the accommodations REST path) ---
/** Create a lodging block (auto-creates its partner hotel reservation + broadcasts); returns it. */
/** Update a lodging block (syncs the partner reservation); throws if it isn't on the trip. */
/** Delete a lodging block (cascades the partner reservation/budget row); returns { deleted: true }. */
// --- Reservations (the 'reservation_edit' permission) ---
/** Create a reservation (accommodation/budget side effects + broadcasts, as the web app); returns it. */
/** Update a reservation on a trip (same side effects); returns it, or throws if it isn't on the trip. */
/** Delete a reservation from a trip (same side effects); returns { deleted: true }. */
// --- Packing (the 'packing_edit' permission; #858 privacy-scoped broadcasts) ---
/** Create a packing item (owner = acting user); privacy-scoped packing:created broadcast; returns it. */
/** Update a packing item; four-case public<->private broadcast; throws if not on the trip. */
/** Delete a packing item; owner+recipients-scoped packing:deleted broadcast; returns { deleted: true }. */
// --- Packing bags (packing_edit; no privacy — broadcast to the whole room) ---
// --- Read-convenience: weather (tenant-free), categories (global), the trip roster ---
// --- Tags (the acting user's own; no trip) ---
// --- Todos (core, trip-scoped; the 'packing_edit' permission, like the REST path) ---
// --- Plugin metadata on core entities (db:meta) ---
/** The trip a trip/place/day belongs to (for the membership gate), or undefined. */
metaEntityTrip(entityType: string, entityId: number): number | undefined;
metaGet(entityType: string, entityId: number, key: string): unknown;
metaSet(entityType: string, entityId: number, key: string, value: unknown): unknown;
metaList(entityType: string, entityId: number): unknown;
metaDelete(entityType: string, entityId: number, key: string): unknown;
/** Optional sink for the capability audit log (host-side, hash-chained). */
audit?(entry: { pluginId: string; actingUserId?: number; method: string; resource: string | null; code: string }): void;
}
type Handler = (params: Record<string, unknown>, actingUserId: number | undefined) => unknown;
// Mirrors the STRING_LIMITS the places REST controller enforces (the @trek/shared
// schema doesn't), so the plugin write path rejects the same oversized fields.
const PLACE_STR_LIMITS: Record<string, number> = { name: 200, description: 2000, address: 500, notes: 2000 };
// Core entities a plugin may attach its own db:meta to. Each maps to an owning
// trip (metaEntityTrip) so the membership + edit gates are the standard ones.
const META_ENTITY_TYPES: ReadonlySet<string> = new Set(['trip', 'place', 'day', 'reservation', 'accommodation']);
// Same idea for trips — the @trek/shared schema leaves the title/description open,
// so mirror the REST controller's field limits on the plugin write path too.
const TRIP_STR_LIMITS: Record<string, number> = { title: 200, description: 2000 };
export class PluginRpcHost {
private methods = new Map<string, Handler>();
@@ -184,306 +59,27 @@ export class PluginRpcHost {
private readonly pluginId: string,
granted: ReadonlySet<string>,
private readonly deps: HostDeps,
// Additive and OPTIONAL, the same convention plugin-runtime.service.ts already
// uses for its own late-added params. Every existing
// `new PluginRpcHost(id, granted, deps)` site keeps compiling untouched, which is
// what makes the decorator rollout a per-domain move instead of a big-bang one.
registry?: PluginRpcRegistry,
registry: PluginRpcRegistry,
) {
const has = (p: string) => granted.has(p);
if (has('db:own')) {
this.methods.set('db.query', (p) => deps.data.query(str(p.sql, 'sql'), asArgs(p.args)));
this.methods.set('db.exec', (p) => deps.data.exec(str(p.sql, 'sql'), asArgs(p.args)));
this.methods.set('db.migrate', (p) => deps.data.migrate(str(p.id, 'id'), str(p.sql, 'sql')));
this.methods.set('db.tx', (p) => deps.data.tx(asTxOps(p.ops)));
}
// trips.*, reservations.listMine and the member roster now live in
// src/nest/trips/trips.rpc.ts.
// files.* now lives in src/nest/files/files.rpc.ts.
// User-scoped addon reads: the acting user's OWN journals/atlas/vacay across all
// their trips (not one trip), so — like costs.listMine — they are gated on a bound
// acting user, not a tripId; the wiring additionally refuses a disabled addon.
// collab, journal, atlas, vacay and collections now live in their own
// domains' *.rpc.ts, each carrying its addon gate with it.
// costs.* now lives in src/nest/budget/costs.rpc.ts.
// --- Core planner writes (#1429). Each mirrors costs.create: validate the
// input against the SAME @trek/shared schema the web app uses, then gate on
// trip access + the entity's edit permission for the HOST-bound acting user
// (a job/onLoad has no user, so its writes are refused). The delegating deps
// reuse the real services + broadcast the same events, so the app stays live. ---
// places.* now lives in src/nest/places/places.rpc.ts.
// days.* now lives in src/nest/days/days.rpc.ts.
// itinerary.* now lives in src/nest/assignments/itinerary.rpc.ts.
// rates.get now lives in src/nest/budget/exchange-rates.rpc.ts.
// daynotes.* now live in src/nest/days/day-notes.rpc.ts.
// reservations.* now lives in src/nest/reservations/reservations.rpc.ts.
// accommodations.* now lives in src/nest/days/accommodations.rpc.ts.
// packing.* now lives in src/nest/packing/packing.rpc.ts.
// weather.get and categories.list now live in their own domains' *.rpc.ts.
// tags.* now lives in src/nest/tags/tags.rpc.ts, bound through the registry below.
// todos.* now live in src/nest/todo/todo.rpc.ts.
if (has('db:meta')) {
// A plugin's OWN namespaced key/value store attached to a core entity. Not
// core data — but the entity must belong to a trip the acting user can
// ACCESS, so a plugin can't stash/read metadata against another tenant's rows.
this.methods.set('meta.get', (p, uid) => { const e = this.metaEntity(p, uid, false); return deps.metaGet(e.entityType, e.entityId, str(p.key, 'key')); });
this.methods.set('meta.set', (p, uid) => { const e = this.metaEntity(p, uid, true); return deps.metaSet(e.entityType, e.entityId, str(p.key, 'key'), p.value); });
this.methods.set('meta.list', (p, uid) => { const e = this.metaEntity(p, uid, false); return deps.metaList(e.entityType, e.entityId); });
this.methods.set('meta.delete', (p, uid) => { const e = this.metaEntity(p, uid, true); return deps.metaDelete(e.entityType, e.entityId, str(p.key, 'key')); });
}
if (has('db:read:users')) {
// Scope to people the acting user can actually see (self or a trip they
// share) so a plugin can't enumerate every account's profile by looping ids.
this.methods.set('users.getById', (p, uid) => {
const id = num(p.id, 'id');
if (uid === undefined) throw new ForbiddenResource('user reads require an authenticated user context');
if (id !== uid && !this.deps.canSeeUser(uid, id)) throw new ForbiddenResource(`no access to user ${id}`);
return deps.db.prepare('SELECT id, username, display_name, avatar FROM users WHERE id = ?').get(id);
});
}
if (has('ws:broadcast:trip')) {
// Gate the TARGET the same way reads are gated: a plugin may only push to a
// trip room the acting user is a member of — never an arbitrary/other-tenant
// trip. (Event-type namespacing alone doesn't cross the membership boundary.)
this.methods.set('ws.broadcastToTrip', (p, uid) => {
const tripId = num(p.tripId, 'tripId');
if (uid === undefined) throw new ForbiddenResource('broadcasts require an authenticated user context');
if (!this.deps.canAccessTrip(tripId, uid)) throw new ForbiddenResource(`no access to trip ${tripId}`);
deps.broadcastToTrip(tripId, str(p.event, 'event'), asPayload(p.data));
return { ok: true };
});
}
if (has('ws:broadcast:user')) {
// Restrict to the acting user's own connections — a plugin may not push to
// an arbitrary user it has no relationship to.
this.methods.set('ws.broadcastToUser', (p, uid) => {
const userId = num(p.userId, 'userId');
if (uid === undefined || userId !== uid) {
throw new ForbiddenResource('a plugin may only broadcast to the acting user');
}
deps.broadcastToUser(userId, { event: str(p.event, 'event'), ...asPayload(p.data) });
return { ok: true };
});
}
if (has('notify:send')) {
// Host-mediated notification. The plugin supplies only plain text + a target;
// the host owns recipient resolution, channel fan-out and per-user preferences.
// Recipients are FORCED to the acting user (scope 'user', targetId===uid) or a
// trip the acting user is a member of (scope 'trip'); scope 'admin' is refused,
// so there is no arbitrary-recipient / admin-broadcast path (no spam, no phishing).
this.methods.set('notify.send', (p, uid) => {
const actor = this.requireActor(uid, 'notification');
const input = asPayload(p.input);
// Emoji-stripped so a bell/push notification matches TREK's lucide-only UI (also
// trims + collapses whitespace). An all-emoji title collapses to '' → rejected.
const title = typeof input.title === 'string' ? stripEmoji(input.title) : '';
const body = typeof input.body === 'string' ? stripEmoji(input.body) : '';
if (!title || title.length > 200) throw new BadParams('notification title is required (max 200 chars)');
if (!body || body.length > 1000) throw new BadParams('notification body is required (max 1000 chars)');
const scope = input.scope;
if (scope !== 'user' && scope !== 'trip') throw new BadParams("scope must be 'user' or 'trip'");
const targetId = num(input.targetId, 'targetId');
if (scope === 'user' && targetId !== actor) throw new ForbiddenResource('a plugin may only notify the acting user');
if (scope === 'trip' && !deps.canAccessTripForNotify(targetId, actor)) throw new ForbiddenResource('the acting user is not a member of that trip');
let link: string | undefined;
if (typeof input.link === 'string' && input.link !== '') {
// In-app path only. A bare startsWith check misses `/\evil.com`, `/<tab>/…`
// etc. that browsers normalize to protocol-relative, so resolve against a
// throwaway origin and require the result to stay on it (same rule as the
// proxy's toRelativeLocation).
let safe: string | null = null;
try {
const u = new URL(input.link, 'http://x.invalid');
if (u.origin === 'http://x.invalid') safe = (u.pathname + u.search + u.hash);
} catch { /* invalid → rejected below */ }
if (!safe) throw new BadParams('link must be an in-app path starting with /');
link = safe.slice(0, 512);
}
return deps.sendPluginNotification(this.pluginId, { title, body, link, scope, targetId });
});
}
if (has('ai:invoke')) {
// Host-mediated LLM. The host holds the (encrypted) credential and runs the
// call under the acting user's resolved provider config; the plugin passes only
// a prompt / JSON-schema. Output is returned as DATA — never auto-written — so
// prompt-injection cannot reach a write without the plugin's own gated call.
this.methods.set('ai.complete', (p, uid) => {
const actor = this.requireActor(uid, 'AI');
if (!deps.aiConfigured(actor)) throw new BadParams('no AI provider is configured for this user');
const prompt = typeof p.prompt === 'string' ? p.prompt : '';
if (prompt.trim() === '') throw new BadParams('prompt is required');
if (prompt.length > 20000) throw new BadParams('prompt exceeds the 20000-char cap');
return deps.aiComplete(actor, prompt, typeof p.system === 'string' ? p.system.slice(0, 4000) : undefined);
});
this.methods.set('ai.extract', (p, uid) => {
const actor = this.requireActor(uid, 'AI');
if (!deps.aiConfigured(actor)) throw new BadParams('no AI provider is configured for this user');
const text = typeof p.text === 'string' ? p.text : '';
if (text.trim() === '') throw new BadParams('text is required');
if (text.length > 20000) throw new BadParams('text exceeds the 20000-char cap');
if (typeof p.jsonSchema !== 'object' || p.jsonSchema === null) throw new BadParams('jsonSchema (an object) is required');
return deps.aiExtract(actor, text, p.jsonSchema as object, typeof p.prompt === 'string' ? p.prompt.slice(0, 4000) : undefined);
});
}
if (has('oauth:client')) {
// Host-brokered outbound OAuth: return a short-lived access token for the acting
// user (the host ran the flow + holds the refresh token). Never yields a token for
// a userless context, and the plugin can never reach the refresh token/secret.
this.methods.set('oauth.getToken', async (_p, uid) => {
// Userless context (a job/scheduled task) → null, matching the SDK contract + mock
// ("null when the user hasn't connected or in a userless context"), rather than
// throwing RESOURCE_FORBIDDEN, which a background caller can't meaningfully handle.
if (uid === undefined) return { accessToken: null };
return { accessToken: await deps.getOAuthToken(this.pluginId, uid) };
});
}
if (has('jobs:run')) {
// Persistent scheduler: a plugin schedules a userless future callback (once or
// recurring) that survives restarts. Same grant + risk class as its cron jobs.
// Caps are enforced in the wiring (max entries, name/payload size, min interval).
this.methods.set('scheduler.set', (p) => {
const name = str(p.name, 'name');
const dueAt = num(p.dueAt, 'dueAt');
const everyMs = p.everyMs != null ? num(p.everyMs, 'everyMs') : undefined;
return deps.schedulerSet(name, dueAt, everyMs, p.payload ?? null);
});
this.methods.set('scheduler.cancel', (p) => deps.schedulerCancel(str(p.name, 'name')));
}
// Inter-plugin capabilities (#plugins deps). Registered UNCONDITIONALLY — there
// is no permission for these; the router authorizes each call against the
// declared dependency edge + the target's `provides`/`emits` allowlist. The
// acting user is forwarded so the target's export runs as the caller's user.
this.methods.set('plugins.call', (p, uid) =>
deps.callPlugin(str(p.targetId, 'targetId'), str(p.fn, 'fn'), p.args, uid),
);
this.methods.set('events.emit', (p) => {
deps.emitPluginEvent(str(p.event, 'event'), p.payload);
return { ok: true };
});
// The plugin's OWN per-user settings (the acting user's `scope:'user'` values,
// decrypted host-side). Unconditional + not sensitive cross-tenant — it only ever
// returns THIS plugin's config for the acting user. A userless context (job/onLoad)
// has no user, so it returns undefined (the plugin falls back to ctx.config).
this.methods.set('settings.get', (p, uid) => {
if (uid === undefined) return { value: undefined };
return { value: deps.getUserSetting(this.pluginId, uid, str(p.key, 'key')) };
});
// LAST on purpose: a method still owned by one of the has() blocks above then
// collides loudly in bindInto instead of being silently overridden, which is the
// failure mode a half-finished domain move would otherwise have.
//
// `deps.data` is already the lazy per-access getter the factory supplies, so
// passing it through a getter here preserves the disable/re-enable semantics
// exactly and the kit never needs to know about plugin-host-state.
registry?.bindInto(this.methods, granted, (actingUserId) => ({
// `deps.data` is the lazy per-access getter the factory supplies, so passing it
// through a getter here preserves the disable/re-enable semantics exactly and the
// kit never needs to know about plugin-host-state.
registry.bindInto(this.methods, granted, (actingUserId) => ({
pluginId,
actingUserId,
get data() {
return deps.data;
},
// Per host, like everything else on the context: the router behind these binds
// THIS plugin as the caller, which is what lets it authorise a call against the
// declared dependency edge and the target's provides/emits allowlist.
plugins: {
call: (targetId, fn, args, uid) => deps.callPlugin(targetId, fn, args, uid),
emit: (event, payload) => deps.emitPluginEvent(event, payload),
},
}));
}
/**
* Membership-check every trip read against the acting user. The acting user is
* bound by the HOST from the authenticated invocation (see the supervisor's
* invocation map) — NOT taken from a plugin-supplied `asUserId`, which a plugin
* could set to any id to read another user's trips. If no acting user is bound
* (a job / onLoad, or a forged call), the read is forbidden.
*/
private tripRead(p: Record<string, unknown>, actingUserId: number | undefined, read: (userId: number) => unknown): unknown {
const tripId = num(p.tripId, 'tripId');
if (actingUserId === undefined) {
throw new ForbiddenResource('trip reads require an authenticated user context');
}
if (!this.deps.canAccessTrip(tripId, actingUserId)) {
throw new ForbiddenResource(`no access to trip ${tripId}`);
}
// The read runs only for a bound, membership-checked user — hand it through so
// per-user visibility filters (e.g. packing's #858 private items) can apply.
return read(actingUserId);
}
/**
* Every write needs a HOST-bound acting user. A job / onLoad (no user) or a call
* with a forged/unknown invocation id resolves to undefined and is refused — a
* plugin can never write "as" an arbitrary user.
*/
private requireActor(uid: number | undefined, noun: string): number {
if (uid === undefined) throw new ForbiddenResource(`${noun} writes require an authenticated user context`);
return uid;
}
/**
* The @trek/shared write schemas don't carry the string-length caps the REST
* controllers add, so mirror those caps here — otherwise a plugin could write a
* field the web app would reject with 400 (e.g. a 100k-char place name).
*/
private capStrings(input: Record<string, unknown>, limits: Record<string, number>): void {
for (const [field, max] of Object.entries(limits)) {
const v = input[field];
if (typeof v === 'string' && v.length > max) throw new BadParams(`${field} must be ${max} characters or fewer`);
}
}
/** A write is allowed only if the acting user can access AND edit the trip. */
private requireTripEdit(tripId: number, uid: number, canEdit: (t: number, u: number) => boolean): void {
if (!this.deps.canAccessTrip(tripId, uid)) throw new ForbiddenResource(`no access to trip ${tripId}`);
if (!canEdit(tripId, uid)) throw new ForbiddenResource(`no permission to edit trip ${tripId}`);
}
/**
* Validate a metadata target and gate it: the entity type must be one we support,
* and the trip it belongs to must be accessible to the host-bound acting user.
*/
private metaEntity(p: Record<string, unknown>, uid: number | undefined, write: boolean): { entityType: string; entityId: number } {
const entityType = str(p.entityType, 'entityType');
if (!META_ENTITY_TYPES.has(entityType)) {
throw new BadParams(`invalid entityType "${entityType}" (${[...META_ENTITY_TYPES].join('|')})`);
}
const entityId = num(p.entityId, 'entityId');
if (uid === undefined) throw new ForbiddenResource('metadata requires an authenticated user context');
const tripId = this.deps.metaEntityTrip(entityType, entityId);
if (tripId === undefined || !this.deps.canAccessTrip(tripId, uid)) {
throw new ForbiddenResource(`no access to ${entityType} ${entityId}`);
}
// Reads need trip access; WRITES additionally need the entity's edit permission
// — so a read-only member can't overwrite/delete metadata an editor created
// (matches how core writes are gated). Accommodations ride on day_edit (like
// the accommodation write path), reservations on reservation_edit.
if (write) {
const canEdit = entityType === 'trip' ? this.deps.canEditTrip
: entityType === 'place' ? this.deps.canEditPlaces
: entityType === 'reservation' ? this.deps.canEditReservations
: this.deps.canEditDays; // day + accommodation
if (!canEdit(tripId, uid)) throw new ForbiddenResource(`no permission to edit ${entityType} ${entityId}`);
}
return { entityType, entityId };
}
async dispatch(req: RpcRequest, actingUserId?: number): Promise<RpcResponse | RpcError> {
const raw = (req.params ?? {}) as Record<string, unknown>;
// The supervisor resolves the acting user from `_inv` BEFORE dispatch and passes
@@ -550,16 +146,3 @@ export class PluginRpcHost {
}
}
}
/**
* The reservation body is passthrough by contract, but a malformed `endpoints`
* array would otherwise fail DEEP in the service (NOT-NULL mid-transaction) or be
* dropped silently (missing coords) — both miserable to debug from a plugin. So
* the plugin path pins the endpoint shape up front; absent stays absent
* (update semantics: omitted = keep, [] = delete all).
*/
function requireValidEndpoints(v: unknown): void {
if (v === undefined) return;
const parsed = reservationEndpointsInputSchema.safeParse(v);
if (!parsed.success) throw new BadParams(`invalid endpoints: ${parsed.error.issues[0]?.message ?? 'bad input'}`);
}
@@ -74,5 +74,8 @@ from the generated `plugin-sdk/src/generated/host-facts.ts` instead.
A `@PluginController()` class that is missing from its module's `providers: []` is
invisible to discovery. Its methods are simply never bound, and every call to them
comes back `PERMISSION_DENIED` with no other symptom. The compiler cannot see this.
What catches it is `server/tests/unit/plugins/rpc-coverage.test.ts`, and, once the
rollout is finished, `requireTotalCoverage: true` turning it into a boot failure.
`requireTotalCoverage` is now on, so the app refuses to boot instead: `validate()`
names every `KNOWN_METHOD` left without a handler, and every hook left without a
host-side consumer. `server/tests/unit/plugins/rpc-coverage.test.ts` catches the same
gap in CI, before anyone starts the server.
@@ -17,12 +17,29 @@ export class PluginRpcRegistryService extends PluginRpcRegistry implements OnMod
private readonly discovery: DiscoveryService,
private readonly scanner: MetadataScanner,
) {
// Flipped to true in the closing PR of the rollout, once the legacy router map
// in rpc-host.ts is empty and every KNOWN_METHOD has a decorated owner.
super({ requireTotalCoverage: false });
// The rollout is done: the legacy router map is gone, every KNOWN_METHOD has a
// decorated owner and every hook has a host-side consumer. Boot now FAILS on a
// gap rather than letting it surface as a runtime PERMISSION_DENIED, or as a
// hook:* grant on the consent screen that nothing behind it ever calls.
super({ requireTotalCoverage: true });
}
onModuleInit(): void {
this.scanProviders();
// Fail app boot on a wrong decorator argument, a double-owned method or a gap in
// the surface, rather than failing per-plugin at activation time.
this.validate();
}
/**
* Records every `@PluginController()` provider the container knows about.
*
* Separate from validate() because the two answer different questions: this one is
* about discovery (which providers were found, and once each), validate() is about
* the surface being complete and correctly declared. Keeping them apart lets the
* discovery behaviour be tested without assembling all 113 methods first.
*/
scanProviders(): void {
// A provider can be wrapped once per module that lists it, so dedupe by instance
// or every entry is recorded twice and the duplicate check fires spuriously.
const seen = new Set<object>();
@@ -33,8 +50,5 @@ export class PluginRpcRegistryService extends PluginRpcRegistry implements OnMod
seen.add(instance);
this.register(instance, this.scanner.getAllMethodNames(Object.getPrototypeOf(instance)));
}
// Fail app boot on a wrong decorator argument or a double-owned method rather
// than failing per-plugin at activation time.
this.validate();
}
}
@@ -19,6 +19,22 @@ export interface PluginRpcContext {
readonly pluginId: string;
readonly actingUserId: number | undefined;
readonly data: PluginDataDb;
/**
* The inter-plugin capabilities. PER HOST, like everything else on this context:
* the router that backs them is created per plugin and binds THIS plugin as the
* caller, which is what lets it authorise a call against the declared dependency
* edge and the target's provides/emits allowlist.
*
* Typed structurally rather than imported, so the kit stays free of host imports
* (see rpc-kit/README.md). The host supplies the real router when it binds.
*/
readonly plugins: PluginRpcPeers;
}
/** What a plugin may do to its declared dependencies. */
export interface PluginRpcPeers {
call(targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
emit(event: string, payload: unknown): void;
}
export type PluginRpcHandler = (params: Record<string, unknown>, ctx: PluginRpcContext) => unknown;
@@ -0,0 +1,65 @@
import { PluginController, PluginMethod, PluginOpenMethod } from '../rpc-kit/decorators';
import { asArgs, asTxOps, str } from '../rpc-params';
import type { PluginRpcContext } from '../rpc-kit/types';
import { readUserSettingDecrypted } from '../../plugins.service';
/**
* A plugin's OWN sqlite, plus the three methods the router registers unconditionally.
*
* Every method reads `ctx.data` fresh. It must never be captured in a field or a
* closure: the handle is per plugin, and disable()/re-enable builds a new host while
* the old one's dispose() may still be closing the previous handle. A captured one
* would be both a stale-handle bug and, in a singleton like this, a cross-plugin data
* leak, since one instance serves every plugin.
*/
@PluginController()
export class DbRpc {
@PluginMethod('db.query', { permission: 'db:own' })
query(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return ctx.data.query(str(params.sql, 'sql'), asArgs(params.args));
}
@PluginMethod('db.exec', { permission: 'db:own' })
exec(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return ctx.data.exec(str(params.sql, 'sql'), asArgs(params.args));
}
@PluginMethod('db.migrate', { permission: 'db:own' })
migrate(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return ctx.data.migrate(str(params.id, 'id'), str(params.sql, 'sql'));
}
@PluginMethod('db.tx', { permission: 'db:own' })
tx(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return ctx.data.tx(asTxOps(params.ops));
}
/**
* Inter-plugin call. No permission of its own: the router authorises it against
* the declared dependency edge and the target's `provides` allowlist. The acting
* user is forwarded so the target's export runs as the caller's user.
*/
@PluginOpenMethod('plugins.call')
callPlugin(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
return ctx.plugins.call(str(params.targetId, 'targetId'), str(params.fn, 'fn'), params.args, ctx.actingUserId);
}
/** Same deal: the router checks the emitter's `emits` allowlist. */
@PluginOpenMethod('events.emit')
emitEvent(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
ctx.plugins.emit(str(params.event, 'event'), params.payload);
return { ok: true };
}
/**
* The plugin's OWN per-user settings, decrypted host-side. Unconditional and not
* cross-tenant: it only ever returns THIS plugin's config for the acting user. A
* userless context (a job or onLoad) has no user, so it returns undefined and the
* plugin falls back to ctx.config.
*/
@PluginOpenMethod('settings.get')
getSetting(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
if (ctx.actingUserId === undefined) return { value: undefined };
return { value: readUserSettingDecrypted(ctx.pluginId, ctx.actingUserId, str(params.key, 'key')) };
}
}
@@ -0,0 +1,250 @@
import { PluginController, PluginMethod } from '../rpc-kit/decorators';
import { PluginGuards } from '../plugin-guards.service';
import { BadParams, ForbiddenResource } from '../rpc-errors';
import { asPayload, num, str } from '../rpc-params';
import type { PluginRpcContext } from '../rpc-kit/types';
import { budgetFor } from '../plugin-host-state';
import { DatabaseService } from '../../../database/database.service';
import { RealtimeService } from '../../../realtime/realtime.service';
import { NotificationsService } from '../../../notifications/notifications.service';
import { LlmConfigResolver } from '../../../llm-parse/llm-config.resolver';
import { createLlmClient } from '../../../llm-parse/llm-client.factory';
import { PluginOAuthService } from '../../plugin-oauth.service';
import { stripEmoji } from '../../text-sanitize';
/** Caps on the persistent scheduler, bounding the abuse surface. */
const SCHED_MAX = 100; // entries per plugin
const SCHED_NAME_MAX = 128;
const SCHED_PAYLOAD_MAX = 8 * 1024; // 8 KB JSON
const SCHED_EVERY_MIN = 60_000; // 1 min floor for a recurring task
const SCHED_DUE_WINDOW = 366 * 24 * 60 * 60 * 1000; // at most ~a year out
const AI_TEXT_MAX = 20_000;
/**
* The host-mediated surface: the user lookup, the two broadcasts, notifications, the
* LLM bridge, the OAuth token and the persistent scheduler.
*
* What these have in common is that the HOST owns the dangerous half. The plugin
* supplies a prompt, a message or a target; recipient resolution, credentials,
* channel fan-out and the event namespace stay here, and every target is scoped to
* something the acting user may already reach.
*/
@PluginController()
export class HostSurfaceRpc {
constructor(
private readonly db: DatabaseService,
private readonly realtime: RealtimeService,
private readonly notifications: NotificationsService,
private readonly llmConfig: LlmConfigResolver,
private readonly oauth: PluginOAuthService,
private readonly guards: PluginGuards,
) {}
@PluginMethod('users.getById', { permission: 'db:read:users' })
getUser(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
// Scoped to people the acting user can actually see (themselves, or someone they
// share a trip with), so a plugin cannot enumerate every account by looping ids.
const id = num(params.id, 'id');
if (ctx.actingUserId === undefined) throw new ForbiddenResource('user reads require an authenticated user context');
if (id !== ctx.actingUserId && !this.sharesATrip(ctx.actingUserId, id)) {
throw new ForbiddenResource(`no access to user ${id}`);
}
return this.db.prepare('SELECT id, username, display_name, avatar FROM users WHERE id = ?').get(id);
}
@PluginMethod('ws.broadcastToTrip', { permission: 'ws:broadcast:trip' })
broadcastToTrip(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
// The TARGET is gated like a read: only a trip room the acting user belongs to.
// Namespacing the event type alone does not cross the membership boundary.
const tripId = num(params.tripId, 'tripId');
if (ctx.actingUserId === undefined) throw new ForbiddenResource('broadcasts require an authenticated user context');
if (!this.db.canAccessTrip(tripId, ctx.actingUserId)) throw new ForbiddenResource(`no access to trip ${tripId}`);
// The host forces the plugin:{id}:{event} namespace, so a plugin cannot forge a
// core event.
this.realtime.broadcast(tripId, `plugin:${ctx.pluginId}:${str(params.event, 'event')}`, asPayload(params.data));
return { ok: true };
}
@PluginMethod('ws.broadcastToUser', { permission: 'ws:broadcast:user' })
broadcastToUser(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
// Authorised by identity, not by a predicate: only the acting user's own sockets.
const userId = num(params.userId, 'userId');
if (ctx.actingUserId === undefined || userId !== ctx.actingUserId) {
throw new ForbiddenResource('a plugin may only broadcast to the acting user');
}
this.realtime.broadcastToUser(userId, {
type: `plugin:${ctx.pluginId}`,
event: str(params.event, 'event'),
...asPayload(params.data),
});
return { ok: true };
}
@PluginMethod('notify.send', { permission: 'notify:send' })
async notify(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
const actor = this.guards.requireActor(ctx, 'notification');
const input = asPayload(params.input);
// Emoji-stripped so a bell or push notification matches the lucide-only UI; this
// also trims and collapses whitespace, so an all-emoji title collapses to '' and
// is rejected below.
const title = typeof input.title === 'string' ? stripEmoji(input.title) : '';
const body = typeof input.body === 'string' ? stripEmoji(input.body) : '';
if (!title || title.length > 200) throw new BadParams('notification title is required (max 200 chars)');
if (!body || body.length > 1000) throw new BadParams('notification body is required (max 1000 chars)');
const scope = input.scope;
// 'admin' is deliberately absent: there is no arbitrary-recipient or
// admin-broadcast path, so a plugin cannot spam or phish through the host.
if (scope !== 'user' && scope !== 'trip') throw new BadParams("scope must be 'user' or 'trip'");
const targetId = num(input.targetId, 'targetId');
if (scope === 'user' && targetId !== actor) throw new ForbiddenResource('a plugin may only notify the acting user');
if (scope === 'trip' && !this.db.canAccessTrip(targetId, actor)) {
throw new ForbiddenResource('the acting user is not a member of that trip');
}
const link = this.safeLink(input.link);
if (!budgetFor(ctx.pluginId).take('notify', Date.now())) {
throw new BadParams('daily notification budget exhausted (resets at UTC midnight)');
}
await this.notifications.send({
event: 'plugin_notification',
actorId: null,
params: { title, body, ...(link ? { link } : {}) },
scope,
targetId,
inApp: link ? { navigateTarget: link } : undefined,
});
return { sent: true };
}
@PluginMethod('ai.complete', { permission: 'ai:invoke' })
async aiComplete(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
const actor = this.guards.requireActor(ctx, 'AI');
const config = this.requireLlm(actor);
const prompt = typeof params.prompt === 'string' ? params.prompt : '';
if (prompt.trim() === '') throw new BadParams('prompt is required');
if (prompt.length > AI_TEXT_MAX) throw new BadParams(`prompt exceeds the ${AI_TEXT_MAX}-char cap`);
this.takeAiBudget(ctx);
const system = typeof params.system === 'string' ? params.system.slice(0, 4000) : undefined;
const results = await createLlmClient(config).extract({
prompt: system || 'You are a helpful assistant. Reply with a JSON object of the form {"text": "..."} whose "text" field holds your answer.',
jsonSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
model: config.model,
baseUrl: config.baseUrl,
apiKey: config.apiKey,
text: prompt,
});
const first = results[0] as { text?: unknown } | undefined;
return { text: typeof first?.text === 'string' ? first.text : '' };
}
@PluginMethod('ai.extract', { permission: 'ai:invoke' })
async aiExtract(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
const actor = this.guards.requireActor(ctx, 'AI');
const config = this.requireLlm(actor);
const text = typeof params.text === 'string' ? params.text : '';
if (text.trim() === '') throw new BadParams('text is required');
if (text.length > AI_TEXT_MAX) throw new BadParams(`text exceeds the ${AI_TEXT_MAX}-char cap`);
if (typeof params.jsonSchema !== 'object' || params.jsonSchema === null) {
throw new BadParams('jsonSchema (an object) is required');
}
this.takeAiBudget(ctx);
const hint = typeof params.prompt === 'string' ? params.prompt.slice(0, 4000) : '';
const results = await createLlmClient(config).extract({
prompt: hint || 'Extract structured data from the text into the given JSON schema.',
jsonSchema: params.jsonSchema as object,
model: config.model,
baseUrl: config.baseUrl,
apiKey: config.apiKey,
text,
});
return { results };
}
@PluginMethod('oauth.getToken', { permission: 'oauth:client' })
async getOAuthToken(_params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
// A userless context (a job or scheduled task) gets null rather than a refusal,
// matching the SDK contract and its mock: a background caller cannot do anything
// useful with RESOURCE_FORBIDDEN. The plugin never sees the refresh token.
if (ctx.actingUserId === undefined) return { accessToken: null };
return { accessToken: await this.oauth.getAccessToken(ctx.pluginId, ctx.actingUserId, Date.now()) };
}
@PluginMethod('scheduler.set', { permission: 'jobs:run' })
schedulerSet(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const name = str(params.name, 'name');
const dueAt = num(params.dueAt, 'dueAt');
const everyMs = params.everyMs != null ? num(params.everyMs, 'everyMs') : undefined;
if (!name || name.length > SCHED_NAME_MAX) throw new BadParams(`scheduler name is required (max ${SCHED_NAME_MAX} chars)`);
if (!Number.isFinite(dueAt) || dueAt > Date.now() + SCHED_DUE_WINDOW) throw new BadParams('scheduler dueAt out of range');
if (everyMs !== undefined && (!Number.isFinite(everyMs) || everyMs < SCHED_EVERY_MIN)) {
throw new BadParams(`recurring interval must be >= ${SCHED_EVERY_MIN} ms`);
}
const json = JSON.stringify(params.payload ?? null);
if (json.length > SCHED_PAYLOAD_MAX) throw new BadParams(`scheduler payload too large (max ${SCHED_PAYLOAD_MAX} bytes)`);
const existing = this.db
.prepare('SELECT id FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?')
.get(ctx.pluginId, name) as { id: number } | undefined;
if (!existing) {
const n = (this.db.prepare('SELECT COUNT(*) AS c FROM plugin_scheduled_tasks WHERE plugin_id = ?').get(ctx.pluginId) as { c: number }).c;
if (n >= SCHED_MAX) throw new BadParams(`too many scheduled tasks (max ${SCHED_MAX})`);
}
// Upsert by (plugin, name): re-scheduling the same name replaces it.
this.db
.prepare(`INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at, payload, every_ms) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (plugin_id, name) DO UPDATE SET due_at = excluded.due_at, payload = excluded.payload, every_ms = excluded.every_ms`)
.run(ctx.pluginId, name, Math.max(dueAt, Date.now()), json, everyMs ?? null);
return { scheduled: true };
}
@PluginMethod('scheduler.cancel', { permission: 'jobs:run' })
schedulerCancel(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const r = this.db
.prepare('DELETE FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?')
.run(ctx.pluginId, str(params.name, 'name'));
return { cancelled: r.changes > 0 };
}
/** Two users share a trip when both are owner-or-member of the same one. */
private sharesATrip(actingUserId: number, targetUserId: number): boolean {
return !!this.db
.prepare(
`SELECT 1 FROM trips t
LEFT JOIN trip_members m1 ON m1.trip_id = t.id AND m1.user_id = ?
LEFT JOIN trip_members m2 ON m2.trip_id = t.id AND m2.user_id = ?
WHERE (t.user_id = ? OR m1.user_id IS NOT NULL)
AND (t.user_id = ? OR m2.user_id IS NOT NULL)
LIMIT 1`,
)
.get(actingUserId, targetUserId, actingUserId, targetUserId);
}
private requireLlm(userId: number) {
const config = this.llmConfig.resolve(userId);
if (!config) throw new BadParams('no AI provider is configured for this user');
return config;
}
private takeAiBudget(ctx: PluginRpcContext): void {
if (!budgetFor(ctx.pluginId).take('ai', Date.now())) {
throw new BadParams('daily AI budget exhausted (resets at UTC midnight)');
}
}
/**
* In-app paths only. A bare startsWith check misses `/\evil.com` and `/<tab>/…`,
* which browsers normalize to protocol-relative, so resolve against a throwaway
* origin and require the result to stay on it.
*/
private safeLink(value: unknown): string | undefined {
if (typeof value !== 'string' || value === '') return undefined;
let safe: string | null = null;
try {
const u = new URL(value, 'http://x.invalid');
if (u.origin === 'http://x.invalid') safe = u.pathname + u.search + u.hash;
} catch {
/* invalid, rejected below */
}
if (!safe) throw new BadParams('link must be an in-app path starting with /');
return safe.slice(0, 512);
}
}
@@ -0,0 +1,150 @@
import { PluginController, PluginMethod } from '../rpc-kit/decorators';
import { PluginGuards } from '../plugin-guards.service';
import { BadParams, ForbiddenResource } from '../rpc-errors';
import { num, str } from '../rpc-params';
import type { PluginRpcContext } from '../rpc-kit/types';
import { DatabaseService } from '../../../database/database.service';
/** Core entities a plugin may attach its own db:meta to. */
const META_ENTITY_TYPES: ReadonlySet<string> = new Set(['trip', 'place', 'day', 'reservation', 'accommodation']);
// Quotas: a cheap disk-DoS guard on the shared trek.db volume. Generous for real use,
// small enough to bound abuse.
const META_VALUE_MAX = 64 * 1024; // serialized JSON bytes per value
const META_KEY_MAX = 256; // key length (the key is attacker-controlled too)
const META_KEYS_MAX = 100; // keys per (plugin, entity)
/** Which edit permission an entity type rides on. Accommodations ride on days. */
const EDIT_ACTION: Record<string, string> = {
trip: 'trip_edit',
place: 'place_edit',
reservation: 'reservation_edit',
day: 'day_edit',
accommodation: 'day_edit',
};
/** Each of these tables has a NOT NULL trip_id, so the gate resolves the owning trip. */
const ENTITY_TABLE: Record<string, string> = {
place: 'places',
day: 'days',
reservation: 'reservations',
accommodation: 'day_accommodations',
};
/**
* A plugin's OWN namespaced key/value store, attached to a core entity (#plugins).
*
* The rows are not core data, but the entity they hang off must belong to a trip the
* acting user can access, so a plugin cannot stash or read metadata against another
* tenant's rows. Writes additionally need that entity's edit permission, so a
* read-only member cannot overwrite metadata an editor created.
*
* Every row is tagged with the plugin id, so one plugin never sees another's keys.
*/
@PluginController()
export class MetaRpc {
constructor(
private readonly db: DatabaseService,
private readonly guards: PluginGuards,
) {}
@PluginMethod('meta.get', { permission: 'db:meta' })
get(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const { entityType, entityId } = this.resolveEntity(params, ctx, false);
const row = this.db
.prepare('SELECT value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
.get(ctx.pluginId, entityType, entityId, str(params.key, 'key')) as { value: string } | undefined;
if (!row) return null;
try {
return JSON.parse(row.value);
} catch {
return null;
}
}
@PluginMethod('meta.set', { permission: 'db:meta' })
set(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const { entityType, entityId } = this.resolveEntity(params, ctx, true);
const key = str(params.key, 'key');
if (key.length > META_KEY_MAX) throw new BadParams(`metadata key too long (>${META_KEY_MAX} chars)`);
const json = JSON.stringify(params.value ?? null);
if (json.length > META_VALUE_MAX) throw new BadParams(`metadata value too large (>${META_VALUE_MAX} bytes)`);
const exists = this.db
.prepare('SELECT 1 FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
.get(ctx.pluginId, entityType, entityId, key);
if (!exists) {
const { n } = this.db
.prepare('SELECT COUNT(*) AS n FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=?')
.get(ctx.pluginId, entityType, entityId) as { n: number };
if (n >= META_KEYS_MAX) throw new BadParams(`too many metadata keys on this ${entityType} (max ${META_KEYS_MAX})`);
}
this.db
.prepare(`INSERT INTO plugin_entity_metadata (plugin_id, entity_type, entity_id, key, value, updated_at)
VALUES (?, ?, ?, ?, ?, datetime('now'))
ON CONFLICT(plugin_id, entity_type, entity_id, key)
DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`)
.run(ctx.pluginId, entityType, entityId, key, json);
return { key, value: params.value ?? null };
}
@PluginMethod('meta.list', { permission: 'db:meta' })
list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const { entityType, entityId } = this.resolveEntity(params, ctx, false);
const rows = this.db
.prepare('SELECT key, value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? ORDER BY key')
.all(ctx.pluginId, entityType, entityId) as Array<{ key: string; value: string }>;
const out: Record<string, unknown> = {};
for (const r of rows) {
try {
out[r.key] = JSON.parse(r.value);
} catch {
out[r.key] = null;
}
}
return out;
}
@PluginMethod('meta.delete', { permission: 'db:meta' })
delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
const { entityType, entityId } = this.resolveEntity(params, ctx, true);
const res = this.db
.prepare('DELETE FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
.run(ctx.pluginId, entityType, entityId, str(params.key, 'key'));
return { deleted: res.changes > 0 };
}
/**
* Validates the target and gates it: a supported entity type, an entity that
* resolves to a trip the acting user can access, and for a write that entity's own
* edit permission.
*/
private resolveEntity(
params: Record<string, unknown>,
ctx: PluginRpcContext,
write: boolean,
): { entityType: string; entityId: number } {
const entityType = str(params.entityType, 'entityType');
if (!META_ENTITY_TYPES.has(entityType)) {
throw new BadParams(`invalid entityType "${entityType}" (${[...META_ENTITY_TYPES].join('|')})`);
}
const entityId = num(params.entityId, 'entityId');
if (ctx.actingUserId === undefined) throw new ForbiddenResource('metadata requires an authenticated user context');
const tripId = this.entityTrip(entityType, entityId);
if (tripId === undefined || !this.db.canAccessTrip(tripId, ctx.actingUserId)) {
throw new ForbiddenResource(`no access to ${entityType} ${entityId}`);
}
if (write && !this.guards.canEditAs(EDIT_ACTION[entityType], tripId, ctx.actingUserId)) {
throw new ForbiddenResource(`no permission to edit ${entityType} ${entityId}`);
}
return { entityType, entityId };
}
private entityTrip(entityType: string, entityId: number): number | undefined {
if (entityType === 'trip') {
return (this.db.prepare('SELECT id FROM trips WHERE id = ?').get(entityId) as { id: number } | undefined)?.id;
}
// The table name comes from a fixed map, never from the request.
const table = ENTITY_TABLE[entityType];
return (this.db.prepare(`SELECT trip_id FROM ${table} WHERE id = ?`).get(entityId) as { trip_id: number } | undefined)?.trip_id;
}
}
@@ -6,7 +6,7 @@ import { AddonsService } from '../addons/addons.service';
import { ADDON_IDS } from '../../addons';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -67,7 +67,7 @@ function normalize(raw: unknown): EntryRow[] {
@UseGuards(JwtAuthGuard)
export class JournalEntryRowsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
private readonly addons: AddonsService,
private readonly journey: JourneyDomainService,
@@ -87,11 +87,11 @@ export class JournalEntryRowsController {
const row = this.dbs.connection.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as { journey_id: number } | undefined;
if (!row || !this.journey.canAccessJourney(row.journey_id, userId)) return { providers: [] };
const ids = this.runtime.providersOf('journalEntryProvider');
const ids = this.hooks.providersOf('journalEntryProvider');
const results = await Promise.all(
ids.map(async (id): Promise<ProviderResult | null> => {
try {
const raw = await this.runtime.invokeHook(id, 'journalEntryProvider', 'getRows', [entryId], userId, 5000);
const raw = await this.hooks.journalRows(id, entryId, userId);
const items = normalize(raw);
return items.length > 0 ? { pluginId: id, items } : null;
} catch {
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -146,7 +146,7 @@ function normalize(pluginId: string, raw: unknown): MapLayer[] {
@UseGuards(JwtAuthGuard)
export class MapLayersController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -160,11 +160,11 @@ export class MapLayersController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { layers: [] };
const ids = this.runtime.providersOf('mapLayerProvider');
const ids = this.hooks.providersOf('mapLayerProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<MapLayer[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'mapLayerProvider', 'getLayers', [tripId], userId, 5000);
const raw = await this.hooks.mapLayers(id, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -79,7 +79,7 @@ function normalize(pluginId: string, raw: unknown): MapMarker[] {
@UseGuards(JwtAuthGuard)
export class MapMarkersController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -93,11 +93,11 @@ export class MapMarkersController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { markers: [] };
const ids = this.runtime.providersOf('mapMarkerProvider');
const ids = this.hooks.providersOf('mapMarkerProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<MapMarker[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'mapMarkerProvider', 'getMarkers', [tripId], userId, 5000);
const raw = await this.hooks.mapMarkers(id, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -75,7 +75,7 @@ function normalize(pluginId: string, raw: unknown): PdfSection[] {
@UseGuards(JwtAuthGuard)
export class PdfSectionsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -89,11 +89,11 @@ export class PdfSectionsController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { sections: [] };
const ids = this.runtime.providersOf('pdfSectionProvider');
const ids = this.hooks.providersOf('pdfSectionProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<PdfSection[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'pdfSectionProvider', 'getSections', [tripId], userId, 5000);
const raw = await this.hooks.pdfSections(id, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -62,7 +62,7 @@ function normalize(raw: unknown): DetailItem[] {
@UseGuards(JwtAuthGuard)
export class PlaceDetailsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -80,11 +80,11 @@ export class PlaceDetailsController {
const row = this.dbs.connection.prepare('SELECT trip_id FROM places WHERE id = ?').get(placeId) as { trip_id: number } | undefined;
if (!row || !this.dbs.canAccessTrip(row.trip_id, userId)) return { providers: [] };
const ids = this.runtime.providersOf('placeDetailProvider');
const ids = this.hooks.providersOf('placeDetailProvider');
const results = await Promise.all(
ids.map(async (id): Promise<ProviderResult | null> => {
try {
const raw = await this.runtime.invokeHook(id, 'placeDetailProvider', 'getDetails', [placeId], userId, 5000);
const raw = await this.hooks.placeDetails(id, placeId, userId);
const items = normalize(raw);
return items.length > 0 ? { pluginId: id, items } : null;
} catch {
@@ -2,7 +2,7 @@ import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -39,7 +39,7 @@ function normalizeEvents(pluginId: string, source: string, raw: unknown): DevEve
@Controller('api/plugin-calendar')
@UseGuards(JwtAuthGuard)
export class PluginCalendarController {
constructor(private readonly runtime: PluginRuntimeService) {}
constructor(private readonly hooks: PluginHooks) {}
@Get()
async get(
@@ -54,13 +54,13 @@ export class PluginCalendarController {
const s = isoish(start) ?? new Date(Date.now() - 90 * 864e5).toISOString();
const e = isoish(end) ?? new Date(Date.now() + 366 * 864e5).toISOString();
const ids = this.runtime.providersOf('calendarSource');
const ids = this.hooks.providersOf('calendarSource');
const results = await Promise.all(
ids.map(async (id) => {
try {
const [rawName, rawEvents] = await Promise.all([
this.runtime.invokeHook(id, 'calendarSource', 'getName', [], userId, 3000).catch(() => id),
this.runtime.invokeHook(id, 'calendarSource', 'getEvents', [userId, s, e], userId, 5000),
this.hooks.calendarName(id, userId).catch(() => id),
this.hooks.calendarEvents(id, userId, s, e),
]);
const name = cap(rawName, 80) || id;
const events = normalizeEvents(id, name, rawEvents);
@@ -0,0 +1,149 @@
import { PluginController, PluginHook } from './host/rpc-kit/decorators';
import { PluginRuntimeService } from './plugin-runtime.service';
/** What a notification channel is handed for one message. */
export interface HookChannelMessage {
event: string;
title: string;
body: string;
url?: string;
tripName?: string;
}
/** The waypoint request a route provider is asked to solve. */
export interface HookRouteRequest {
tripId: number;
dayId: number | null;
profile: string;
waypoints: unknown[];
}
/**
* Every host-to-plugin hook call, in one place.
*
* The 15 hooks the consent screen offers used to be invoked straight from the
* controllers, with the fn name and the timeout written out at each call site. That
* made three things impossible to check: that a granted `hook:*` permission actually
* has a consumer (a dead grant on the consent screen looks exactly like a live one),
* that the fn name the host asks for matches the one the SDK documents, and that two
* call sites for the same hook agree on the budget.
*
* Each method here carries a `@PluginHook` declaration, which the registry validates
* against HOOK_PERMISSION at boot and, with requireTotalCoverage on, fails the app for
* any hook that no longer has a consumer. The declaration and the invocation are the
* same method on purpose, so the two cannot drift apart.
*
* Timeouts are the plugin's budget to answer. They are deliberately not uniform:
* a name lookup is cheap, a route solve over a full day is not, and a notification
* channel is talking to somebody else's API.
*/
@PluginController()
export class PluginHooks {
constructor(private readonly runtime: PluginRuntimeService) {}
/** The plugins that declared `hook`, in manifest order. */
providersOf(hook: string): string[] {
return this.runtime.providersOf(hook);
}
@PluginHook('photoProvider', { permission: 'hook:photo-provider', fn: 'search', timeoutMs: 5000 })
searchPhotos(pluginId: string, query: string, page: number, limit: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'photoProvider', 'search', [query, { page, limit }], userId, 5000);
}
@PluginHook('photoProvider', { permission: 'hook:photo-provider', fn: 'getById', timeoutMs: 5000 })
getPhoto(pluginId: string, photoId: string, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'photoProvider', 'getById', [photoId], userId, 5000);
}
// A display name is a one-field read, so it gets a shorter leash than the feed it
// labels; the caller falls back to the plugin id when it times out.
@PluginHook('calendarSource', { permission: 'hook:calendar-source', fn: 'getName', timeoutMs: 3000 })
calendarName(pluginId: string, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'calendarSource', 'getName', [], userId, 3000);
}
@PluginHook('calendarSource', { permission: 'hook:calendar-source', fn: 'getEvents', timeoutMs: 5000 })
calendarEvents(pluginId: string, userId: number, start: string, end: string): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'calendarSource', 'getEvents', [userId, start, end], userId, 5000);
}
@PluginHook('placeDetailProvider', { permission: 'hook:place-detail-provider', fn: 'getDetails', timeoutMs: 5000 })
placeDetails(pluginId: string, placeId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'placeDetailProvider', 'getDetails', [placeId], userId, 5000);
}
@PluginHook('warningProvider', { permission: 'hook:trip-warning-provider', fn: 'getWarnings', timeoutMs: 5000 })
tripWarnings(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'warningProvider', 'getWarnings', [tripId], userId, 5000);
}
@PluginHook('tableContributor', { permission: 'hook:table-contributor', fn: 'getContributions', timeoutMs: 5000 })
tableContributions(pluginId: string, view: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'tableContributor', 'getContributions', [view, tripId], userId, 5000);
}
@PluginHook('mapMarkerProvider', { permission: 'hook:map-marker-provider', fn: 'getMarkers', timeoutMs: 5000 })
mapMarkers(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'mapMarkerProvider', 'getMarkers', [tripId], userId, 5000);
}
@PluginHook('mapLayerProvider', { permission: 'hook:map-layer-provider', fn: 'getLayers', timeoutMs: 5000 })
mapLayers(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'mapLayerProvider', 'getLayers', [tripId], userId, 5000);
}
// A route solve runs an external routing engine over a whole day of waypoints, so it
// gets four times the budget of a plain read. The caller falls back to straight lines.
@PluginHook('routeProvider', { permission: 'hook:route-provider', fn: 'getRoute', timeoutMs: 20_000 })
route(pluginId: string, request: HookRouteRequest, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'routeProvider', 'getRoute', [request], userId, 20_000);
}
@PluginHook('dayScheduleProvider', { permission: 'hook:day-schedule-provider', fn: 'getSchedule', timeoutMs: 5000 })
daySchedule(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'dayScheduleProvider', 'getSchedule', [tripId], userId, 5000);
}
@PluginHook('dayTintProvider', { permission: 'hook:day-tint-provider', fn: 'getDayTints', timeoutMs: 5000 })
dayTints(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'dayTintProvider', 'getDayTints', [tripId], userId, 5000);
}
@PluginHook('pdfSectionProvider', { permission: 'hook:pdf-section-provider', fn: 'getSections', timeoutMs: 5000 })
pdfSections(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'pdfSectionProvider', 'getSections', [tripId], userId, 5000);
}
@PluginHook('atlasLayerProvider', { permission: 'hook:atlas-layer-provider', fn: 'getLayers', timeoutMs: 5000 })
atlasLayers(pluginId: string, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'atlasLayerProvider', 'getLayers', [], userId, 5000);
}
@PluginHook('journalEntryProvider', { permission: 'hook:journal-entry-provider', fn: 'getRows', timeoutMs: 5000 })
journalRows(pluginId: string, entryId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'journalEntryProvider', 'getRows', [entryId], userId, 5000);
}
@PluginHook('tripCardProvider', { permission: 'hook:trip-card-provider', fn: 'getCards', timeoutMs: 5000 })
tripCards(pluginId: string, tripIds: number[], userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'tripCardProvider', 'getCards', [tripIds], userId, 5000);
}
/**
* Both notification-channel calls run with NO acting user: a notification is
* host-initiated for an arbitrary recipient, so the hook gets that recipient's own
* decrypted config as an argument rather than the right to read anything as them.
* The budget is the longest of the read hooks because the channel is talking to a
* third-party API (Telegram, ntfy, a webhook) rather than to TREK.
*/
@PluginHook('notificationChannel', { permission: 'hook:notification-channel', fn: 'send', timeoutMs: 8000 })
sendNotification(pluginId: string, message: HookChannelMessage, userSettings: unknown): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'notificationChannel', 'send', [message, userSettings], undefined, 8000);
}
@PluginHook('notificationChannel', { permission: 'hook:notification-channel', fn: 'test', timeoutMs: 8000 })
testNotification(pluginId: string, userSettings: unknown): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'notificationChannel', 'test', [userSettings], undefined, 8000);
}
}
@@ -2,7 +2,7 @@ import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -57,12 +57,12 @@ function normalizePhotos(pluginId: string, raw: unknown): DevPhoto[] {
@Controller('api/plugin-photos')
@UseGuards(JwtAuthGuard)
export class PluginPhotosController {
constructor(private readonly runtime: PluginRuntimeService) {}
constructor(private readonly hooks: PluginHooks) {}
@Get('sources')
sources(): { sources: Array<{ pluginId: string }> } {
if (!pluginsEnabled()) return { sources: [] };
return { sources: this.runtime.providersOf('photoProvider').map((pluginId) => ({ pluginId })) };
return { sources: this.hooks.providersOf('photoProvider').map((pluginId) => ({ pluginId })) };
}
@Get('search')
@@ -77,11 +77,11 @@ export class PluginPhotosController {
const query = cap(q, 200);
const page = Math.max(1, Math.min(1000, Number(pageRaw) || 1));
const ids = this.runtime.providersOf('photoProvider');
const ids = this.hooks.providersOf('photoProvider');
const results = await Promise.all(
ids.map(async (id) => {
try {
const raw = (await this.runtime.invokeHook(id, 'photoProvider', 'search', [query, { page, limit: MAX_PHOTOS }], userId, 5000)) as
const raw = (await this.hooks.searchPhotos(id, query, page, MAX_PHOTOS, userId)) as
| { photos?: unknown; total?: unknown; hasMore?: unknown }
| undefined;
const photos = normalizePhotos(id, raw?.photos);
@@ -104,9 +104,9 @@ export class PluginPhotosController {
if (!pluginsEnabled()) return { photo: null };
const userId = req.user?.id;
if (userId == null || !pluginId || !id) return { photo: null };
if (!this.runtime.providersOf('photoProvider').includes(pluginId)) return { photo: null };
if (!this.hooks.providersOf('photoProvider').includes(pluginId)) return { photo: null };
try {
const raw = await this.runtime.invokeHook(pluginId, 'photoProvider', 'getById', [cap(id, 256)], userId, 5000);
const raw = await this.hooks.getPhoto(pluginId, cap(id, 256), userId);
return { photo: normalizePhotos(pluginId, [raw])[0] ?? null };
} catch {
return { photo: null };
@@ -4,7 +4,7 @@ import type Database from 'better-sqlite3';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -150,7 +150,7 @@ function normalize(pluginId: string, profile: string, waypointCount: number, raw
@UseGuards(JwtAuthGuard)
export class PluginRoutesController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -174,18 +174,11 @@ export class PluginRoutesController {
// Provider gate (implements the hook AND holds the grant) + the profile must be
// one the manifest declared — re-validated from the DB row like the plugins feed,
// so a hand-edited capabilities blob can't invent profiles.
if (!this.runtime.providersOf('routeProvider').includes(pluginId)) return { route: null };
if (!this.hooks.providersOf('routeProvider').includes(pluginId)) return { route: null };
if (!declaredProfiles(this.dbs.connection, pluginId).includes(profileId)) return { route: null };
try {
const raw = await this.runtime.invokeHook(
pluginId,
'routeProvider',
'getRoute',
[{ tripId, dayId, profile: profileId, waypoints }],
userId,
20_000,
);
const raw = await this.hooks.route(pluginId, { tripId, dayId, profile: profileId, waypoints }, userId);
return { route: normalize(pluginId, profileId, waypoints.length, raw) };
} catch {
return { route: null }; // slow / failing provider — client falls back to straight lines
@@ -14,7 +14,7 @@ import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { PluginSupervisor, type PluginRouteInfo } from './supervisor/plugin-supervisor';
import fs from 'node:fs';
import path from 'node:path';
import { PluginHostDepsFactory } from './host/plugin-host-deps.factory';
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
import { closePluginDataDb } from './host/plugin-host-state';
import { ForbiddenResource } from './host/rpc-host';
import { removePluginData } from './host/plugin-data.service';
@@ -123,11 +123,11 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
// The rpc-host factory is bound to `this` as the inter-plugin router, so a
// plugin's ctx.plugins.call / ctx.events.emit resolve through callPlugin/
// emitPluginEvent below (which own the dependency-edge authorization). The
// arrow reads this.hostDeps lazily at spawn time, so the field-initializer
// arrow reads this.hostFactory lazily at spawn time, so the field-initializer
// ordering (it runs before the constructor params are assigned) is safe.
private readonly supervisor = new PluginSupervisor((id, granted) => {
if (!this.hostDeps) throw new Error('PluginHostDepsFactory not provided — tests that activate plugins must pass one');
return this.hostDeps.create(id, granted, this);
if (!this.hostFactory) throw new Error('PluginRpcHostFactory not provided — tests that activate plugins must pass one');
return this.hostFactory.create(id, granted, this);
}, {
// Both hooks run from child lifecycle EventEmitter callbacks (exit / stderr 'data'),
// so a throw here becomes an uncaughtException that has no host-side handler. During a
@@ -160,7 +160,7 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
// Coalesces overlapping erasure drains (the sweep and enqueue both trigger one).
private drainInFlight: Promise<void> | null = null;
// The registry and host-deps factory stay optional at the type level so tests
// The registry and host factory stay optional at the type level so tests
// can construct the service without them; Nest always injects the real ones
// (both providers are in the module). audit sits before the optionals
// because a required param cannot follow optional ones.
@@ -169,7 +169,7 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
private readonly audit: AuditService,
private readonly addons: AddonsService,
private readonly registry?: PluginRegistryService,
private readonly hostDeps?: PluginHostDepsFactory,
private readonly hostFactory?: PluginRpcHostFactory,
) {}
private get db() {
@@ -1048,6 +1048,9 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
// excludes them, and a manifest can only narrow that set, never widen it.
supportsEvent: (event: string) => allowed.has(event),
isConfiguredFor: (userId: number) => hasRequiredUserSettings(id, userId),
// Declared as a contract on PluginHooks.sendNotification, like every other
// hook. It is invoked here rather than through that class because PluginHooks
// injects this service, and going back the other way would close a DI cycle.
sendToUser: (userId: number, msg: ChannelMessage) =>
this.invokeHook(
id,
+14 -8
View File
@@ -25,10 +25,14 @@ import { PluginOAuthController } from './plugin-oauth.controller';
import { PluginOAuthService } from './plugin-oauth.service';
import { PluginsService } from './plugins.service';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { PluginRegistryService } from './registry/registry.service';
import { PluginHostDepsFactory } from './host/plugin-host-deps.factory';
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
import { PluginRpcRegistryService } from './host/rpc-kit/registry.service';
import { PluginGuardsModule } from './host/plugin-guards.module';
import { DbRpc } from './host/rpc/db.rpc';
import { MetaRpc } from './host/rpc/meta.rpc';
import { HostSurfaceRpc } from './host/rpc/host-surface.rpc';
import { TagsModule } from '../tags/tags.module';
import { CategoriesModule } from '../categories/categories.module';
import { BudgetModule } from '../budget/budget.module';
@@ -59,15 +63,17 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module'
* widget assets at /plugin-frame/:id/*.
*/
@Module({
// The DI-native domain services the plugin host wiring injects
// (PluginHostDepsFactory); DatabaseModule is @Global, so not listed.
// DiscoveryModule is what lets PluginRpcRegistryService find the @PluginController
// providers at boot. PluginGuardsModule is a leaf that hands the resource gates to
// the domain modules; it must not be this module, because the domains would then
// have to import PluginsModule back and close a cycle.
// The domain modules whose @PluginController providers own the plugin wire surface;
// DatabaseModule is @Global, so not listed. DiscoveryModule is what lets
// PluginRpcRegistryService find those providers at boot. PluginGuardsModule is a leaf
// that hands the resource gates to the domain modules; it must not be this module,
// because the domains would then have to import PluginsModule back and close a cycle.
imports: [DiscoveryModule, PluginGuardsModule, TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule, FilesModule, CollabModule, VacayModule, TripsModule, PermissionsModule, AuditModule, AddonsModule, PlacesModule, CollectionsModule, AtlasModule, NotificationsModule, TripMembershipModule, JourneyDomainModule],
controllers: [PluginsController, PluginsFeedController, PluginsProxyController, PluginFrameController, PlaceDetailsController, TripWarningsController, ViewContributionsController, TripCardContributionsController, PluginPhotosController, PluginCalendarController, MapMarkersController, MapLayersController, PluginRoutesController, DayScheduleController, DayTintsController, PdfSectionsController, AtlasLayersController, JournalEntryRowsController, PluginUserSettingsController, PluginOAuthController, PluginActivityController],
providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory, PluginRpcRegistryService],
// DbRpc, MetaRpc and HostSurfaceRpc are the plugin surface that belongs to no
// domain: the plugin's own sqlite, its namespaced entity metadata, and the
// host-mediated calls (user lookup, broadcasts, notifications, LLM, OAuth, scheduler).
providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginRpcHostFactory, PluginRpcRegistryService, PluginHooks, DbRpc, MetaRpc, HostSurfaceRpc],
// Exported so the admin addon-toggle handler can cascade-disable plugins whose
// required addon was just turned off (#plugins dependencies).
exports: [PluginRuntimeService],
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -83,7 +83,7 @@ function normalize(pluginId: string, raw: unknown, allowed: Set<number>): TripCa
@UseGuards(JwtAuthGuard)
export class TripCardContributionsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -107,11 +107,11 @@ export class TripCardContributionsController {
if (accessible.length === 0) return { contributions: [] };
const allowed = new Set(accessible);
const ids = this.runtime.providersOf('tripCardProvider');
const ids = this.hooks.providersOf('tripCardProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<TripCardBadge[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'tripCardProvider', 'getCards', [accessible], userId, 5000);
const raw = await this.hooks.tripCards(id, accessible, userId);
return normalize(id, raw, allowed);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -28,7 +28,7 @@ const MESSAGE_MAX = 300;
@UseGuards(JwtAuthGuard)
export class TripWarningsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -42,11 +42,11 @@ export class TripWarningsController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { warnings: [] };
const ids = this.runtime.providersOf('warningProvider');
const ids = this.hooks.providersOf('warningProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<Warning[]> => {
try {
const raw = (await this.runtime.invokeHook(id, 'warningProvider', 'getWarnings', [tripId], userId, 5000)) as unknown;
const raw = (await this.hooks.tripWarnings(id, tripId, userId)) as unknown;
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
// Drop non-object elements BEFORE the cap — otherwise one null in the array
// throws inside map() and the catch below discards ALL of this provider's
@@ -3,7 +3,7 @@ import type { Request } from 'express';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { stripEmoji } from './text-sanitize';
/**
@@ -103,7 +103,7 @@ function normalize(pluginId: string, raw: unknown): Contribution[] {
@UseGuards(JwtAuthGuard)
export class ViewContributionsController {
constructor(
private readonly runtime: PluginRuntimeService,
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@@ -118,11 +118,11 @@ export class ViewContributionsController {
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { contributions: [] };
const ids = this.runtime.providersOf('tableContributor');
const ids = this.hooks.providersOf('tableContributor');
const perProvider = await Promise.all(
ids.map(async (id): Promise<Contribution[]> => {
try {
const raw = await this.runtime.invokeHook(id, 'tableContributor', 'getContributions', [view, tripId], userId, 5000);
const raw = await this.hooks.tableContributions(id, view, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
@@ -15,7 +15,7 @@ export type { EndpointInput, ReservationEndpoint, ReservationTraveler } from './
* MCP tools and resource moved to the DI-discovered reservations.mcp.ts, the
* transit tools to the DI-discovered transit.mcp.ts (which injects
* ReservationsService), and the plugin RPC host injects ReservationsService
* via PluginHostDepsFactory). Exports only the legacy services/reservationService
* via ReservationsRpc). Exports only the legacy services/reservationService
* names still consumed outside the container, 1:1, so repointing a consumer is
* an import-path-only diff. Inside the container, inject ReservationsService
* instead. Delete exports here as their consumers migrate.
@@ -25,7 +25,7 @@ import { AuthModule } from '../auth/auth.module';
imports: [DaysModule, PermissionsModule, BudgetModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [ReservationsController, AccommodationsController, UpcomingReservationsController],
providers: [ReservationsService, AccommodationsService, ReservationsMcp, ReservationsRpc],
// For in-container consumers (PluginHostDepsFactory, TripsService, BookingImportService).
// For in-container consumers (ReservationsRpc, TripsService, BookingImportService).
exports: [ReservationsService],
})
export class ReservationsModule {}
@@ -125,7 +125,7 @@ type AccommodationTimesMeta = {
* Non-Nest consumers (legacy tripService, airtrail import/sync, the transit +
* transports MCP registrars) go through reservations.bridge.ts instead of
* importing this class directly; the plugin RPC host injects it via
* PluginHostDepsFactory.
* ReservationsRpc.
*/
@Injectable()
export class ReservationsService {
+1 -1
View File
@@ -13,7 +13,7 @@ import { AuthModule } from '../auth/auth.module';
// PROVIDERS only, and a missing entry here would leave tags.* answering
// PERMISSION_DENIED with no other symptom.
providers: [TagsService, TagsMcp, TagsRpc],
// For in-container consumers (PluginHostDepsFactory).
// For in-container consumers (TagsRpc).
exports: [TagsService],
})
export class TagsModule {}
+1 -1
View File
@@ -6,7 +6,7 @@ import { DatabaseService } from '../database/database.service';
* Tags domain service — owns the tag SQL (moved 1:1 from the legacy
* services/tagService.ts: identical statements, the #10b981 default and the
* COALESCE update semantics). All consumers are in-container now — the plugin
* RPC host injects this class via PluginHostDepsFactory.
* RPC surface injects this class into TagsRpc.
*/
@Injectable()
export class TagsService {
+1 -1
View File
@@ -8,7 +8,7 @@ import { AuthModule } from '../auth/auth.module';
/**
* Vacay addon domain (S1 — Phase 2 trip sub-domain). Registered in AppModule.
* VacayService is exported for the plugin host wiring (PluginHostDepsFactory);
* VacayService is exported for the plugin host surface (VacayRpc);
* VacayMcp carries the DI-discovered MCP tools/resources.
*/
@Module({