mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
style: format server and shared with prettier
A mechanical prettier --write over server/src, server/tests, server/scripts and shared/src with the workspaces' .prettierrc; nothing but layout and import order changes, and every file keeps the same set of imports. shared is formatted throughout and its format baseline is empty. The server baseline keeps the 35 files that Prettier would grow past their lint:size limit (they need a split first, which is not a formatting change), and the generated entity files stay as their generator writes them.
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/atlas-layers — country tint layers plugins draw over the Atlas world
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Days } from '../../../db/entities/Days.entity';
|
||||
import type { DaysRepository } from '../../../db/repositories/Days.repository';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/day-schedule/:tripId — bounded time contributions plugins attach to the
|
||||
@@ -61,7 +62,8 @@ function normalize(pluginId: string, tripDayIds: ReadonlySet<number>, raw: unkno
|
||||
const assignmentId = Number.isInteger(it.assignmentId) ? (it.assignmentId as number) : undefined;
|
||||
const reservationId = Number.isInteger(it.reservationId) ? (it.reservationId as number) : undefined;
|
||||
const minutesRaw = Number(it.minutes);
|
||||
const minutes = Number.isFinite(minutesRaw) && minutesRaw > 0 ? Math.min(Math.round(minutesRaw), MAX_MINUTES) : undefined;
|
||||
const minutes =
|
||||
Number.isFinite(minutesRaw) && minutesRaw > 0 ? Math.min(Math.round(minutesRaw), MAX_MINUTES) : undefined;
|
||||
out.push({
|
||||
pluginId,
|
||||
id,
|
||||
@@ -96,7 +98,8 @@ export class DayScheduleController {
|
||||
if (!pluginsEnabled()) return { items: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { items: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { items: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('dayScheduleProvider');
|
||||
if (ids.length === 0) return { items: [] };
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Days } from '../../../db/entities/Days.entity';
|
||||
import type { DaysRepository } from '../../../db/repositories/Days.repository';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/day-tints/:tripId — the colours the planner paints into a day card in the
|
||||
@@ -68,8 +69,7 @@ const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice
|
||||
* beacon for the plugin's own server. Nothing but `#rrggbb` gets through.
|
||||
*/
|
||||
const HEX = /^#[0-9a-fA-F]{6}$/;
|
||||
const hex = (v: unknown): string | undefined =>
|
||||
typeof v === 'string' && HEX.test(v) ? v.toLowerCase() : undefined;
|
||||
const hex = (v: unknown): string | undefined => (typeof v === 'string' && HEX.test(v) ? v.toLowerCase() : undefined);
|
||||
|
||||
// Bound the work, not just the output: an all-invalid raw array (no entry ever
|
||||
// reaching `out`) would otherwise be iterated in full. Slice up front, well above
|
||||
@@ -84,12 +84,15 @@ const MAX_RAW_TINTS = 2000;
|
||||
* hooks use for `tone`.
|
||||
*/
|
||||
const region = (v: unknown): Tone | undefined =>
|
||||
v === undefined || v === null ? undefined : (TONES.has(v as string) ? (v as Tone) : 'default');
|
||||
v === undefined || v === null ? undefined : TONES.has(v as string) ? (v as Tone) : 'default';
|
||||
|
||||
const named = (v: unknown): boolean => v !== undefined && v !== null;
|
||||
|
||||
/** One region of the card, resolved whole — a colour, a tone, or nothing. */
|
||||
interface RegionTint { tone?: Tone; color?: string }
|
||||
interface RegionTint {
|
||||
tone?: Tone;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one region against the contribution's `tone` / `color` shorthands, in one
|
||||
@@ -173,7 +176,8 @@ export class DayTintsController {
|
||||
if (!pluginsEnabled()) return { tints: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { tints: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { tints: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('dayTintProvider');
|
||||
if (ids.length === 0) return { tints: [] };
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { JourneyDomainService } from '../../journey/journey-domain.service';
|
||||
import { ADDON_IDS } from '../../../addons';
|
||||
import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
|
||||
import type { JourneyEntriesRepository } from '../../../db/repositories/JourneyEntries.repository';
|
||||
import { AddonsService } from '../../addons/addons.service';
|
||||
import { ADDON_IDS } from '../../../addons';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { JourneyDomainService } from '../../journey/journey-domain.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/journal-entry-rows/:entryId — extra rows for a journal entry,
|
||||
@@ -45,7 +46,9 @@ function safeUrl(raw: unknown): string | undefined {
|
||||
if (typeof raw !== 'string' || raw === '') return undefined;
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:' ? raw.slice(0, 2048) : undefined;
|
||||
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:'
|
||||
? raw.slice(0, 2048)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/map-layers/:tripId — bounded vector overlays plugins draw on the trip map
|
||||
@@ -99,7 +100,9 @@ function normalize(pluginId: string, raw: unknown): MapLayer[] {
|
||||
const id = cap(l.id, 64);
|
||||
if (!id) continue;
|
||||
const feats: MapLayerFeature[] = [];
|
||||
const rawFeats = Array.isArray(l.features) ? (l.features as Array<Record<string, unknown>>).slice(0, MAX_RAW_FEATURES) : [];
|
||||
const rawFeats = Array.isArray(l.features)
|
||||
? (l.features as Array<Record<string, unknown>>).slice(0, MAX_RAW_FEATURES)
|
||||
: [];
|
||||
for (const f of rawFeats) {
|
||||
if (features >= MAX_FEATURES || points >= MAX_POINTS) break;
|
||||
if (!f || typeof f !== 'object') continue;
|
||||
@@ -158,7 +161,8 @@ export class MapLayersController {
|
||||
if (!pluginsEnabled()) return { layers: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { layers: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { layers: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('mapLayerProvider');
|
||||
const perProvider = await Promise.all(
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/map-markers/:tripId — bounded markers plugins overlay on the trip map
|
||||
@@ -40,7 +41,9 @@ function safeUrl(raw: unknown): string | undefined {
|
||||
if (typeof raw !== 'string' || raw === '') return undefined;
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:' ? raw.slice(0, 2048) : undefined;
|
||||
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:'
|
||||
? raw.slice(0, 2048)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -56,7 +59,8 @@ function normalize(pluginId: string, raw: unknown): MapMarker[] {
|
||||
const lng = Number(m.lng);
|
||||
const id = cap(m.id, 64);
|
||||
// A marker with no id or out-of-range coordinates is meaningless — drop it.
|
||||
if (!id || !Number.isFinite(lat) || !Number.isFinite(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180) continue;
|
||||
if (!id || !Number.isFinite(lat) || !Number.isFinite(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180)
|
||||
continue;
|
||||
out.push({
|
||||
pluginId,
|
||||
id,
|
||||
@@ -91,7 +95,8 @@ export class MapMarkersController {
|
||||
if (!pluginsEnabled()) return { markers: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { markers: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { markers: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('mapMarkerProvider');
|
||||
const perProvider = await Promise.all(
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/pdf-sections/:tripId — text-only sections plugins append to a trip's
|
||||
@@ -64,7 +65,9 @@ function normalize(pluginId: string, raw: unknown): PdfSection[] {
|
||||
out.push({
|
||||
pluginId,
|
||||
title,
|
||||
paragraphs: (Array.isArray(s.paragraphs) ? s.paragraphs : []).slice(0, MAX_PARAGRAPHS).map((p) => cap(p, PARAGRAPH_MAX)),
|
||||
paragraphs: (Array.isArray(s.paragraphs) ? s.paragraphs : [])
|
||||
.slice(0, MAX_PARAGRAPHS)
|
||||
.map((p) => cap(p, PARAGRAPH_MAX)),
|
||||
table: normalizeTable(s.table),
|
||||
});
|
||||
}
|
||||
@@ -87,7 +90,8 @@ export class PdfSectionsController {
|
||||
if (!pluginsEnabled()) return { sections: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { sections: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { sections: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('pdfSectionProvider');
|
||||
const perProvider = await Promise.all(
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Places } from '../../../db/entities/Places.entity';
|
||||
import type { PlacesRepository } from '../../../db/repositories/Places.repository';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/place-details/:placeId — extra info for a place, contributed by plugins
|
||||
@@ -38,7 +39,9 @@ function safeUrl(raw: unknown): string | undefined {
|
||||
if (typeof raw !== 'string' || raw === '') return undefined;
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:' ? raw.slice(0, 2048) : undefined;
|
||||
return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:'
|
||||
? raw.slice(0, 2048)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Calendar events contributed by plugins that implement the `calendarSource` hook
|
||||
@@ -14,11 +15,20 @@ import { stripEmoji } from '../text-sanitize';
|
||||
* short timeout, one that errors/times out is skipped. Every field is NORMALIZED —
|
||||
* strings length-capped, dates kept as ISO strings, the event count capped per source.
|
||||
*/
|
||||
interface DevEvent { id: string; pluginId: string; source: string; title: string; start: string; end: string; allDay: boolean; }
|
||||
interface DevEvent {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
source: string;
|
||||
title: string;
|
||||
start: string;
|
||||
end: string;
|
||||
allDay: boolean;
|
||||
}
|
||||
|
||||
const MAX_EVENTS = 500; // per source per request
|
||||
const MAX_EVENTS = 500; // per source per request
|
||||
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
|
||||
const isoish = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 && v.length <= 40 ? v : undefined);
|
||||
const isoish = (v: unknown): string | undefined =>
|
||||
typeof v === 'string' && v.length > 0 && v.length <= 40 ? v : undefined;
|
||||
|
||||
function normalizeEvents(pluginId: string, source: string, raw: unknown): DevEvent[] {
|
||||
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { PluginsRuntimeModule } from '../plugins-runtime.module';
|
||||
import { AddonsModule } from '../../addons/addons.module';
|
||||
import { JourneyDomainModule } from '../../journey/journey-domain.module';
|
||||
import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import { Days } from '../../../db/entities/Days.entity';
|
||||
import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
|
||||
import { Places } from '../../../db/entities/Places.entity';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import { Trips } from '../../../db/entities/Trips.entity';
|
||||
import { AddonsModule } from '../../addons/addons.module';
|
||||
import { DemoModule } from '../../common/demo.module';
|
||||
import { JourneyDomainModule } from '../../journey/journey-domain.module';
|
||||
import { TripMembershipModule } from '../../trip-membership/trip-membership.module';
|
||||
import { PluginsRuntimeModule } from '../plugins-runtime.module';
|
||||
import { AtlasLayersController } from './atlas-layers.controller';
|
||||
import { DayScheduleController } from './day-schedule.controller';
|
||||
import { DayTintsController } from './day-tints.controller';
|
||||
import { JournalEntryRowsController } from './journal-entry-rows.controller';
|
||||
import { MapLayersController } from './map-layers.controller';
|
||||
import { MapMarkersController } from './map-markers.controller';
|
||||
import { PdfSectionsController } from './pdf-sections.controller';
|
||||
import { PlaceDetailsController } from './place-details.controller';
|
||||
import { PluginSearchController } from './plugin-search.controller';
|
||||
import { TripWarningsController } from './trip-warnings.controller';
|
||||
import { TripWarningsMcp } from './trip-warnings.mcp';
|
||||
import { PluginSearchMcp } from './plugin-search.mcp';
|
||||
import { PluginCalendarController } from './plugin-calendar.controller';
|
||||
import { PluginMcpToolsService } from './plugin-mcp-tools.service';
|
||||
import { PluginPhotosController } from './plugin-photos.controller';
|
||||
import { PluginPoisController } from './plugin-pois.controller';
|
||||
import { PluginPoisMcp } from './plugin-pois.mcp';
|
||||
import { PluginPoisService } from './plugin-pois.service';
|
||||
import { PluginMcpToolsService } from './plugin-mcp-tools.service';
|
||||
import { ViewContributionsController } from './view-contributions.controller';
|
||||
import { TripCardContributionsController } from './trip-card-contributions.controller';
|
||||
import { PluginPhotosController } from './plugin-photos.controller';
|
||||
import { PluginCalendarController } from './plugin-calendar.controller';
|
||||
import { MapMarkersController } from './map-markers.controller';
|
||||
import { MapLayersController } from './map-layers.controller';
|
||||
import { PluginRoutesController } from './plugin-routes.controller';
|
||||
import { DayScheduleController } from './day-schedule.controller';
|
||||
import { DayTintsController } from './day-tints.controller';
|
||||
import { PdfSectionsController } from './pdf-sections.controller';
|
||||
import { AtlasLayersController } from './atlas-layers.controller';
|
||||
import { JournalEntryRowsController } from './journal-entry-rows.controller';
|
||||
import { DemoModule } from '../../common/demo.module';
|
||||
import { TripMembershipModule } from '../../trip-membership/trip-membership.module';
|
||||
import { PluginSearchController } from './plugin-search.controller';
|
||||
import { PluginSearchMcp } from './plugin-search.mcp';
|
||||
import { TripCardContributionsController } from './trip-card-contributions.controller';
|
||||
import { TripWarningsController } from './trip-warnings.controller';
|
||||
import { TripWarningsMcp } from './trip-warnings.mcp';
|
||||
import { ViewContributionsController } from './view-contributions.controller';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* The read-only surface plugins contribute to the app: photos, calendar events,
|
||||
@@ -64,7 +64,14 @@ import { TripMembershipModule } from '../../trip-membership/trip-membership.modu
|
||||
* dependency unresolved.
|
||||
*/
|
||||
@Module({
|
||||
imports: [TripMembershipModule, PluginsRuntimeModule, AddonsModule, JourneyDomainModule, DemoModule, MikroOrmModule.forFeature([JourneyEntries, Plugins, Days, Places, Trips])],
|
||||
imports: [
|
||||
TripMembershipModule,
|
||||
PluginsRuntimeModule,
|
||||
AddonsModule,
|
||||
JourneyDomainModule,
|
||||
DemoModule,
|
||||
MikroOrmModule.forFeature([JourneyEntries, Plugins, Days, Places, Trips]),
|
||||
],
|
||||
controllers: [
|
||||
PlaceDetailsController,
|
||||
PluginSearchController,
|
||||
|
||||
@@ -10,13 +10,11 @@
|
||||
* reads only state already in memory or in SQLite. Nothing here waits on a
|
||||
* child process.
|
||||
*/
|
||||
import { Injectable, type OnApplicationBootstrap, type OnModuleDestroy } from '@nestjs/common';
|
||||
|
||||
import { demoDenied, errorResult, type McpContext, type McpDynamicTool, type McpTextResult } from '../../../nest-mcp';
|
||||
import { setPluginMcpToolSource } from '../../../plugin-mcp-tools';
|
||||
import { RuntimeEnvService } from '../../app-config/runtime-env.service';
|
||||
import { DemoService } from '../../common/demo.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { PluginRuntimeService } from '../plugin-runtime.service';
|
||||
import {
|
||||
MCP_TOOLS_MAX,
|
||||
MCP_TOOLS_TOTAL_MAX,
|
||||
@@ -24,10 +22,10 @@ import {
|
||||
clampToolAnnotations,
|
||||
mcpToolName,
|
||||
} from '../mcp-tool-schema';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { PluginRuntimeService } from '../plugin-runtime.service';
|
||||
import { sanitiseAssistantText } from '../text-sanitize';
|
||||
import { setPluginMcpToolSource } from '../../../plugin-mcp-tools';
|
||||
|
||||
import { demoDenied, errorResult, type McpContext, type McpDynamicTool, type McpTextResult } from '../../../nest-mcp';
|
||||
import { Injectable, type OnApplicationBootstrap, type OnModuleDestroy } from '@nestjs/common';
|
||||
|
||||
/** The hook a plugin implements to publish tools. */
|
||||
const HOOK = 'mcpToolProvider';
|
||||
@@ -167,18 +165,16 @@ export class PluginMcpToolsService implements OnApplicationBootstrap, OnModuleDe
|
||||
// A failed or timed-out invoke is a TOOL error, not a protocol one: the
|
||||
// model has to see it and be able to try something else.
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
return errorResult(`Plugin "${pluginId}" could not run "${name}": ${sanitiseAssistantText(message, RESULT_ERROR_MAX)}`);
|
||||
return errorResult(
|
||||
`Plugin "${pluginId}" could not run "${name}": ${sanitiseAssistantText(message, RESULT_ERROR_MAX)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** True for a value already shaped like an MCP result the SDK would accept. */
|
||||
function isTextResult(v: unknown): v is McpTextResult {
|
||||
return (
|
||||
typeof v === 'object' &&
|
||||
v !== null &&
|
||||
Array.isArray((v as { content?: unknown }).content)
|
||||
);
|
||||
return typeof v === 'object' && v !== null && Array.isArray((v as { content?: unknown }).content);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -272,21 +268,25 @@ export function toMcpTextResult(raw: unknown): McpTextResult {
|
||||
function serialiseBounded(value: unknown): { text: string; cut: boolean } {
|
||||
let budget = RESULT_MAX;
|
||||
let cut = false;
|
||||
const text = JSON.stringify(value, (_key, v: unknown) => {
|
||||
if (budget <= 0) {
|
||||
cut = true;
|
||||
return undefined;
|
||||
}
|
||||
if (typeof v === 'string') {
|
||||
budget -= v.length;
|
||||
const text = JSON.stringify(
|
||||
value,
|
||||
(_key, v: unknown) => {
|
||||
if (budget <= 0) {
|
||||
cut = true;
|
||||
return v.slice(0, Math.max(0, v.length + budget));
|
||||
return undefined;
|
||||
}
|
||||
if (typeof v === 'string') {
|
||||
budget -= v.length;
|
||||
if (budget <= 0) {
|
||||
cut = true;
|
||||
return v.slice(0, Math.max(0, v.length + budget));
|
||||
}
|
||||
return v;
|
||||
}
|
||||
budget -= 8; // rough cost of a number, boolean, or structural token
|
||||
return v;
|
||||
}
|
||||
budget -= 8; // rough cost of a number, boolean, or structural token
|
||||
return v;
|
||||
}, 2);
|
||||
},
|
||||
2,
|
||||
);
|
||||
return { text: text ?? '', cut };
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Photo sources contributed by plugins that implement the `photoProvider` hook
|
||||
@@ -16,9 +17,16 @@ import { stripEmoji } from '../text-sanitize';
|
||||
* skipped. Every field is NORMALIZED: strings length-capped, the photo count capped,
|
||||
* and thumbnail/full URLs must be http/https (an image src) — never javascript:/data:.
|
||||
*/
|
||||
interface DevPhoto { id: string; pluginId: string; title?: string; thumbnailUrl: string; fullUrl: string; takenAt?: string; }
|
||||
interface DevPhoto {
|
||||
id: string;
|
||||
pluginId: string;
|
||||
title?: string;
|
||||
thumbnailUrl: string;
|
||||
fullUrl: string;
|
||||
takenAt?: string;
|
||||
}
|
||||
|
||||
const MAX_PHOTOS = 60; // per provider per page
|
||||
const MAX_PHOTOS = 60; // per provider per page
|
||||
const cap = (v: unknown, n: number): string => String(v ?? '').slice(0, n);
|
||||
|
||||
/** http/https only — these become <img src>, so a javascript:/data: URL is XSS. */
|
||||
@@ -43,7 +51,8 @@ function normalizePhotos(pluginId: string, raw: unknown): DevPhoto[] {
|
||||
const full = imageUrl(p.fullUrl);
|
||||
if (!id || !thumb || !full) continue; // an unusable photo (no id / bad urls) is dropped
|
||||
out.push({
|
||||
id, pluginId,
|
||||
id,
|
||||
pluginId,
|
||||
// Strip emojis from the display title (but NOT the id — that round-trips to getById).
|
||||
title: p.title != null ? stripEmoji(cap(p.title, 200)) : undefined,
|
||||
thumbnailUrl: thumb,
|
||||
@@ -82,8 +91,7 @@ export class PluginPhotosController {
|
||||
ids.map(async (id) => {
|
||||
try {
|
||||
const raw = (await this.hooks.searchPhotos(id, query, page, MAX_PHOTOS, userId)) as
|
||||
| { photos?: unknown; total?: unknown; hasMore?: unknown }
|
||||
| undefined;
|
||||
{ photos?: unknown; total?: unknown; hasMore?: unknown } | undefined;
|
||||
const photos = normalizePhotos(id, raw?.photos);
|
||||
if (photos.length === 0) return null;
|
||||
return { pluginId: id, photos, total: Number(raw?.total) || photos.length, hasMore: raw?.hasMore === true };
|
||||
@@ -92,7 +100,11 @@ export class PluginPhotosController {
|
||||
}
|
||||
}),
|
||||
);
|
||||
return { providers: results.filter((r): r is { pluginId: string; photos: DevPhoto[]; total: number; hasMore: boolean } => r !== null) };
|
||||
return {
|
||||
providers: results.filter(
|
||||
(r): r is { pluginId: string; photos: DevPhoto[]; total: number; hasMore: boolean } => r !== null,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('item')
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Controller, Get, HttpException, Query, UseGuards } from '@nestjs/common';
|
||||
import { pluginPoiQuerySchema, type PluginPoiQuery, type PluginPoiResponse } from '@trek/shared';
|
||||
import type { User } from '../../../types';
|
||||
import { CurrentUser } from '../../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { PluginPoisService, UNKNOWN_POI_CATEGORY } from './plugin-pois.service';
|
||||
import { Controller, Get, HttpException, Query, UseGuards } from '@nestjs/common';
|
||||
import { pluginPoiQuerySchema, type PluginPoiQuery, type PluginPoiResponse } from '@trek/shared';
|
||||
|
||||
const BBOX_FIELDS: ReadonlySet<string> = new Set(['south', 'west', 'north', 'east', 'bbox']);
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { clampPoiBbox, type PoiBbox } from '../../maps/maps.helpers';
|
||||
import { sanitiseAssistantText } from '../text-sanitize';
|
||||
import { normalizeSearchHit } from './plugin-search.helpers';
|
||||
import {
|
||||
PLUGIN_POI_DETAIL_LABEL_MAX,
|
||||
PLUGIN_POI_DETAIL_VALUE_MAX,
|
||||
@@ -8,9 +11,6 @@ import {
|
||||
type PluginPoiCategory,
|
||||
type PluginPoiDetail,
|
||||
} from '@trek/shared';
|
||||
import { clampPoiBbox, type PoiBbox } from '../../maps/maps.helpers';
|
||||
import { sanitiseAssistantText } from '../text-sanitize';
|
||||
import { normalizeSearchHit } from './plugin-search.helpers';
|
||||
|
||||
/**
|
||||
* Turning what a `poiCategoryProvider` answers into explore-pill POIs (#1781).
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { PLUGIN_POI_CATEGORY_ID_RE, PLUGIN_POI_PLUGIN_ID_RE, isOrderedPoiBbox } from '@trek/shared';
|
||||
import { z } from 'zod';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../../nest-mcp';
|
||||
import { POI_BBOX_TOOL_INPUT } from '../../maps/maps.helpers';
|
||||
import { PluginPoisService } from './plugin-pois.service';
|
||||
import { PLUGIN_POI_CATEGORY_ID_RE, PLUGIN_POI_PLUGIN_ID_RE, isOrderedPoiBbox } from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* The MCP half of the plugin POI categories (#1781): the chips a plugin adds to the
|
||||
@@ -20,9 +21,14 @@ export class PluginPoisMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'list_plugin_poi_categories',
|
||||
description: 'List the extra place categories installed plugins add to the trip map\'s "Explore places" bar, such as hiking trailheads, EV chargers, wheelchair-accessible places, public toilets and drinking water, or campsites. Each entry names the plugin (`pluginId`) and its own category id (`id`), which is what search_plugin_pois takes. Returns an empty list when no plugin adds categories, which is the normal case; the built-in categories are the ones search_pois covers.',
|
||||
description:
|
||||
'List the extra place categories installed plugins add to the trip map\'s "Explore places" bar, such as hiking trailheads, EV chargers, wheelchair-accessible places, public toilets and drinking water, or campsites. Each entry names the plugin (`pluginId`) and its own category id (`id`), which is what search_plugin_pois takes. Returns an empty list when no plugin adds categories, which is the normal case; the built-in categories are the ones search_pois covers.',
|
||||
inputSchema: {
|
||||
lang: z.string().max(35).optional().describe('Language for the category labels, e.g. "de". Falls back to the plugin\'s default label'),
|
||||
lang: z
|
||||
.string()
|
||||
.max(35)
|
||||
.optional()
|
||||
.describe('Language for the category labels, e.g. "de". Falls back to the plugin\'s default label'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'geo', mode: 'read' },
|
||||
@@ -33,18 +39,34 @@ export class PluginPoisMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'search_plugin_pois',
|
||||
description: 'List the places of one plugin-provided category (from list_plugin_poi_categories) inside a map rectangle, as the plugin answers them. Results have the shape search_pois returns, plus the `pluginId` that answered, a `rating` where the plugin has one, and `details`: up to six label and value rows only that plugin knows, such as a trail length or a step-free entrance. Use search_pois for the built-in categories. Never calls Google.',
|
||||
description:
|
||||
'List the places of one plugin-provided category (from list_plugin_poi_categories) inside a map rectangle, as the plugin answers them. Results have the shape search_pois returns, plus the `pluginId` that answered, a `rating` where the plugin has one, and `details`: up to six label and value rows only that plugin knows, such as a trail length or a step-free entrance. Use search_pois for the built-in categories. Never calls Google.',
|
||||
inputSchema: {
|
||||
pluginId: z.string().regex(PLUGIN_POI_PLUGIN_ID_RE).describe('The plugin that declared the category, from list_plugin_poi_categories'),
|
||||
category: z.string().regex(PLUGIN_POI_CATEGORY_ID_RE).describe('The plugin\'s own category id, from list_plugin_poi_categories'),
|
||||
pluginId: z
|
||||
.string()
|
||||
.regex(PLUGIN_POI_PLUGIN_ID_RE)
|
||||
.describe('The plugin that declared the category, from list_plugin_poi_categories'),
|
||||
category: z
|
||||
.string()
|
||||
.regex(PLUGIN_POI_CATEGORY_ID_RE)
|
||||
.describe("The plugin's own category id, from list_plugin_poi_categories"),
|
||||
bbox: POI_BBOX_TOOL_INPUT,
|
||||
lang: z.string().max(35).optional().describe('Language for the place names, e.g. "de", for plugins that carry localized names'),
|
||||
lang: z
|
||||
.string()
|
||||
.max(35)
|
||||
.optional()
|
||||
.describe('Language for the place names, e.g. "de", for plugins that carry localized names'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'geo', mode: 'read' },
|
||||
})
|
||||
async search(
|
||||
{ pluginId, category, bbox, lang }: {
|
||||
{
|
||||
pluginId,
|
||||
category,
|
||||
bbox,
|
||||
lang,
|
||||
}: {
|
||||
pluginId: string;
|
||||
category: string;
|
||||
bbox: { south: number; west: number; north: number; east: number };
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import {
|
||||
PLUGIN_POI_HIT_CAP,
|
||||
pluginPoiCategoryKey,
|
||||
pluginPoiCategoryLabel,
|
||||
type PluginPoiCategory,
|
||||
type PluginPoiResponse,
|
||||
} from '@trek/shared';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
@@ -14,6 +5,15 @@ import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { poiCategoriesOf } from '../poi-categories';
|
||||
import { sanitiseAssistantText } from '../text-sanitize';
|
||||
import { normalizePluginPois, pluginPoiWindow } from './plugin-pois.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PLUGIN_POI_HIT_CAP,
|
||||
pluginPoiCategoryKey,
|
||||
pluginPoiCategoryLabel,
|
||||
type PluginPoiCategory,
|
||||
type PluginPoiResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** One search for a plugin POI category, as both the REST route and the MCP tool ask it. */
|
||||
export interface PluginPoiSearch {
|
||||
@@ -38,8 +38,7 @@ export interface AvailablePoiCategory {
|
||||
}
|
||||
|
||||
export type PluginPoiOutcome =
|
||||
| { ok: true; result: PluginPoiResponse }
|
||||
| { ok: false; status: 404 | 502; error: string };
|
||||
{ ok: true; result: PluginPoiResponse } | { ok: false; status: 404 | 502; error: string };
|
||||
|
||||
export const UNKNOWN_POI_CATEGORY = 'Unknown POI category';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
|
||||
type Tone = 'default' | 'success' | 'warn' | 'danger';
|
||||
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { Body, Controller, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { PluginRouteDto } from '../plugins.dto';
|
||||
import { normalize, declaredProfiles, readWaypoints, PROFILE_RE, type PluginRouteOut } from './plugin-route-normalize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Body, Controller, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
export type { PluginRouteOut } from './plugin-route-normalize';
|
||||
|
||||
/**
|
||||
@@ -49,7 +51,8 @@ export class PluginRoutesController {
|
||||
if (!pluginsEnabled()) return { route: null };
|
||||
const userId = req.user?.id;
|
||||
const tripId = Number(body?.tripId);
|
||||
if (userId == null || !Number.isFinite(tripId) || !(await this.trips.findAccessible(tripId, userId))) return { route: null };
|
||||
if (userId == null || !Number.isFinite(tripId) || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { route: null };
|
||||
if (!PROFILE_RE.test(profileId)) return { route: null };
|
||||
const waypoints = readWaypoints(body?.waypoints);
|
||||
if (!waypoints) return { route: null };
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { PLUGIN_SEARCH_SUGGEST_MAX } from '@trek/shared';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import {
|
||||
collectHits,
|
||||
interleave,
|
||||
limitFrom,
|
||||
searchRequestFrom,
|
||||
type SearchHit,
|
||||
} from './plugin-search.helpers';
|
||||
import { collectHits, interleave, limitFrom, searchRequestFrom, type SearchHit } from './plugin-search.helpers';
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import { PLUGIN_SEARCH_SUGGEST_MAX } from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/plugin-search — places found by plugins implementing `searchProvider` (#2221).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { normalizePlaceWebsite } from '@trek/shared';
|
||||
import type { HookSearchRequest } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { normalizePlaceWebsite } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Turning what a `searchProvider` plugin answers into rows TREK can show (#2221).
|
||||
@@ -151,7 +151,9 @@ export function searchRequestFrom(
|
||||
limit: number,
|
||||
minLength = 1,
|
||||
): HookSearchRequest | null {
|
||||
const query = String(q ?? '').trim().slice(0, MAX_QUERY);
|
||||
const query = String(q ?? '')
|
||||
.trim()
|
||||
.slice(0, MAX_QUERY);
|
||||
if (query.length < minLength) return null;
|
||||
return { query, limit, lang: lang ? String(lang).slice(0, 20) : undefined, near: nearFrom(lat, lng) };
|
||||
}
|
||||
@@ -170,7 +172,7 @@ export function limitFrom(raw: unknown): number {
|
||||
export function interleave(results: SearchHit[][]): SearchHit[] {
|
||||
const out: SearchHit[] = [];
|
||||
for (let i = 0; ; i += 1) {
|
||||
const row = results.filter(r => r.length > i);
|
||||
const row = results.filter((r) => r.length > i);
|
||||
if (row.length === 0) return out;
|
||||
for (const r of row) out.push(r[i]);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { z } from 'zod';
|
||||
import { idSchema } from '@trek/shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext, type McpTextResult } from '../../../nest-mcp';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
ok,
|
||||
type McpContext,
|
||||
type McpTextResult,
|
||||
} from '../../../nest-mcp';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import {
|
||||
collectHits,
|
||||
interleave,
|
||||
limitFrom,
|
||||
MAX_QUERY,
|
||||
nearFrom,
|
||||
} from './plugin-search.helpers';
|
||||
import { collectHits, interleave, limitFrom, MAX_QUERY, nearFrom } from './plugin-search.helpers';
|
||||
import { idSchema } from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* The MCP half of GET /api/plugin-search (#2221).
|
||||
@@ -32,12 +34,16 @@ export class PluginSearchMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'search_places_via_plugins',
|
||||
description: 'Search for a place in the search indexes installed plugins provide, which are the ones TREK does not ship itself. Use it alongside search_place, never instead of it: search_place is TREK\'s own index and OpenStreetMap, this is whatever else the instance owner installed, and only these results can carry a rating — open data has none, so a question like "the best rated hotel near here" can only be answered from this list. Results have the same shape search_place returns, plus a `rating` and the `pluginId` that found them. Returns an empty list when no plugin provides a search index, which is the normal case.',
|
||||
description:
|
||||
'Search for a place in the search indexes installed plugins provide, which are the ones TREK does not ship itself. Use it alongside search_place, never instead of it: search_place is TREK\'s own index and OpenStreetMap, this is whatever else the instance owner installed, and only these results can carry a rating — open data has none, so a question like "the best rated hotel near here" can only be answered from this list. Results have the same shape search_place returns, plus a `rating` and the `pluginId` that found them. Returns an empty list when no plugin provides a search index, which is the normal case.',
|
||||
inputSchema: {
|
||||
query: z.string().min(1).max(MAX_QUERY).describe('Place name or address to search for'),
|
||||
near: z.strictObject({ lat: z.number(), lng: z.number() })
|
||||
near: z
|
||||
.strictObject({ lat: z.number(), lng: z.number() })
|
||||
.optional()
|
||||
.describe('Centre the search on a coordinate. Pass it whenever the trip has a destination: a bare name like "Central Station" otherwise resolves wherever the provider guesses'),
|
||||
.describe(
|
||||
'Centre the search on a coordinate. Pass it whenever the trip has a destination: a bare name like "Central Station" otherwise resolves wherever the provider guesses',
|
||||
),
|
||||
lang: z.string().max(20).optional().describe('BCP 47 language for the result names, e.g. "de" or "ja"'),
|
||||
limit: idSchema.max(20).optional().describe('How many results per provider (default 10, capped at 20)'),
|
||||
},
|
||||
@@ -45,8 +51,16 @@ export class PluginSearchMcp {
|
||||
access: { group: 'places', mode: 'read' },
|
||||
})
|
||||
async searchViaPlugins(
|
||||
{ query, near, lang, limit }: {
|
||||
query: string; near?: { lat: number; lng: number }; lang?: string; limit?: number;
|
||||
{
|
||||
query,
|
||||
near,
|
||||
lang,
|
||||
limit,
|
||||
}: {
|
||||
query: string;
|
||||
near?: { lat: number; lng: number };
|
||||
lang?: string;
|
||||
limit?: number;
|
||||
},
|
||||
ctx: McpContext,
|
||||
): Promise<McpTextResult> {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/trip-card-contributions?tripIds=1,2,3 — host-rendered badges that plugins
|
||||
@@ -22,11 +23,20 @@ import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
* contributes nothing.
|
||||
*/
|
||||
type Tone = 'default' | 'success' | 'warn' | 'danger';
|
||||
interface TripCardBadge { pluginId: string; tripId: number; id: string; label: string; value?: string; icon?: string; tone: Tone; url?: string; }
|
||||
interface TripCardBadge {
|
||||
pluginId: string;
|
||||
tripId: number;
|
||||
id: string;
|
||||
label: string;
|
||||
value?: string;
|
||||
icon?: string;
|
||||
tone: Tone;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
|
||||
const MAX_TRIP_IDS = 60; // a dashboard never shows more cards than this
|
||||
const MAX_BADGES_PER_TRIP = 4; // per provider PER card — so one badge on every card always fits
|
||||
const MAX_TRIP_IDS = 60; // a dashboard never shows more cards than this
|
||||
const MAX_BADGES_PER_TRIP = 4; // per provider PER card — so one badge on every card always fits
|
||||
const MAX_BADGES_TOTAL = MAX_TRIP_IDS * MAX_BADGES_PER_TRIP; // overall abuse bound
|
||||
const LABEL_MAX = 64;
|
||||
const VALUE_MAX = 256;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/trip-warnings/:tripId — validation/warning contributions from plugins
|
||||
@@ -40,7 +41,8 @@ export class TripWarningsController {
|
||||
if (!pluginsEnabled()) return { warnings: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { warnings: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { warnings: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('warningProvider');
|
||||
const perProvider = await Promise.all(
|
||||
@@ -51,13 +53,16 @@ export class TripWarningsController {
|
||||
// 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
|
||||
// warnings (and the cap should count only valid entries anyway).
|
||||
return list.filter((w): w is Record<string, unknown> => !!w && typeof w === 'object').slice(0, MAX_WARNINGS).map((w) => ({
|
||||
pluginId: id,
|
||||
level: w.level === 'error' || w.level === 'info' ? (w.level as Level) : 'warning',
|
||||
message: stripEmoji(String(w.message ?? '')).slice(0, MESSAGE_MAX),
|
||||
dayId: typeof w.dayId === 'number' ? w.dayId : undefined,
|
||||
placeId: typeof w.placeId === 'number' ? w.placeId : undefined,
|
||||
}));
|
||||
return list
|
||||
.filter((w): w is Record<string, unknown> => !!w && typeof w === 'object')
|
||||
.slice(0, MAX_WARNINGS)
|
||||
.map((w) => ({
|
||||
pluginId: id,
|
||||
level: w.level === 'error' || w.level === 'info' ? (w.level as Level) : 'warning',
|
||||
message: stripEmoji(String(w.message ?? '')).slice(0, MESSAGE_MAX),
|
||||
dayId: typeof w.dayId === 'number' ? w.dayId : undefined,
|
||||
placeId: typeof w.placeId === 'number' ? w.placeId : undefined,
|
||||
}));
|
||||
} catch {
|
||||
return []; // a slow / failing provider contributes nothing
|
||||
}
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { idSchema } from '@trek/shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext, type McpTextResult } from '../../../nest-mcp';
|
||||
import { noAccess } from '../../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
ok,
|
||||
type McpContext,
|
||||
type McpTextResult,
|
||||
} from '../../../nest-mcp';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { idSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The MCP half of GET /api/trip-warnings/:tripId (#1429).
|
||||
@@ -45,7 +52,8 @@ export class TripWarningsMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'get_trip_warnings',
|
||||
description: 'Problems installed plugins report about a trip: a plugin flagging that something is wrong with the itinerary, such as an accommodation with no check-out, a day that cannot be travelled in the time it allows, or a place closed on the day it is planned for. get_trip_summary returns the trip\'s stored data and never these verdicts, so call this as well before reviewing a trip, reporting on it, or telling the user it looks fine. Returns an empty list when no installed plugin contributes warnings, which is the normal case.',
|
||||
description:
|
||||
"Problems installed plugins report about a trip: a plugin flagging that something is wrong with the itinerary, such as an accommodation with no check-out, a day that cannot be travelled in the time it allows, or a place closed on the day it is planned for. get_trip_summary returns the trip's stored data and never these verdicts, so call this as well before reviewing a trip, reporting on it, or telling the user it looks fine. Returns an empty list when no installed plugin contributes warnings, which is the normal case.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
},
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginHooks } from '../plugin-hooks.service';
|
||||
import { stripEmoji } from '../text-sanitize';
|
||||
import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/view-contributions/:view/:tripId — host-rendered columns/actions that
|
||||
@@ -21,11 +22,38 @@ import { TripAccessService } from '../../trip-membership/trip-access.service';
|
||||
*/
|
||||
type Tone = 'default' | 'success' | 'warn' | 'danger';
|
||||
type ActionTarget = { kind: 'frame'; sub: string } | { kind: 'route'; method: 'GET' | 'POST'; sub: string };
|
||||
interface Column { kind: 'column'; pluginId: string; entityId: number; id: string; label: string; value?: string; url?: string; icon?: string; tone: Tone; }
|
||||
interface Action { kind: 'action'; pluginId: string; entityId: number; id: string; label: string; icon?: string; target: ActionTarget; }
|
||||
interface Column {
|
||||
kind: 'column';
|
||||
pluginId: string;
|
||||
entityId: number;
|
||||
id: string;
|
||||
label: string;
|
||||
value?: string;
|
||||
url?: string;
|
||||
icon?: string;
|
||||
tone: Tone;
|
||||
}
|
||||
interface Action {
|
||||
kind: 'action';
|
||||
pluginId: string;
|
||||
entityId: number;
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
target: ActionTarget;
|
||||
}
|
||||
type Contribution = Column | Action;
|
||||
|
||||
const VIEWS: ReadonlySet<string> = new Set(['reservations', 'transports', 'places', 'day', 'costs', 'packing', 'files', 'todos']);
|
||||
const VIEWS: ReadonlySet<string> = new Set([
|
||||
'reservations',
|
||||
'transports',
|
||||
'places',
|
||||
'day',
|
||||
'costs',
|
||||
'packing',
|
||||
'files',
|
||||
'todos',
|
||||
]);
|
||||
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
|
||||
const MAX_COLUMNS = 20;
|
||||
const MAX_ACTIONS = 10;
|
||||
@@ -88,7 +116,13 @@ function normalize(pluginId: string, raw: unknown): Contribution[] {
|
||||
let target: ActionTarget | undefined;
|
||||
if (t && t.kind === 'frame' && typeof t.sub === 'string' && t.sub) {
|
||||
target = { kind: 'frame', sub: cap(t.sub, SUB_MAX) };
|
||||
} else if (t && t.kind === 'route' && (t.method === 'GET' || t.method === 'POST') && typeof t.sub === 'string' && t.sub) {
|
||||
} else if (
|
||||
t &&
|
||||
t.kind === 'route' &&
|
||||
(t.method === 'GET' || t.method === 'POST') &&
|
||||
typeof t.sub === 'string' &&
|
||||
t.sub
|
||||
) {
|
||||
target = { kind: 'route', method: t.method, sub: cap(t.sub, SUB_MAX) };
|
||||
}
|
||||
if (!target) continue; // a malformed target drops the action, never renders a dead button
|
||||
@@ -116,7 +150,8 @@ export class ViewContributionsController {
|
||||
if (!pluginsEnabled() || !VIEWS.has(view)) return { contributions: [] };
|
||||
const tripId = Number(tripIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { contributions: [] };
|
||||
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
|
||||
return { contributions: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('tableContributor');
|
||||
const perProvider = await Promise.all(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import semver from 'semver';
|
||||
import type { PluginDependency } from './install/manifest';
|
||||
|
||||
import semver from 'semver';
|
||||
|
||||
/**
|
||||
* Pure dependency-reasoning helpers for the plugin runtime (#plugins). Kept
|
||||
* side-effect free (no DB, no process) so the activation gate, the addon-disable
|
||||
@@ -38,11 +39,16 @@ export function parseDependencies(raw: string | null | undefined): PluginDepende
|
||||
try {
|
||||
const o = JSON.parse(raw) as Partial<PluginDependencies>;
|
||||
return {
|
||||
requiredAddons: Array.isArray(o.requiredAddons) ? o.requiredAddons.filter((a): a is string => typeof a === 'string') : [],
|
||||
requiredAddons: Array.isArray(o.requiredAddons)
|
||||
? o.requiredAddons.filter((a): a is string => typeof a === 'string')
|
||||
: [],
|
||||
pluginDependencies: Array.isArray(o.pluginDependencies)
|
||||
? o.pluginDependencies.filter(
|
||||
(d): d is PluginDependency =>
|
||||
!!d && typeof d === 'object' && typeof (d as PluginDependency).id === 'string' && typeof (d as PluginDependency).version === 'string',
|
||||
!!d &&
|
||||
typeof d === 'object' &&
|
||||
typeof (d as PluginDependency).id === 'string' &&
|
||||
typeof (d as PluginDependency).version === 'string',
|
||||
)
|
||||
: [],
|
||||
};
|
||||
@@ -85,7 +91,10 @@ export interface DependencyState {
|
||||
}
|
||||
|
||||
/** Classify each declared plugin dependency against what is installed. */
|
||||
export function resolveDependencyState(deps: PluginDependencies, installed: Map<string, PluginDepRow>): DependencyState {
|
||||
export function resolveDependencyState(
|
||||
deps: PluginDependencies,
|
||||
installed: Map<string, PluginDepRow>,
|
||||
): DependencyState {
|
||||
const state: DependencyState = { missing: [], versionMismatch: [], satisfiedDisabled: [], satisfiedActive: [] };
|
||||
for (const dep of deps.pluginDependencies) {
|
||||
const row = installed.get(dep.id);
|
||||
@@ -106,7 +115,9 @@ export function resolveDependencyState(deps: PluginDependencies, installed: Map<
|
||||
|
||||
/** Plugins whose `pluginDependencies` reference `pluginId` (direct dependents). */
|
||||
export function findDependents(pluginId: string, rows: PluginDepRow[]): string[] {
|
||||
return rows.filter((r) => parseDependencies(r.dependencies).pluginDependencies.some((d) => d.id === pluginId)).map((r) => r.id);
|
||||
return rows
|
||||
.filter((r) => parseDependencies(r.dependencies).pluginDependencies.some((d) => d.id === pluginId))
|
||||
.map((r) => r.id);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* silently on in a shared or production deployment.
|
||||
*/
|
||||
import { readEnv } from '../../app-config';
|
||||
|
||||
export function devLinkEnabled(): boolean {
|
||||
return readEnv().plugins.devLink;
|
||||
}
|
||||
|
||||
@@ -54,7 +54,11 @@ export class DailyBudget {
|
||||
private ai = 0;
|
||||
private notify = 0;
|
||||
|
||||
constructor(private readonly cfg: DailyBudgetConfig, now: number, seed?: { ai?: number; notify?: number }) {
|
||||
constructor(
|
||||
private readonly cfg: DailyBudgetConfig,
|
||||
now: number,
|
||||
seed?: { ai?: number; notify?: number },
|
||||
) {
|
||||
this.day = utcDay(now);
|
||||
this.ai = seed?.ai ?? 0;
|
||||
this.notify = seed?.notify ?? 0;
|
||||
@@ -85,6 +89,12 @@ export class DailyBudget {
|
||||
/** Current usage snapshot for the admin view (read-only). */
|
||||
used(now: number): { day: string; ai: number; aiMax: number; notify: number; notifyMax: number } {
|
||||
this.rollover(now);
|
||||
return { day: this.day, ai: this.ai, aiMax: this.cfg.aiPerDay, notify: this.notify, notifyMax: this.cfg.notifyPerDay };
|
||||
return {
|
||||
day: this.day,
|
||||
ai: this.ai,
|
||||
aiMax: this.cfg.aiPerDay,
|
||||
notify: this.notify,
|
||||
notifyMax: this.cfg.notifyPerDay,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import crypto from 'node:crypto';
|
||||
import type {
|
||||
PluginCapabilityAuditRepository,
|
||||
AuditForPluginRow,
|
||||
AuditForUserRow,
|
||||
} from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { METHOD_PERMISSION } from '../protocol/envelope';
|
||||
import type { PluginCapabilityAuditRepository, AuditForPluginRow, AuditForUserRow } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Host-side, hash-chained capability audit (#plugins, L1 hardening).
|
||||
@@ -26,10 +31,12 @@ export function auditResource(method: string, params: Record<string, unknown>):
|
||||
if (method === 'trips.create') return 'trips:new';
|
||||
if (method === 'trips.listMine') return 'trips:all';
|
||||
if (method === 'reservations.listMine') return 'reservations:all';
|
||||
if (method.startsWith('trips.') || method.startsWith('reservations.') || method.startsWith('accommodations.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('trips.') || method.startsWith('reservations.') || method.startsWith('accommodations.'))
|
||||
return `trip:${params.tripId ?? '?'}`;
|
||||
if (method === 'costs.listMine') return 'costs:all';
|
||||
if (method.startsWith('costs.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('places.') || method.startsWith('days.') || method.startsWith('itinerary.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('places.') || method.startsWith('days.') || method.startsWith('itinerary.'))
|
||||
return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('packing.') || method.startsWith('files.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method === 'journal.listMine') return 'journal:all';
|
||||
if (method.startsWith('journal.')) return `journal:entry:${params.entryId ?? params.journeyId ?? '?'}`;
|
||||
@@ -50,7 +57,10 @@ export function auditResource(method: string, params: Record<string, unknown>):
|
||||
if (method === 'users.getById') return `user:${params.id ?? '?'}`;
|
||||
if (method === 'ws.broadcastToTrip') return `trip:${params.tripId ?? '?'}`;
|
||||
if (method === 'ws.broadcastToUser') return `user:${params.userId ?? '?'}`;
|
||||
if (method === 'notify.send') { const i = (params.input ?? {}) as Record<string, unknown>; return `notify:${i.scope ?? '?'}:${i.targetId ?? '?'}`; }
|
||||
if (method === 'notify.send') {
|
||||
const i = (params.input ?? {}) as Record<string, unknown>;
|
||||
return `notify:${i.scope ?? '?'}:${i.targetId ?? '?'}`;
|
||||
}
|
||||
if (method === 'ai.complete' || method === 'ai.extract') return 'ai:invoke';
|
||||
if (method === 'oauth.getToken') return 'oauth:token';
|
||||
if (method.startsWith('scheduler.')) return `scheduler:${params.name ?? '?'}`;
|
||||
@@ -142,7 +152,11 @@ function envInt(name: string, def: number): number {
|
||||
|
||||
/** Keep only the newest `MAX_AUDIT_ROWS` rows for a plugin. Called amortised from
|
||||
* appendAudit; exported for tests. No-op when disabled or under the cap. */
|
||||
export async function pruneAudit(audit: PluginCapabilityAuditRepository, pluginId: string, keep = MAX_AUDIT_ROWS): Promise<void> {
|
||||
export async function pruneAudit(
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
pluginId: string,
|
||||
keep = MAX_AUDIT_ROWS,
|
||||
): Promise<void> {
|
||||
if (keep <= 0) return;
|
||||
await audit.pruneKeepingNewest(pluginId, keep);
|
||||
}
|
||||
@@ -167,7 +181,10 @@ export async function appendAudit(audit: PluginCapabilityAuditRepository, e: Aud
|
||||
const prev = (await audit.lastHash(e.pluginId)) ?? '';
|
||||
const ts = new Date().toISOString();
|
||||
const row = JSON.stringify([e.pluginId, e.actingUserId ?? null, e.method, e.resource ?? null, e.code, ts]);
|
||||
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(prev + row)
|
||||
.digest('hex');
|
||||
await audit.insertRow({
|
||||
plugin_id: e.pluginId,
|
||||
acting_user_id: e.actingUserId ?? null,
|
||||
@@ -181,20 +198,30 @@ export async function appendAudit(audit: PluginCapabilityAuditRepository, e: Aud
|
||||
});
|
||||
// Amortised retention: prune roughly every PRUNE_EVERY appends per plugin.
|
||||
const n = (appendsSincePrune.get(e.pluginId) ?? 0) + 1;
|
||||
if (n >= PRUNE_EVERY) { appendsSincePrune.set(e.pluginId, 0); await pruneAudit(audit, e.pluginId); }
|
||||
else appendsSincePrune.set(e.pluginId, n);
|
||||
if (n >= PRUNE_EVERY) {
|
||||
appendsSincePrune.set(e.pluginId, 0);
|
||||
await pruneAudit(audit, e.pluginId);
|
||||
} else appendsSincePrune.set(e.pluginId, n);
|
||||
}
|
||||
|
||||
/** Read the most recent audit rows across ALL plugins for one acting user — the
|
||||
* "what have plugins done in my name?" view. This is what legitimizes the broad
|
||||
* read grants: the user, not just the admin, can see every plugin action bound to
|
||||
* them. Joined with the plugin name for display; capped. */
|
||||
export async function readAuditForUser(audit: PluginCapabilityAuditRepository, userId: number, limit = 200): Promise<AuditForUserRow[]> {
|
||||
export async function readAuditForUser(
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
userId: number,
|
||||
limit = 200,
|
||||
): Promise<AuditForUserRow[]> {
|
||||
return audit.forUser(userId, limit);
|
||||
}
|
||||
|
||||
/** Read the most recent audit rows for a plugin (admin view). */
|
||||
export async function readAudit(audit: PluginCapabilityAuditRepository, pluginId: string, limit = 200): Promise<AuditForPluginRow[]> {
|
||||
export async function readAudit(
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
pluginId: string,
|
||||
limit = 200,
|
||||
): Promise<AuditForPluginRow[]> {
|
||||
return audit.forPlugin(pluginId, limit);
|
||||
}
|
||||
|
||||
@@ -214,13 +241,25 @@ export async function readAudit(audit: PluginCapabilityAuditRepository, pluginId
|
||||
* admin "verify audit integrity" surface would want exactly this.
|
||||
*/
|
||||
export function verifyChain(
|
||||
rows: Array<{ plugin_id: string; acting_user_id: number | null; method: string; resource: string | null; code: string; ts: string; prev_hash: string | null; hash: string }>,
|
||||
rows: Array<{
|
||||
plugin_id: string;
|
||||
acting_user_id: number | null;
|
||||
method: string;
|
||||
resource: string | null;
|
||||
code: string;
|
||||
ts: string;
|
||||
prev_hash: string | null;
|
||||
hash: string;
|
||||
}>,
|
||||
): boolean {
|
||||
let prev = '';
|
||||
for (const r of rows) {
|
||||
if ((r.prev_hash ?? '') !== prev) return false;
|
||||
const row = JSON.stringify([r.plugin_id, r.acting_user_id ?? null, r.method, r.resource ?? null, r.code, r.ts]);
|
||||
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(prev + row)
|
||||
.digest('hex');
|
||||
if (hash !== r.hash) return false;
|
||||
prev = r.hash;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Database as Db, Statement } from 'better-sqlite3';
|
||||
import { openDatabase } from '../../../db/connection';
|
||||
import { pluginDataDir, pluginDbFile, pluginsDataRoot } from '../paths';
|
||||
import { splitAfterSemicolons } from './sql-script';
|
||||
|
||||
import type { Database as Db, Statement } from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* A plugin's own sqlite database (#plugins, db:own). The HOST owns the handle;
|
||||
* the plugin child never gets a path or a connection — it can only reach this
|
||||
@@ -81,7 +82,11 @@ const openDbs = new Set<PluginDataDb>();
|
||||
* Best-effort per handle; never throws. */
|
||||
export function checkpointAllPluginDataDbs(): void {
|
||||
for (const d of openDbs) {
|
||||
try { d.checkpoint(); } catch { /* a busy/closed handle is skipped, not fatal */ }
|
||||
try {
|
||||
d.checkpoint();
|
||||
} catch {
|
||||
/* a busy/closed handle is skipped, not fatal */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,9 +107,7 @@ export class PluginDataDb {
|
||||
const pageSize = Number(this.db.pragma('page_size', { simple: true })) || 4096;
|
||||
this.db.pragma(`max_page_count = ${Math.max(1, Math.floor(QUOTA_BYTES / pageSize))}`);
|
||||
// Track applied migrations so db.migrate is idempotent per (plugin, id).
|
||||
this.db.exec(
|
||||
`CREATE TABLE IF NOT EXISTS _plugin_migrations (id TEXT PRIMARY KEY, applied_at INTEGER)`,
|
||||
);
|
||||
this.db.exec(`CREATE TABLE IF NOT EXISTS _plugin_migrations (id TEXT PRIMARY KEY, applied_at INTEGER)`);
|
||||
}
|
||||
|
||||
private guard(sql: string): void {
|
||||
@@ -327,11 +330,21 @@ export function snapshotAllPluginDataDbs(destRoot: string): void {
|
||||
// WAL loses committed transactions, whereas the .db + its WAL is a recoverable set.
|
||||
let foldedIn = false;
|
||||
if (open) {
|
||||
try { open.snapshotInto(path.join(destDir, 'plugin.db')); foldedIn = true; }
|
||||
catch {
|
||||
try { open.checkpoint(); foldedIn = true; } catch { /* WAL not folded — keep sidecars */ }
|
||||
try { fs.copyFileSync(path.join(srcDir, 'plugin.db'), path.join(destDir, 'plugin.db')); }
|
||||
catch { /* unreadable live db — best effort */ }
|
||||
try {
|
||||
open.snapshotInto(path.join(destDir, 'plugin.db'));
|
||||
foldedIn = true;
|
||||
} catch {
|
||||
try {
|
||||
open.checkpoint();
|
||||
foldedIn = true;
|
||||
} catch {
|
||||
/* WAL not folded — keep sidecars */
|
||||
}
|
||||
try {
|
||||
fs.copyFileSync(path.join(srcDir, 'plugin.db'), path.join(destDir, 'plugin.db'));
|
||||
} catch {
|
||||
/* unreadable live db — best effort */
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const f of fs.readdirSync(srcDir, { withFileTypes: true })) {
|
||||
@@ -348,7 +361,9 @@ export function snapshotAllPluginDataDbs(destRoot: string): void {
|
||||
try {
|
||||
if (f.isDirectory()) fs.cpSync(src, dest, { recursive: true });
|
||||
else fs.copyFileSync(src, dest);
|
||||
} catch { /* skip an unreadable entry rather than fail the whole backup */ }
|
||||
} catch {
|
||||
/* skip an unreadable entry rather than fail the whole backup */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { PluginDataDb } from './plugin-data.service';
|
||||
import { DailyBudget, DEFAULT_DAILY_BUDGET } from './daily-budget';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { DailyBudget, DEFAULT_DAILY_BUDGET } from './daily-budget';
|
||||
import { PluginDataDb } from './plugin-data.service';
|
||||
|
||||
/**
|
||||
* Process-wide plugin host state, deliberately module-level (NOT a Nest
|
||||
@@ -64,7 +64,8 @@ async function seedBudget(id: string, audit: PluginCapabilityAuditRepository): P
|
||||
const now = Date.now();
|
||||
const since = new Date(now).toISOString().slice(0, 10) + 'T00:00:00';
|
||||
const rows = await audit.budgetSeed(id, since);
|
||||
let ai = 0, notify = 0;
|
||||
let ai = 0,
|
||||
notify = 0;
|
||||
for (const r of rows) {
|
||||
if (r.method === 'notify.send') notify += r.n;
|
||||
else ai += r.n; // ai.complete + ai.extract
|
||||
@@ -86,6 +87,9 @@ export async function budgetFor(id: string, audit: PluginCapabilityAuditReposito
|
||||
}
|
||||
|
||||
/** Today's broker usage for one plugin (admin view). Seeds the counter if unseen. */
|
||||
export async function pluginBudgetUsage(id: string, audit: PluginCapabilityAuditRepository): Promise<ReturnType<DailyBudget['used']>> {
|
||||
export async function pluginBudgetUsage(
|
||||
id: string,
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
): Promise<ReturnType<DailyBudget['used']>> {
|
||||
return (await budgetFor(id, audit)).used(Date.now());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CronJob, validateCronExpression } from 'cron';
|
||||
import { JOBS_PERMISSION } from '../protocol/envelope';
|
||||
|
||||
import { CronJob, validateCronExpression } from 'cron';
|
||||
|
||||
/**
|
||||
* Host-side scheduler for a plugin's declared background jobs (#plugins).
|
||||
*
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginCapabilityAudit } from '../../../db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { PluginRpcHost } from './rpc-host';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import { PluginRpcRegistryService } from '../../../nest-rpc/rpc-kit/registry.service';
|
||||
import { appendAudit } from './plugin-audit';
|
||||
import { getPluginDataDb } from './plugin-host-state';
|
||||
import { PluginRpcHost } from './rpc-host';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
|
||||
/** 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>;
|
||||
callPlugin(
|
||||
callerId: string,
|
||||
targetId: string,
|
||||
fn: string,
|
||||
args: unknown,
|
||||
actingUserId: number | undefined,
|
||||
): Promise<unknown>;
|
||||
emitPluginEvent(sourceId: string, event: string, payload: unknown): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,10 @@ export class RpcRateLimiter {
|
||||
private readonly bucket: TokenBucket;
|
||||
private inFlight = 0;
|
||||
|
||||
constructor(private readonly cfg: RpcLimitConfig, now: number) {
|
||||
constructor(
|
||||
private readonly cfg: RpcLimitConfig,
|
||||
now: number,
|
||||
) {
|
||||
this.bucket = new TokenBucket(cfg.burst, cfg.perSec, now);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { BadParams, ForbiddenResource } from '../../../nest-rpc/rpc-errors';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import {
|
||||
KNOWN_METHODS,
|
||||
METHOD_PERMISSION,
|
||||
@@ -6,11 +8,9 @@ import {
|
||||
type RpcRequest,
|
||||
type RpcResponse,
|
||||
} from '../protocol/envelope';
|
||||
import type { PluginDataDb } from './plugin-data.service';
|
||||
import { auditResource, isAuditable } from './plugin-audit';
|
||||
import { BadParams, ForbiddenResource } from '../../../nest-rpc/rpc-errors';
|
||||
import { shapePluginOutput } from '../protocol/output-contract';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import { auditResource, isAuditable } from './plugin-audit';
|
||||
import type { PluginDataDb } from './plugin-data.service';
|
||||
|
||||
// Both used to be declared here. They now live in rpc-errors.ts so decorated
|
||||
// *.rpc.ts handlers can throw them without importing the router, and are re-exported
|
||||
@@ -50,7 +50,13 @@ export interface HostDeps {
|
||||
/** Publish an event from this host's plugin to its subscribed dependents. */
|
||||
emitPluginEvent(event: string, payload: unknown): Promise<void>;
|
||||
/** Optional sink for the capability audit log (host-side, hash-chained). */
|
||||
audit?(entry: { pluginId: string; actingUserId?: number; method: string; resource: string | null; code: string }): Promise<void>;
|
||||
audit?(entry: {
|
||||
pluginId: string;
|
||||
actingUserId?: number;
|
||||
method: string;
|
||||
resource: string | null;
|
||||
code: string;
|
||||
}): Promise<void>;
|
||||
}
|
||||
|
||||
type Handler = (params: Record<string, unknown>, actingUserId: number | undefined) => unknown;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { PluginController, PluginMethod, PluginOpenMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import { asArgs, asTxOps, str } from '../../../../nest-rpc/rpc-params';
|
||||
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
|
||||
import { asArgs, asTxOps, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginUserSettingsService } from '../../plugin-user-settings.service';
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import { PluginCapabilityAudit } from '../../../../db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginScheduledTasks } from '../../../../db/entities/PluginScheduledTasks.entity';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import { Users } from '../../../../db/entities/Users.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import type { PluginScheduledTasksRepository } from '../../../../db/repositories/PluginScheduledTasks.repository';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import type { UsersRepository } from '../../../../db/repositories/Users.repository';
|
||||
import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors';
|
||||
import { asPayload, num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
|
||||
import { budgetFor } from '../plugin-host-state';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginCapabilityAudit } from '../../../../db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { Users } from '../../../../db/entities/Users.entity';
|
||||
import type { UsersRepository } from '../../../../db/repositories/Users.repository';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import { PluginScheduledTasks } from '../../../../db/entities/PluginScheduledTasks.entity';
|
||||
import type { PluginScheduledTasksRepository } from '../../../../db/repositories/PluginScheduledTasks.repository';
|
||||
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 { asPayload, num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { UnreadableLlmResponse } from '../../../llm-parse/clients/openai-compatible.client';
|
||||
import { createLlmClient } from '../../../llm-parse/llm-client.factory';
|
||||
import type { ResolvedLlmConfig } from '../../../llm-parse/llm-config';
|
||||
import { LlmConfigResolver } from '../../../llm-parse/llm-config.resolver';
|
||||
import type { LlmExtractionInput } from '../../../llm-parse/llm-provider.interface';
|
||||
import { NotificationsService } from '../../../notifications/notifications.service';
|
||||
import { RealtimeService } from '../../../realtime/realtime.service';
|
||||
import { PluginOAuthService } from '../../oauth/plugin-oauth.service';
|
||||
import { stripEmoji } from '../../text-sanitize';
|
||||
import { budgetFor } from '../plugin-host-state';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
|
||||
/** Caps on the persistent scheduler, bounding the abuse surface. */
|
||||
const SCHED_MAX = 100; // entries per plugin
|
||||
@@ -82,7 +82,8 @@ export class HostSurfaceRpc {
|
||||
// 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 (!(await this.trips.findAccessible(tripId, ctx.actingUserId))) throw new ForbiddenResource(`no access to trip ${tripId}`);
|
||||
if (!(await this.trips.findAccessible(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));
|
||||
@@ -149,7 +150,9 @@ export class HostSurfaceRpc {
|
||||
await this.takeAiBudget(ctx);
|
||||
const system = typeof params.system === 'string' ? params.system.slice(0, 4000) : undefined;
|
||||
const results = await this.runModel(config, {
|
||||
prompt: system || 'You are a helpful assistant. Reply with a JSON object of the form {"text": "..."} whose "text" field holds your answer.',
|
||||
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,
|
||||
@@ -197,13 +200,16 @@ export class HostSurfaceRpc {
|
||||
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 (!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)`);
|
||||
if (json.length > SCHED_PAYLOAD_MAX)
|
||||
throw new BadParams(`scheduler payload too large (max ${SCHED_PAYLOAD_MAX} bytes)`);
|
||||
// HR5/HR6/HR7 — Plan 3j Task 7 fix (must-land 3): one atomic call, not
|
||||
// three separately-awaited ones (task-7-review.md's concurrent-cap-bypass).
|
||||
// Upsert by (plugin, name): re-scheduling the same name replaces it.
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import { DayAccommodations } from '../../../../db/entities/DayAccommodations.entity';
|
||||
import { Days } from '../../../../db/entities/Days.entity';
|
||||
import { Places } from '../../../../db/entities/Places.entity';
|
||||
import { PluginEntityMetadata } from '../../../../db/entities/PluginEntityMetadata.entity';
|
||||
import { Reservations } from '../../../../db/entities/Reservations.entity';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import type { DayAccommodationsRepository } from '../../../../db/repositories/DayAccommodations.repository';
|
||||
import type { DaysRepository } from '../../../../db/repositories/Days.repository';
|
||||
import type { PlacesRepository } from '../../../../db/repositories/Places.repository';
|
||||
import type { PluginEntityMetadataRepository } from '../../../../db/repositories/PluginEntityMetadata.repository';
|
||||
import type { ReservationsRepository } from '../../../../db/repositories/Reservations.repository';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors';
|
||||
import { num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
|
||||
import { PluginEntityMetadata } from '../../../../db/entities/PluginEntityMetadata.entity';
|
||||
import type { PluginEntityMetadataRepository } from '../../../../db/repositories/PluginEntityMetadata.repository';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import { Places } from '../../../../db/entities/Places.entity';
|
||||
import type { PlacesRepository } from '../../../../db/repositories/Places.repository';
|
||||
import { Days } from '../../../../db/entities/Days.entity';
|
||||
import type { DaysRepository } from '../../../../db/repositories/Days.repository';
|
||||
import { Reservations } from '../../../../db/entities/Reservations.entity';
|
||||
import type { ReservationsRepository } from '../../../../db/repositories/Reservations.repository';
|
||||
import { DayAccommodations } from '../../../../db/entities/DayAccommodations.entity';
|
||||
import type { DayAccommodationsRepository } from '../../../../db/repositories/DayAccommodations.repository';
|
||||
import { num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
|
||||
/** Core entities a plugin may attach its own db:meta to. */
|
||||
const META_ENTITY_TYPES: ReadonlySet<string> = new Set(['trip', 'place', 'day', 'reservation', 'accommodation']);
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { PluginActionsRepository } from '../../../db/repositories/PluginActions.repository';
|
||||
import type { PluginErrorLogRepository } from '../../../db/repositories/PluginErrorLog.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import type { UnitOfWork } from '../../database/unit-of-work';
|
||||
import { devLinkEnabled } from '../dev-link';
|
||||
import { pluginsCodeRoot, pluginCodeDir } from '../paths';
|
||||
import { parseJsonText, parseManifest, type PluginManifest } from './manifest';
|
||||
import { scanForNativeBinaries } from './native-scan';
|
||||
import { devLinkEnabled } from '../dev-link';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import type { PluginActionsRepository } from '../../../db/repositories/PluginActions.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginErrorLogRepository } from '../../../db/repositories/PluginErrorLog.repository';
|
||||
import type { UnitOfWork } from '../../database/unit-of-work';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** `discoverPlugins`/`upsert`'s repository set — "swap the parameter type" (plan3j-inputs.md
|
||||
* §0): the raw `BetterSqlite3.Database` parameter becomes this bundle of the four
|
||||
@@ -50,7 +51,11 @@ export async function discoverPlugins(repos: DiscoveryRepos): Promise<{ discover
|
||||
// A dev-link symlink only loads in dev-link mode; a stale link left on the
|
||||
// volume must not be discovered/registered on a normal (non-dev) boot.
|
||||
if (!devLinkEnabled()) continue;
|
||||
try { isDir = fs.statSync(full).isDirectory(); } catch { isDir = false; }
|
||||
try {
|
||||
isDir = fs.statSync(full).isDirectory();
|
||||
} catch {
|
||||
isDir = false;
|
||||
}
|
||||
} else if (isDir && !devLinkEnabled()) {
|
||||
// On Windows a dev-link is a junction, which Dirent reports as a plain
|
||||
// directory (isSymbolicLink() is false). Detect it the same way: if the
|
||||
@@ -58,7 +63,9 @@ export async function discoverPlugins(repos: DiscoveryRepos): Promise<{ discover
|
||||
// unless dev-link mode is on. A normal dir realpaths back to itself.
|
||||
try {
|
||||
if (fs.realpathSync(full) !== path.join(fs.realpathSync(root), entry.name)) continue;
|
||||
} catch { /* unreadable target — leave as a normal dir and let discovery fail loudly */ }
|
||||
} catch {
|
||||
/* unreadable target — leave as a normal dir and let discovery fail loudly */
|
||||
}
|
||||
}
|
||||
if (!isDir) continue;
|
||||
const dir = pluginCodeDir(entry.name);
|
||||
@@ -116,7 +123,14 @@ async function upsert(repos: DiscoveryRepos, m: PluginManifest): Promise<void> {
|
||||
await repos.actions.deleteAllForPlugin(m.id);
|
||||
await repos.actions.insertActions(
|
||||
m.id,
|
||||
m.actions.map((a, i) => ({ action_key: a.key, label: a.label, hint: a.hint ?? null, danger: a.danger ? 1 : 0, scope: a.scope, sort_order: i })),
|
||||
m.actions.map((a, i) => ({
|
||||
action_key: a.key,
|
||||
label: a.label,
|
||||
hint: a.hint ?? null,
|
||||
danger: a.danger ? 1 : 0,
|
||||
scope: a.scope,
|
||||
sort_order: i,
|
||||
})),
|
||||
);
|
||||
|
||||
await repos.settingsFields.deleteAllForPlugin(m.id);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import semver from 'semver';
|
||||
import { readEnv, runningVersion } from '../../../app-config';
|
||||
|
||||
import semver from 'semver';
|
||||
|
||||
/**
|
||||
* Host-version compatibility for plugins (#plugins). A manifest declares the TREK
|
||||
* versions it supports as a semver RANGE (`"trek": ">=3.2.0 <4.0.0"`); this module
|
||||
@@ -46,7 +47,9 @@ export function normalizedHost(): string | null {
|
||||
const coerced = semver.coerce(raw)?.version ?? null;
|
||||
if (!coerced && !warnedUnparseable) {
|
||||
warnedUnparseable = true;
|
||||
console.warn(`[plugins] APP_VERSION "${raw}" is not a semver version — plugin TREK-compatibility checks are disabled`);
|
||||
console.warn(
|
||||
`[plugins] APP_VERSION "${raw}" is not a semver version — plugin TREK-compatibility checks are disabled`,
|
||||
);
|
||||
}
|
||||
return coerced;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import semver from 'semver';
|
||||
import { McpToolSchemaError, buildToolInputSchema, normaliseToolSchema, sanitiseToolText } from '../mcp-tool-schema';
|
||||
import { readPoiCategory } from '../poi-categories';
|
||||
import { isKnownPermission, PLUGIN_API_VERSION } from '../protocol/envelope';
|
||||
import { isValidTrekRange, minTrekOf, trekRangeBypassed } from './host-compat';
|
||||
import {
|
||||
McpToolSchemaError,
|
||||
buildToolInputSchema,
|
||||
normaliseToolSchema,
|
||||
sanitiseToolText,
|
||||
} from '../mcp-tool-schema';
|
||||
import {
|
||||
ACTIONS_MAX,
|
||||
ADDON_ID_RE,
|
||||
@@ -28,8 +22,10 @@ import {
|
||||
TRIP_PAGE_POSITION_MAX,
|
||||
WIDGET_SLOTS,
|
||||
} from '../protocol/manifest-rules';
|
||||
import { isValidTrekRange, minTrekOf, trekRangeBypassed } from './host-compat';
|
||||
import { PLUGIN_POI_MAX_CATEGORIES, type PluginPoiCategory } from '@trek/shared';
|
||||
import { readPoiCategory } from '../poi-categories';
|
||||
|
||||
import semver from 'semver';
|
||||
|
||||
/**
|
||||
* Parse + validate a plugin's trek-plugin.json (#plugins, M4). Kept deliberately
|
||||
@@ -262,7 +258,9 @@ export function parseManifest(raw: unknown, opts?: { requireTrek?: boolean }): P
|
||||
egress.length === 0 &&
|
||||
m.operatorEgress !== true
|
||||
) {
|
||||
throw new ManifestError('http:outbound declared but egress[] is empty (set operatorEgress: true if the hosts are admin-supplied)');
|
||||
throw new ManifestError(
|
||||
'http:outbound declared but egress[] is empty (set operatorEgress: true if the hosts are admin-supplied)',
|
||||
);
|
||||
}
|
||||
if (egress.includes('*')) throw new ManifestError('egress[] must not contain a bare "*"');
|
||||
const badEgress = egress.find((h) => !HOST_RE.test(h));
|
||||
@@ -321,7 +319,8 @@ export function parseManifest(raw: unknown, opts?: { requireTrek?: boolean }): P
|
||||
function parseRequiredAddons(raw: unknown): string[] {
|
||||
const out: string[] = [];
|
||||
for (const v of arr(raw)) {
|
||||
if (typeof v !== 'string' || !ADDON_ID_RE.test(v)) throw new ManifestError(`invalid requiredAddons entry "${String(v)}"`);
|
||||
if (typeof v !== 'string' || !ADDON_ID_RE.test(v))
|
||||
throw new ManifestError(`invalid requiredAddons entry "${String(v)}"`);
|
||||
if (!out.includes(v)) out.push(v);
|
||||
}
|
||||
return out;
|
||||
@@ -343,7 +342,8 @@ function parsePluginDependencies(raw: unknown, selfId: string): PluginDependency
|
||||
if (id === selfId) throw new ManifestError(`plugin "${selfId}" cannot depend on itself`);
|
||||
if (out.some((e) => e.id === id)) throw new ManifestError(`duplicate pluginDependencies id "${id}"`);
|
||||
const version = str(d.version, 'pluginDependencies.version');
|
||||
if (semver.validRange(version) === null) throw new ManifestError(`invalid pluginDependencies version range "${version}" for "${id}"`);
|
||||
if (semver.validRange(version) === null)
|
||||
throw new ManifestError(`invalid pluginDependencies version range "${version}" for "${id}"`);
|
||||
out.push({ id, version });
|
||||
}
|
||||
return out;
|
||||
@@ -371,15 +371,24 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
|
||||
const replaces: string[] = [];
|
||||
for (const v of tp.replaces) {
|
||||
if (typeof v !== 'string' || !TABS.includes(v)) {
|
||||
throw new ManifestError(`capabilities.tripPage.replaces: "${String(v)}" is not a replaceable tab (${REPLACEABLE_TABS.join(', ')})`);
|
||||
throw new ManifestError(
|
||||
`capabilities.tripPage.replaces: "${String(v)}" is not a replaceable tab (${REPLACEABLE_TABS.join(', ')})`,
|
||||
);
|
||||
}
|
||||
if (!replaces.includes(v)) replaces.push(v);
|
||||
}
|
||||
if (replaces.length) page.replaces = replaces;
|
||||
}
|
||||
if (tp.position !== undefined) {
|
||||
if (typeof tp.position !== 'number' || !Number.isInteger(tp.position) || tp.position < 0 || tp.position > TRIP_PAGE_POSITION_MAX) {
|
||||
throw new ManifestError(`capabilities.tripPage.position must be an integer between 0 and ${TRIP_PAGE_POSITION_MAX}`);
|
||||
if (
|
||||
typeof tp.position !== 'number' ||
|
||||
!Number.isInteger(tp.position) ||
|
||||
tp.position < 0 ||
|
||||
tp.position > TRIP_PAGE_POSITION_MAX
|
||||
) {
|
||||
throw new ManifestError(
|
||||
`capabilities.tripPage.position must be an integer between 0 and ${TRIP_PAGE_POSITION_MAX}`,
|
||||
);
|
||||
}
|
||||
page.position = tp.position;
|
||||
}
|
||||
@@ -395,7 +404,8 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
|
||||
const title = optStr(nc.title);
|
||||
if (title) channel.title = title;
|
||||
if (nc.events !== undefined) {
|
||||
if (!Array.isArray(nc.events)) throw new ManifestError('capabilities.notificationChannel.events must be an array');
|
||||
if (!Array.isArray(nc.events))
|
||||
throw new ManifestError('capabilities.notificationChannel.events must be an array');
|
||||
const events: string[] = [];
|
||||
for (const v of nc.events) {
|
||||
if (typeof v !== 'string' || !CHANNEL_EVENTS.includes(v)) {
|
||||
@@ -422,9 +432,11 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
|
||||
if (!ROUTE_PROFILE_ID_RE.test(id)) {
|
||||
throw new ManifestError('capabilities.routeProfiles: id must be lowercase [a-z][a-z0-9-], max 24 chars');
|
||||
}
|
||||
if (profiles.some((x) => x.id === id)) throw new ManifestError(`capabilities.routeProfiles: duplicate id "${id}"`);
|
||||
if (profiles.some((x) => x.id === id))
|
||||
throw new ManifestError(`capabilities.routeProfiles: duplicate id "${id}"`);
|
||||
const label = typeof p.label === 'string' ? p.label.trim() : '';
|
||||
if (!label || label.length > 40) throw new ManifestError('capabilities.routeProfiles: label is required (max 40 chars)');
|
||||
if (!label || label.length > 40)
|
||||
throw new ManifestError('capabilities.routeProfiles: label is required (max 40 chars)');
|
||||
const icon = optStr(p.icon);
|
||||
profiles.push({ id, label, ...(icon ? { icon: icon.slice(0, 40) } : {}) });
|
||||
}
|
||||
@@ -525,7 +537,8 @@ function parseCapabilityNames(raw: unknown, field: string): string[] {
|
||||
if (!Array.isArray(raw)) throw new ManifestError(`capabilities.${field} must be an array of names`);
|
||||
const out: string[] = [];
|
||||
for (const v of raw) {
|
||||
if (typeof v !== 'string' || !CAPABILITY_NAME_RE.test(v)) throw new ManifestError(`invalid capabilities.${field} entry "${String(v)}"`);
|
||||
if (typeof v !== 'string' || !CAPABILITY_NAME_RE.test(v))
|
||||
throw new ManifestError(`invalid capabilities.${field} entry "${String(v)}"`);
|
||||
if (!out.includes(v)) out.push(v);
|
||||
}
|
||||
return out;
|
||||
@@ -550,7 +563,10 @@ function parseSettings(raw: unknown): ManifestSettingField[] {
|
||||
default: parseSettingDefault(s.default, { secret, input_type, options }),
|
||||
scope: s.scope === 'user' ? 'user' : 'instance',
|
||||
options,
|
||||
oauth: s.oauth && typeof s.oauth === 'object' ? (s.oauth as { initPath?: string; callbackPath?: string }) : undefined,
|
||||
oauth:
|
||||
s.oauth && typeof s.oauth === 'object'
|
||||
? (s.oauth as { initPath?: string; callbackPath?: string })
|
||||
: undefined,
|
||||
};
|
||||
})
|
||||
.filter((s) => s.key);
|
||||
@@ -573,7 +589,8 @@ function parseSettingDefault(
|
||||
if (raw === undefined || raw === null || field.secret) return undefined;
|
||||
if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean') return undefined;
|
||||
if (field.input_type === 'checkbox' && typeof raw !== 'boolean') return undefined;
|
||||
if (field.options && field.options.length > 0 && !field.options.some((o) => o.value === String(raw))) return undefined;
|
||||
if (field.options && field.options.length > 0 && !field.options.some((o) => o.value === String(raw)))
|
||||
return undefined;
|
||||
return raw;
|
||||
}
|
||||
|
||||
@@ -636,7 +653,9 @@ function assertSettingKey(key: string): string {
|
||||
// would leave the plugin expecting a setting the host will never store.
|
||||
if (!key) return key;
|
||||
if (!SETTING_KEY_RE.test(key) || RESERVED_SETTING_KEYS.has(key)) {
|
||||
throw new ManifestError(`invalid settings key "${key}" (letters, digits, . _ - ; must start with a letter; 1–64 chars)`);
|
||||
throw new ManifestError(
|
||||
`invalid settings key "${key}" (letters, digits, . _ - ; must start with a letter; 1–64 chars)`,
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ export function safeJoin(dest: string, name: string): string {
|
||||
if (norm.split('/').some((seg) => seg === '..')) throw new ExtractError(`path traversal rejected: ${name}`);
|
||||
const resolved = path.resolve(dest, norm);
|
||||
const root = path.resolve(dest);
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new ExtractError(`escapes destination: ${name}`);
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep))
|
||||
throw new ExtractError(`escapes destination: ${name}`);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
@@ -90,7 +91,9 @@ function readTarGz(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
// memory. The entry budgets in extractArchive never get a say; they run on
|
||||
// the list this function has to finish building first.
|
||||
if (!Number.isSafeInteger(size) || size < 0) {
|
||||
throw new ExtractError(`invalid entry size in tar header: ${block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim()}`);
|
||||
throw new ExtractError(
|
||||
`invalid entry size in tar header: ${block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim()}`,
|
||||
);
|
||||
}
|
||||
const typeflag = String.fromCodePoint(block[156]);
|
||||
off += 512;
|
||||
@@ -98,7 +101,8 @@ function readTarGz(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
off += Math.ceil(size / 512) * 512;
|
||||
if (!name || name.endsWith('/PaxHeader/') || typeflag === 'x' || typeflag === 'g') continue;
|
||||
if (typeflag === '5') members.push({ name, type: 'dir' });
|
||||
else if (typeflag === '0' || typeflag === '\0' || typeflag === '') members.push({ name, type: 'file', data: Buffer.from(data) });
|
||||
else if (typeflag === '0' || typeflag === '\0' || typeflag === '')
|
||||
members.push({ name, type: 'file', data: Buffer.from(data) });
|
||||
else members.push({ name, type: 'other' }); // links (1,2), devices, fifo
|
||||
}
|
||||
return members;
|
||||
@@ -109,7 +113,10 @@ function readZip(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
// Find End Of Central Directory.
|
||||
let eocd = -1;
|
||||
for (let i = buf.length - 22; i >= 0 && i > buf.length - 22 - 65536; i--) {
|
||||
if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
|
||||
if (buf.readUInt32LE(i) === 0x06054b50) {
|
||||
eocd = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocd < 0) throw new ExtractError('invalid zip (no EOCD)');
|
||||
const count = buf.readUInt16LE(eocd + 10);
|
||||
@@ -140,8 +147,14 @@ function readZip(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
const comp = buf.subarray(dataStart, dataStart + compSize);
|
||||
p += 46 + nameLen + extraLen + commentLen;
|
||||
|
||||
if (isSymlink) { members.push({ name, type: 'other' }); continue; }
|
||||
if (name.endsWith('/')) { members.push({ name, type: 'dir' }); continue; }
|
||||
if (isSymlink) {
|
||||
members.push({ name, type: 'other' });
|
||||
continue;
|
||||
}
|
||||
if (name.endsWith('/')) {
|
||||
members.push({ name, type: 'dir' });
|
||||
continue;
|
||||
}
|
||||
let data: Buffer;
|
||||
if (method === 0) {
|
||||
if (compSize > lim.maxFileBytes) throw new ExtractError(`file too large: ${name}`);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isBlockedIp } from '../runtime/egress-policy';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import dns from 'node:dns/promises';
|
||||
import { isBlockedIp } from '../runtime/egress-policy';
|
||||
|
||||
/**
|
||||
* SSRF-hardened download for the plugin installer (#plugins, M4). The primary
|
||||
|
||||
@@ -34,7 +34,12 @@ function ed25519KeyFromRaw(raw: Buffer): crypto.KeyObject {
|
||||
* A bare 32-byte base64 key (44 chars) is also accepted for simple deployments.
|
||||
*/
|
||||
function parseMinisignPubKey(pub: string): { key: crypto.KeyObject; keyId: Buffer | null } {
|
||||
const line = pub.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).pop();
|
||||
const line = pub
|
||||
.trim()
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !l.startsWith('untrusted comment'))
|
||||
.pop();
|
||||
if (!line) throw new SignatureError('empty public key');
|
||||
const buf = Buffer.from(line, 'base64');
|
||||
if (buf.length === 32) return { key: ed25519KeyFromRaw(buf), keyId: null };
|
||||
@@ -51,7 +56,12 @@ function parseMinisignPubKey(pub: string): { key: crypto.KeyObject; keyId: Buffe
|
||||
* raw bytes) is also accepted.
|
||||
*/
|
||||
function parseMinisignSignature(sig: string): { algo: 'Ed' | 'ED' | 'raw'; keyId: Buffer | null; signature: Buffer } {
|
||||
const line = sig.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).shift();
|
||||
const line = sig
|
||||
.trim()
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !l.startsWith('untrusted comment'))
|
||||
.shift();
|
||||
if (!line) throw new SignatureError('empty signature');
|
||||
const buf = Buffer.from(line, 'base64');
|
||||
if (buf.length === 64) return { algo: 'raw', keyId: null, signature: buf };
|
||||
@@ -77,8 +87,7 @@ export function verifyAuthorSignature(bytes: Buffer, signatureB64: string, publi
|
||||
// If both carry a key id, they must match the same key (catches a wrong-key mixup).
|
||||
if (keyId && sigKeyId && !keyId.equals(sigKeyId)) return false;
|
||||
|
||||
const message =
|
||||
algo === 'ED' ? crypto.createHash('blake2b512').update(bytes).digest() : bytes;
|
||||
const message = algo === 'ED' ? crypto.createHash('blake2b512').update(bytes).digest() : bytes;
|
||||
try {
|
||||
return crypto.verify(null, message, key, signature);
|
||||
} catch {
|
||||
|
||||
@@ -12,14 +12,12 @@
|
||||
* static-token deprecation notice is delivered in a tool RESULT precisely
|
||||
* because that is what an assistant reliably surfaces.
|
||||
*/
|
||||
import type { McpZodSchema } from '../../nest-mcp';
|
||||
import { MCP_TOOLS_MAX, TOOL_NAME_RE } from './protocol/manifest-rules';
|
||||
import { sanitiseAssistantText } from './text-sanitize';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { McpZodSchema } from '../../nest-mcp';
|
||||
|
||||
import { MCP_TOOLS_MAX, TOOL_NAME_RE } from './protocol/manifest-rules';
|
||||
|
||||
// The per-plugin cap and the tool-name pattern are manifest rules: they live in
|
||||
// protocol/manifest-rules.ts, which gen-plugin-facts writes into the SDK.
|
||||
export { MCP_TOOLS_MAX, TOOL_NAME_RE };
|
||||
@@ -333,11 +331,29 @@ export function normaliseToolSchema(raw: unknown): Record<string, unknown> | und
|
||||
* accordingly, and the handler then receives whatever a caller actually sent.
|
||||
*/
|
||||
const SUPPORTED_KEYWORDS = new Set([
|
||||
'type', 'properties', 'required', 'additionalProperties', 'items',
|
||||
'enum', 'const', 'description', 'title', 'default', 'examples',
|
||||
'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf',
|
||||
'minLength', 'maxLength', 'pattern', 'format',
|
||||
'minItems', 'maxItems', 'uniqueItems',
|
||||
'type',
|
||||
'properties',
|
||||
'required',
|
||||
'additionalProperties',
|
||||
'items',
|
||||
'enum',
|
||||
'const',
|
||||
'description',
|
||||
'title',
|
||||
'default',
|
||||
'examples',
|
||||
'minimum',
|
||||
'maximum',
|
||||
'exclusiveMinimum',
|
||||
'exclusiveMaximum',
|
||||
'multipleOf',
|
||||
'minLength',
|
||||
'maxLength',
|
||||
'pattern',
|
||||
'format',
|
||||
'minItems',
|
||||
'maxItems',
|
||||
'uniqueItems',
|
||||
'nullable',
|
||||
]);
|
||||
|
||||
@@ -345,12 +361,19 @@ const SUPPORTED_TYPES = new Set(['object', 'string', 'number', 'integer', 'boole
|
||||
|
||||
/** Keywords the branches below read with a `typeof` guard, and the type they need. */
|
||||
const NUMERIC_KEYWORDS: ReadonlyArray<readonly [string, 'number' | 'string' | 'boolean']> = [
|
||||
['minimum', 'number'], ['maximum', 'number'],
|
||||
['exclusiveMinimum', 'number'], ['exclusiveMaximum', 'number'],
|
||||
['multipleOf', 'number'], ['minLength', 'number'], ['maxLength', 'number'],
|
||||
['minItems', 'number'], ['maxItems', 'number'],
|
||||
['pattern', 'string'], ['format', 'string'],
|
||||
['uniqueItems', 'boolean'], ['nullable', 'boolean'],
|
||||
['minimum', 'number'],
|
||||
['maximum', 'number'],
|
||||
['exclusiveMinimum', 'number'],
|
||||
['exclusiveMaximum', 'number'],
|
||||
['multipleOf', 'number'],
|
||||
['minLength', 'number'],
|
||||
['maxLength', 'number'],
|
||||
['minItems', 'number'],
|
||||
['maxItems', 'number'],
|
||||
['pattern', 'string'],
|
||||
['format', 'string'],
|
||||
['uniqueItems', 'boolean'],
|
||||
['nullable', 'boolean'],
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -493,9 +516,12 @@ function nodeToZod(node: unknown, path: string): z.ZodType {
|
||||
let ac = z.array(items);
|
||||
if (typeof node.minItems === 'number') ac = ac.min(node.minItems);
|
||||
if (typeof node.maxItems === 'number') ac = ac.max(node.maxItems);
|
||||
out = node.uniqueItems === true
|
||||
? ac.refine((v) => new Set(v.map((x) => JSON.stringify(x))).size === v.length, { message: 'items must be unique' })
|
||||
: ac;
|
||||
out =
|
||||
node.uniqueItems === true
|
||||
? ac.refine((v) => new Set(v.map((x) => JSON.stringify(x))).size === v.length, {
|
||||
message: 'items must be unique',
|
||||
})
|
||||
: ac;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Controller, Get, Param, Post, Query, Req, Res, UseGuards } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from '../kill-switch';
|
||||
import { PluginOAuthService } from './plugin-oauth.service';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, Param, Post, Query, Req, Res, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Host-brokered outbound OAuth endpoints (#plugins). All are gated by JwtAuthGuard —
|
||||
@@ -28,14 +29,21 @@ export class PluginOAuthController {
|
||||
}
|
||||
|
||||
@Get(':id/status')
|
||||
async status(@Param('id') id: string, @Req() req: Request & { user?: { id: number } }): Promise<{ configured: boolean; connected: boolean }> {
|
||||
async status(
|
||||
@Param('id') id: string,
|
||||
@Req() req: Request & { user?: { id: number } },
|
||||
): Promise<{ configured: boolean; connected: boolean }> {
|
||||
const userId = req.user?.id;
|
||||
if (!pluginsEnabled() || userId == null || !(await this.isActive(id))) return { configured: false, connected: false };
|
||||
if (!pluginsEnabled() || userId == null || !(await this.isActive(id)))
|
||||
return { configured: false, connected: false };
|
||||
return await this.oauth.status(id, userId);
|
||||
}
|
||||
|
||||
@Post(':id/connect')
|
||||
async connect(@Param('id') id: string, @Req() req: Request & { user?: { id: number } }): Promise<{ authorizeUrl: string }> {
|
||||
async connect(
|
||||
@Param('id') id: string,
|
||||
@Req() req: Request & { user?: { id: number } },
|
||||
): Promise<{ authorizeUrl: string }> {
|
||||
const userId = req.user?.id;
|
||||
if (!pluginsEnabled() || userId == null || !(await this.isActive(id))) throw new Error('plugin not available');
|
||||
return { authorizeUrl: await this.oauth.startConnect(id, userId, Date.now()) };
|
||||
@@ -63,7 +71,10 @@ export class PluginOAuthController {
|
||||
}
|
||||
|
||||
@Post(':id/disconnect')
|
||||
async disconnect(@Param('id') id: string, @Req() req: Request & { user?: { id: number } }): Promise<{ connected: false }> {
|
||||
async disconnect(
|
||||
@Param('id') id: string,
|
||||
@Req() req: Request & { user?: { id: number } },
|
||||
): Promise<{ connected: false }> {
|
||||
const userId = req.user?.id;
|
||||
if (userId != null) await this.oauth.disconnect(id, userId);
|
||||
return { connected: false };
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import { PluginOauthTokens } from '../../../db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../db/entities/PluginOauthState.entity';
|
||||
import { PluginOauthTokens } from '../../../db/entities/PluginOauthTokens.entity';
|
||||
import { PluginSettingsFields } from '../../../db/entities/PluginSettingsFields.entity';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import { PluginOAuthController } from './plugin-oauth.controller';
|
||||
import { PluginOAuthService } from './plugin-oauth.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Host-brokered outbound OAuth for plugins: the host runs the authorization code
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import crypto from 'node:crypto';
|
||||
import { encrypt_api_key, decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
|
||||
import { applySettingDefaults, settingDefaults } from '../settings-defaults';
|
||||
import { getAppUrl } from '../../../app-config';
|
||||
import { isPrivateIp } from '../install/safe-fetch';
|
||||
import { safeFetchAdminConfigured } from '../../../utils/ssrfGuard';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { PluginOauthTokens } from '../../../db/entities/PluginOauthTokens.entity';
|
||||
import type { PluginOauthTokensRepository } from '../../../db/repositories/PluginOauthTokens.repository';
|
||||
import { PluginOauthState } from '../../../db/entities/PluginOauthState.entity';
|
||||
import type { PluginOauthStateRepository } from '../../../db/repositories/PluginOauthState.repository';
|
||||
import { PluginOauthTokens } from '../../../db/entities/PluginOauthTokens.entity';
|
||||
import { PluginSettingsFields } from '../../../db/entities/PluginSettingsFields.entity';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginOauthStateRepository } from '../../../db/repositories/PluginOauthState.repository';
|
||||
import type { PluginOauthTokensRepository } from '../../../db/repositories/PluginOauthTokens.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { safeFetchAdminConfigured } from '../../../utils/ssrfGuard';
|
||||
import { encrypt_api_key, decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
|
||||
import { UnitOfWork } from '../../database/unit-of-work';
|
||||
import { isPrivateIp } from '../install/safe-fetch';
|
||||
import { applySettingDefaults, settingDefaults } from '../settings-defaults';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Host-brokered outbound OAuth (#plugins). A plugin becomes an OAuth *client* of a
|
||||
@@ -63,13 +64,18 @@ function assertSafeHttps(urlStr: string, what: string): URL {
|
||||
const host = u.hostname.toLowerCase();
|
||||
const ip = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
|
||||
const loopbackOrMeta =
|
||||
ip === '::1' || ip.startsWith('127.') || ip.startsWith('0.') ||
|
||||
ip.startsWith('169.254.') || /^fe[89ab][0-9a-f]:/.test(ip) || ip.startsWith('fd00:ec2:');
|
||||
ip === '::1' ||
|
||||
ip.startsWith('127.') ||
|
||||
ip.startsWith('0.') ||
|
||||
ip.startsWith('169.254.') ||
|
||||
/^fe[89ab][0-9a-f]:/.test(ip) ||
|
||||
ip.startsWith('fd00:ec2:');
|
||||
if (loopbackOrMeta) throw new Error(`${what} may not point at a loopback or metadata address`);
|
||||
if (host === 'localhost' || host.endsWith('.local') || host.endsWith('.internal')) {
|
||||
throw new Error(`${what} may not point at a local address`);
|
||||
}
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(host) && isPrivateIp(host)) throw new Error(`${what} may not point at a private address`);
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(host) && isPrivateIp(host))
|
||||
throw new Error(`${what} may not point at a private address`);
|
||||
return u;
|
||||
}
|
||||
|
||||
@@ -207,7 +213,10 @@ export class PluginOAuthService {
|
||||
|
||||
// --- internals ---
|
||||
|
||||
private async tokenRequest(cfg: OAuthProviderConfig, params: Record<string, string>): Promise<{ access_token?: string; refresh_token?: string; expires_in?: number; scope?: string }> {
|
||||
private async tokenRequest(
|
||||
cfg: OAuthProviderConfig,
|
||||
params: Record<string, string>,
|
||||
): Promise<{ access_token?: string; refresh_token?: string; expires_in?: number; scope?: string }> {
|
||||
assertSafeHttps(cfg.tokenUrl, 'token_url');
|
||||
const body = new URLSearchParams({ ...params, client_id: cfg.clientId, client_secret: cfg.clientSecret });
|
||||
// Route the server-side token POST through the SSRF guard: it resolves the host
|
||||
@@ -219,12 +228,16 @@ export class PluginOAuthService {
|
||||
// client_secret to a second host, and a token endpoint has no legitimate
|
||||
// reason to redirect. The timeout is not optional either — without it a
|
||||
// hanging provider pins the request handler open indefinitely.
|
||||
const resp = await safeFetchAdminConfigured(cfg.tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
||||
body: body.toString(),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
}, 0);
|
||||
const resp = await safeFetchAdminConfigured(
|
||||
cfg.tokenUrl,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
||||
body: body.toString(),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
},
|
||||
0,
|
||||
);
|
||||
if (!resp.ok) throw new Error(`token endpoint returned ${resp.status}`);
|
||||
const json = (await resp.json()) as Record<string, unknown>;
|
||||
return {
|
||||
@@ -235,7 +248,12 @@ export class PluginOAuthService {
|
||||
};
|
||||
}
|
||||
|
||||
private async storeToken(pluginId: string, userId: number, token: { access_token?: string; refresh_token?: string; expires_in?: number; scope?: string }, nowMs: number): Promise<void> {
|
||||
private async storeToken(
|
||||
pluginId: string,
|
||||
userId: number,
|
||||
token: { access_token?: string; refresh_token?: string; expires_in?: number; scope?: string },
|
||||
nowMs: number,
|
||||
): Promise<void> {
|
||||
if (!token.access_token) throw new Error('token endpoint returned no access_token');
|
||||
const expiresAt = token.expires_in ? nowMs + token.expires_in * 1000 : null;
|
||||
// PO11 (R-oauth-upsert) — encryption happens HERE, in the service, before the
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readEnv } from '../../app-config';
|
||||
import { resolveDataPaths } from '../../app-config/data-paths';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* Filesystem layout for the plugin system (#plugins). Code and data are two
|
||||
* separate trees so the child can be given a read-only view of its code and a
|
||||
@@ -154,7 +155,9 @@ export function pluginPermissionArgs(pluginId: string): string[] {
|
||||
// off by accident.
|
||||
if (!warnedPermissionsOff) {
|
||||
warnedPermissionsOff = true;
|
||||
console.warn('[plugins] TREK_PLUGIN_PERMISSIONS=off — the OS permission jail is DISABLED; installed plugins run with full Node access to this process. Only use this on a machine you fully trust.');
|
||||
console.warn(
|
||||
'[plugins] TREK_PLUGIN_PERMISSIONS=off — the OS permission jail is DISABLED; installed plugins run with full Node access to this process. Only use this on a machine you fully trust.',
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginCapabilityAudit } from '../../db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { readAuditForUser } from './host/plugin-audit';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET /api/plugin-activity — the authenticated user's OWN plugin activity log:
|
||||
@@ -23,7 +24,10 @@ export class PluginActivityController {
|
||||
constructor(@InjectRepository(PluginCapabilityAudit) private readonly audit: PluginCapabilityAuditRepository) {}
|
||||
|
||||
@Get()
|
||||
async mine(@Req() req: Request & { user?: { id: number } }, @Query('limit') limitRaw?: string): Promise<{ activity: unknown[] }> {
|
||||
async mine(
|
||||
@Req() req: Request & { user?: { id: number } },
|
||||
@Query('limit') limitRaw?: string,
|
||||
): Promise<{ activity: unknown[] }> {
|
||||
if (!pluginsEnabled()) return { activity: [] };
|
||||
const userId = req.user?.id;
|
||||
if (userId == null) return { activity: [] };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { pluginsCodeRoot, pluginsDataRoot } from './paths';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pluginsCodeRoot, pluginsDataRoot } from './paths';
|
||||
|
||||
/**
|
||||
* Backup/restore of the plugin trees (#plugins). A TREK backup archives travel.db +
|
||||
@@ -18,8 +19,12 @@ import { pluginsCodeRoot, pluginsDataRoot } from './paths';
|
||||
|
||||
const STAGE_SUFFIX = '.restore';
|
||||
|
||||
function dataStaging(): string { return pluginsDataRoot() + STAGE_SUFFIX; }
|
||||
function codeStaging(): string { return pluginsCodeRoot() + STAGE_SUFFIX; }
|
||||
function dataStaging(): string {
|
||||
return pluginsDataRoot() + STAGE_SUFFIX;
|
||||
}
|
||||
function codeStaging(): string {
|
||||
return pluginsCodeRoot() + STAGE_SUFFIX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the plugin trees an archive extracted (under `extractDir/plugins-data` and
|
||||
@@ -45,10 +50,10 @@ export function stageExtractedPluginTrees(extractDir: string): boolean {
|
||||
for (const [from, to] of pairs) {
|
||||
if (!fs.existsSync(from)) continue;
|
||||
const tmp = to + '.tmp';
|
||||
fs.rmSync(to, { recursive: true, force: true }); // drop a stale completed staging
|
||||
fs.rmSync(to, { recursive: true, force: true }); // drop a stale completed staging
|
||||
fs.rmSync(tmp, { recursive: true, force: true }); // drop a stale partial staging
|
||||
fs.cpSync(from, tmp, { recursive: true }); // may die partway → only .tmp is left, never .restore
|
||||
fs.renameSync(tmp, to); // atomic: publishes a COMPLETE staging
|
||||
fs.cpSync(from, tmp, { recursive: true }); // may die partway → only .tmp is left, never .restore
|
||||
fs.renameSync(tmp, to); // atomic: publishes a COMPLETE staging
|
||||
staged = true;
|
||||
}
|
||||
return staged;
|
||||
@@ -83,7 +88,11 @@ function swapContents(live: string, staged: string): void {
|
||||
if (stagedNames.has(name)) continue;
|
||||
const p = path.join(live, name);
|
||||
let real: string;
|
||||
try { real = fs.realpathSync(p); } catch { real = p; }
|
||||
try {
|
||||
real = fs.realpathSync(p);
|
||||
} catch {
|
||||
real = p;
|
||||
}
|
||||
if (real !== p && !real.startsWith(realLive + path.sep)) continue; // dev-link → keep
|
||||
fs.rmSync(p, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Public } from '../auth-core/public.decorator';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { pluginCodeDir } from './paths';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { pluginCodeDir } from './paths';
|
||||
import { Public } from '../auth-core/public.decorator';
|
||||
|
||||
/**
|
||||
* Serves a page/widget plugin's static client from /plugin-frame/:id/* (#plugins,
|
||||
@@ -108,7 +109,10 @@ export class PluginFrameController {
|
||||
// admin writer's EGRESS_HOST_RE), but never interpolate anything that isn't a clean
|
||||
// host/wildcard into connect-src — a stray space or `*` would inject an extra CSP source.
|
||||
const outbound = [
|
||||
...new Set([...(await this.runtime.outboundHostsOf(pluginId)), ...(await this.runtime.operatorEgressHosts(pluginId))]),
|
||||
...new Set([
|
||||
...(await this.runtime.outboundHostsOf(pluginId)),
|
||||
...(await this.runtime.operatorEgressHosts(pluginId)),
|
||||
]),
|
||||
].filter((h) => /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i.test(h));
|
||||
// The frame runs at an OPAQUE origin (sandbox without allow-same-origin), so
|
||||
// 'self' matches nothing and the plugin's own <script src>/<link> files would
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { PluginsService, MissingRequiredSettingError } from './plugins.service';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../db/repositories/Plugins.repository';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { PluginUserSettingsUpdateDto } from './plugins.dto';
|
||||
import { PluginsService, MissingRequiredSettingError } from './plugins.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { PluginActionDescriptor, PluginActionResult } from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* GET/POST /api/plugin-settings/:id — a USER's own `scope:'user'` settings for a
|
||||
* plugin (#plugins). Deliberately its own path (not under the admin surface, not
|
||||
@@ -36,13 +37,17 @@ export class PluginUserSettingsController {
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async get(@Param('id') id: string, @Req() req: Request & { user?: { id: number } }): Promise<{
|
||||
async get(
|
||||
@Param('id') id: string,
|
||||
@Req() req: Request & { user?: { id: number } },
|
||||
): Promise<{
|
||||
fields: unknown[];
|
||||
config: Record<string, unknown>;
|
||||
actions: PluginActionDescriptor[];
|
||||
}> {
|
||||
const userId = req.user?.id;
|
||||
if (!pluginsEnabled() || userId == null || !(await this.activeWithUserFields(id))) return { fields: [], config: {}, actions: [] };
|
||||
if (!pluginsEnabled() || userId == null || !(await this.activeWithUserFields(id)))
|
||||
return { fields: [], config: {}, actions: [] };
|
||||
return {
|
||||
fields: await this.plugins.userSettingsFields(id),
|
||||
config: await this.plugins.getUserConfig(id, userId),
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginSettingsFields } from '../../db/entities/PluginSettingsFields.entity';
|
||||
import { PluginUserConfig } from '../../db/entities/PluginUserConfig.entity';
|
||||
import type { PluginSettingsFieldsRepository } from '../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginUserConfigRepository } from '../../db/repositories/PluginUserConfig.repository';
|
||||
import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
|
||||
import { safeParseConfig } from './plugin-config-parse';
|
||||
import { isFilled, settingDefaults } from './settings-defaults';
|
||||
import { PluginSettingsFields } from '../../db/entities/PluginSettingsFields.entity';
|
||||
import type { PluginSettingsFieldsRepository } from '../../db/repositories/PluginSettingsFields.repository';
|
||||
import { PluginUserConfig } from '../../db/entities/PluginUserConfig.entity';
|
||||
import type { PluginUserConfigRepository } from '../../db/repositories/PluginUserConfig.repository';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* A plugin's per-user settings, decrypted host-side.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import type { PluginPoiCategory } from '@trek/shared';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../db/repositories/Plugins.repository';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { POI_CATEGORY_PERMISSION, poiCategoriesOf } from './poi-categories';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import type { PluginPoiCategory } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* GET /api/plugins — the authenticated feed of ACTIVE plugins the client renders
|
||||
@@ -74,7 +74,9 @@ function slotOf(capabilities: string): ActivePlugin['slot'] {
|
||||
try {
|
||||
const c = JSON.parse(capabilities || '{}') as { widget?: { slot?: string } };
|
||||
const slot = c.widget?.slot;
|
||||
return slot === 'hero' || slot === 'place-detail' || slot === 'day-detail' || slot === 'reservation-detail' ? slot : 'sidebar';
|
||||
return slot === 'hero' || slot === 'place-detail' || slot === 'day-detail' || slot === 'reservation-detail'
|
||||
? slot
|
||||
: 'sidebar';
|
||||
} catch {
|
||||
return 'sidebar';
|
||||
}
|
||||
@@ -83,7 +85,14 @@ function slotOf(capabilities: string): ActivePlugin['slot'] {
|
||||
// Re-validated here even though the manifest parser already gated the values —
|
||||
// the capabilities column is a JSON blob, and the tab list the client hides
|
||||
// must never be steerable by a hand-edited row ('plan' stays unhideable).
|
||||
const REPLACEABLE_TABS: ReadonlySet<string> = new Set(['transports', 'buchungen', 'listen', 'finanzplan', 'dateien', 'collab']);
|
||||
const REPLACEABLE_TABS: ReadonlySet<string> = new Set([
|
||||
'transports',
|
||||
'buchungen',
|
||||
'listen',
|
||||
'finanzplan',
|
||||
'dateien',
|
||||
'collab',
|
||||
]);
|
||||
|
||||
function settingsUiOf(capabilities: string): boolean {
|
||||
try {
|
||||
@@ -116,7 +125,8 @@ function routeProfilesOf(capabilities: string, granted: string): ActivePlugin['r
|
||||
for (const v of c.routeProfiles.slice(0, 3)) {
|
||||
if (!v || typeof v !== 'object') continue;
|
||||
const p = v as { id?: unknown; label?: unknown; icon?: unknown };
|
||||
if (typeof p.id !== 'string' || !PROFILE_RE.test(p.id) || typeof p.label !== 'string' || !p.label.trim()) continue;
|
||||
if (typeof p.id !== 'string' || !PROFILE_RE.test(p.id) || typeof p.label !== 'string' || !p.label.trim())
|
||||
continue;
|
||||
out.push({
|
||||
id: p.id,
|
||||
label: p.label.trim().slice(0, 40),
|
||||
@@ -134,8 +144,13 @@ function tripPageOf(capabilities: string): ActivePlugin['tripPage'] {
|
||||
const c = JSON.parse(capabilities || '{}') as { tripPage?: { replaces?: unknown; position?: unknown } };
|
||||
const tp = c.tripPage;
|
||||
if (!tp || typeof tp !== 'object') return undefined;
|
||||
const replaces = Array.isArray(tp.replaces) ? tp.replaces.filter((t): t is string => typeof t === 'string' && REPLACEABLE_TABS.has(t)) : [];
|
||||
const position = typeof tp.position === 'number' && Number.isInteger(tp.position) && tp.position >= 0 && tp.position <= 50 ? tp.position : undefined;
|
||||
const replaces = Array.isArray(tp.replaces)
|
||||
? tp.replaces.filter((t): t is string => typeof t === 'string' && REPLACEABLE_TABS.has(t))
|
||||
: [];
|
||||
const position =
|
||||
typeof tp.position === 'number' && Number.isInteger(tp.position) && tp.position >= 0 && tp.position <= 50
|
||||
? tp.position
|
||||
: undefined;
|
||||
if (!replaces.length && position === undefined) return undefined;
|
||||
return { ...(replaces.length ? { replaces } : {}), ...(position !== undefined ? { position } : {}) };
|
||||
} catch {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { All, Controller, Param, Req, Res } from '@nestjs/common';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import type { Request, Response } from 'express';
|
||||
import { UserSessions } from '../../db/entities/UserSessions.entity';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import { extractToken, verifyJwtAndLoadUser } from '../auth-core/jwt-verify';
|
||||
import { Public } from '../auth-core/public.decorator';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { Public } from '../auth-core/public.decorator';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import { UserSessions } from '../../db/entities/UserSessions.entity';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import { All, Controller, Param, Req, Res } from '@nestjs/common';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
/**
|
||||
* Proxies a plugin's own HTTP routes at /api/plugins/:id/* (#plugins, M2).
|
||||
@@ -33,12 +34,24 @@ const SAFE_RESPONSE_HEADERS = new Set(['content-type', 'cache-control']);
|
||||
// so a forwarded header can never leak a TREK session or be replayed. Signature +
|
||||
// event headers from the common providers (GitHub/Stripe/Svix/GitLab/generic) pass.
|
||||
const SAFE_INBOUND_HEADERS = new Set([
|
||||
'content-type', 'user-agent', 'x-request-id', 'x-idempotency-key',
|
||||
'x-hub-signature', 'x-hub-signature-256', 'x-github-event', 'x-github-delivery',
|
||||
'content-type',
|
||||
'user-agent',
|
||||
'x-request-id',
|
||||
'x-idempotency-key',
|
||||
'x-hub-signature',
|
||||
'x-hub-signature-256',
|
||||
'x-github-event',
|
||||
'x-github-delivery',
|
||||
'stripe-signature',
|
||||
'svix-id', 'svix-timestamp', 'svix-signature',
|
||||
'x-gitlab-event', 'x-gitlab-token',
|
||||
'x-signature', 'x-signature-256', 'x-webhook-signature', 'x-event-type',
|
||||
'svix-id',
|
||||
'svix-timestamp',
|
||||
'svix-signature',
|
||||
'x-gitlab-event',
|
||||
'x-gitlab-token',
|
||||
'x-signature',
|
||||
'x-signature-256',
|
||||
'x-webhook-signature',
|
||||
'x-event-type',
|
||||
]);
|
||||
|
||||
function pickInboundHeaders(raw: Record<string, unknown> | undefined): Record<string, string> {
|
||||
@@ -103,7 +116,9 @@ export class PluginsProxyController {
|
||||
let user: { id: number; username: string; role?: 'admin' | 'user' } | null = null;
|
||||
if (route.auth) {
|
||||
const token = extractToken(req);
|
||||
const loaded = token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions)) : null;
|
||||
const loaded = token
|
||||
? await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions))
|
||||
: null;
|
||||
if (!loaded) {
|
||||
res.status(401).json({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
||||
return;
|
||||
@@ -126,7 +141,8 @@ export class PluginsProxyController {
|
||||
// so a non-UTF-8 signed body survives) — the plugin decodes and verifies a
|
||||
// provider's HMAC over the exact payload; the parsed JSON can't be
|
||||
// re-serialised identically.
|
||||
rawBodyBase64: route.auth === false ? ((req as { rawBody?: Buffer }).rawBody?.toString('base64') ?? null) : undefined,
|
||||
rawBodyBase64:
|
||||
route.auth === false ? ((req as { rawBody?: Buffer }).rawBody?.toString('base64') ?? null) : undefined,
|
||||
// Only auth:false routes (webhooks) get inbound headers, and only the
|
||||
// allowlisted, credential-free subset — an authenticated route never
|
||||
// needs them and must not see even the safe ones.
|
||||
|
||||
@@ -1,65 +1,65 @@
|
||||
import { DayAccommodations } from '../../db/entities/DayAccommodations.entity';
|
||||
import { Days } from '../../db/entities/Days.entity';
|
||||
import { NotificationChannelPreferences } from '../../db/entities/NotificationChannelPreferences.entity';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { PluginActions } from '../../db/entities/PluginActions.entity';
|
||||
import { PluginCapabilityAudit } from '../../db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginEgressHosts } from '../../db/entities/PluginEgressHosts.entity';
|
||||
import { PluginEntityMetadata } from '../../db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginErrorLog } from '../../db/entities/PluginErrorLog.entity';
|
||||
import { PluginMetaMigrations } from '../../db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginOauthState } from '../../db/entities/PluginOauthState.entity';
|
||||
import { PluginOauthTokens } from '../../db/entities/PluginOauthTokens.entity';
|
||||
import { PluginScheduledTasks } from '../../db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginSettingsFields } from '../../db/entities/PluginSettingsFields.entity';
|
||||
import { PluginUserConfig } from '../../db/entities/PluginUserConfig.entity';
|
||||
import { PluginUserErasureQueue } from '../../db/entities/PluginUserErasureQueue.entity';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import { Reservations } from '../../db/entities/Reservations.entity';
|
||||
import { Settings } from '../../db/entities/Settings.entity';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import { PluginGuardsModule } from '../../nest-rpc/plugin-guards.module';
|
||||
import { PluginRpcRegistryService } from '../../nest-rpc/rpc-kit/registry.service';
|
||||
import { AccommodationsModule } from '../accommodations/accommodations.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { AssignmentsModule } from '../assignments/assignments.module';
|
||||
import { AtlasModule } from '../atlas/atlas.module';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { BudgetModule } from '../budget/budget.module';
|
||||
import { CategoriesModule } from '../categories/categories.module';
|
||||
import { CollabModule } from '../collab/collab.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
import { DayNotesModule } from '../day-notes/day-notes.module';
|
||||
import { DaysModule } from '../days/days.module';
|
||||
import { FilesModule } from '../files/files.module';
|
||||
import { JournalRpcModule } from '../journey/journal-rpc.module';
|
||||
import { LlmParseModule } from '../llm-parse/llm-parse.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { PackingModule } from '../packing/packing.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { ReservationsModule } from '../reservations/reservations.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { TagsModule } from '../tags/tags.module';
|
||||
import { TodoModule } from '../todo/todo.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { TripsModule } from '../trips/trips.module';
|
||||
import { VacayModule } from '../vacay/vacay.module';
|
||||
import { WeatherModule } from '../weather/weather.module';
|
||||
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
|
||||
import { DbRpc } from './host/rpc/db.rpc';
|
||||
import { HostSurfaceRpc } from './host/rpc/host-surface.rpc';
|
||||
import { MetaRpc } from './host/rpc/meta.rpc';
|
||||
import { PluginOAuthModule } from './oauth/plugin-oauth.module';
|
||||
import { PluginHooks } from './plugin-hooks.service';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { PluginUserSettingsService } from './plugin-user-settings.service';
|
||||
import { PluginsService } from './plugins.service';
|
||||
import { PluginRegistryService } from './registry/registry.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DiscoveryModule } from '@nestjs/core';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../db/entities/PluginErrorLog.entity';
|
||||
import { PluginScheduledTasks } from '../../db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginUserErasureQueue } from '../../db/entities/PluginUserErasureQueue.entity';
|
||||
import { PluginEgressHosts } from '../../db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../db/entities/PluginUserConfig.entity';
|
||||
import { PluginEntityMetadata } from '../../db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginOauthTokens } from '../../db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../db/entities/PluginOauthState.entity';
|
||||
import { PluginMetaMigrations } from '../../db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginCapabilityAudit } from '../../db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../db/entities/NotificationChannelPreferences.entity';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { Days } from '../../db/entities/Days.entity';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { Reservations } from '../../db/entities/Reservations.entity';
|
||||
import { DayAccommodations } from '../../db/entities/DayAccommodations.entity';
|
||||
import { PluginsService } from './plugins.service';
|
||||
import { PluginUserSettingsService } from './plugin-user-settings.service';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
import { PluginHooks } from './plugin-hooks.service';
|
||||
import { PluginRegistryService } from './registry/registry.service';
|
||||
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
|
||||
import { PluginRpcRegistryService } from '../../nest-rpc/rpc-kit/registry.service';
|
||||
import { PluginGuardsModule } from '../../nest-rpc/plugin-guards.module';
|
||||
import { PluginOAuthModule } from './oauth/plugin-oauth.module';
|
||||
import { DbRpc } from './host/rpc/db.rpc';
|
||||
import { MetaRpc } from './host/rpc/meta.rpc';
|
||||
import { HostSurfaceRpc } from './host/rpc/host-surface.rpc';
|
||||
import { WeatherModule } from '../weather/weather.module';
|
||||
import { TagsModule } from '../tags/tags.module';
|
||||
import { CategoriesModule } from '../categories/categories.module';
|
||||
import { BudgetModule } from '../budget/budget.module';
|
||||
import { ReservationsModule } from '../reservations/reservations.module';
|
||||
import { TodoModule } from '../todo/todo.module';
|
||||
import { PackingModule } from '../packing/packing.module';
|
||||
import { DaysModule } from '../days/days.module';
|
||||
import { DayNotesModule } from '../day-notes/day-notes.module';
|
||||
import { AccommodationsModule } from '../accommodations/accommodations.module';
|
||||
import { AssignmentsModule } from '../assignments/assignments.module';
|
||||
import { LlmParseModule } from '../llm-parse/llm-parse.module';
|
||||
import { FilesModule } from '../files/files.module';
|
||||
import { CollabModule } from '../collab/collab.module';
|
||||
import { VacayModule } from '../vacay/vacay.module';
|
||||
import { TripsModule } from '../trips/trips.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
import { AtlasModule } from '../atlas/atlas.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { JournalRpcModule } from '../journey/journal-rpc.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
|
||||
/**
|
||||
* The plugin execution half (#plugins, M1/M2): the process supervisor, the
|
||||
@@ -89,10 +89,21 @@ import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
// their OWN owning modules also register them; MikroOrmModule.forFeature is
|
||||
// idempotent per entity within one DI graph.
|
||||
MikroOrmModule.forFeature([
|
||||
Plugins, PluginErrorLog, PluginScheduledTasks, PluginUserErasureQueue, PluginEgressHosts,
|
||||
PluginSettingsFields, PluginActions, PluginUserConfig, PluginEntityMetadata,
|
||||
PluginOauthTokens, PluginOauthState, PluginMetaMigrations, PluginCapabilityAudit,
|
||||
Settings, NotificationChannelPreferences,
|
||||
Plugins,
|
||||
PluginErrorLog,
|
||||
PluginScheduledTasks,
|
||||
PluginUserErasureQueue,
|
||||
PluginEgressHosts,
|
||||
PluginSettingsFields,
|
||||
PluginActions,
|
||||
PluginUserConfig,
|
||||
PluginEntityMetadata,
|
||||
PluginOauthTokens,
|
||||
PluginOauthState,
|
||||
PluginMetaMigrations,
|
||||
PluginCapabilityAudit,
|
||||
Settings,
|
||||
NotificationChannelPreferences,
|
||||
// Plan 3j Task 5 — HostSurfaceRpc's (Users, Trips, PluginScheduledTasks
|
||||
// above) and MetaRpc's (PluginEntityMetadata above, Trips, Places, Days,
|
||||
// Reservations, DayAccommodations) own `@InjectRepository` params; both
|
||||
@@ -100,7 +111,12 @@ import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
// reasoning every entry above already documents — it owns their
|
||||
// registration too, even though `TripsModule`/`PlacesModule`/etc are
|
||||
// already imported (none of them export `MikroOrmModule`).
|
||||
Users, Trips, Days, Places, Reservations, DayAccommodations,
|
||||
Users,
|
||||
Trips,
|
||||
Days,
|
||||
Places,
|
||||
Reservations,
|
||||
DayAccommodations,
|
||||
]),
|
||||
// A leaf that hands the resource gates to the domain modules. It must not be this
|
||||
// module: the domains would then have to import this one back and close a cycle.
|
||||
@@ -112,11 +128,31 @@ import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
// it must be imported explicitly here, same as every other job-owning module
|
||||
// (place-shadow.module.ts is the precedent).
|
||||
SchedulingModule,
|
||||
WeatherModule, TagsModule, CategoriesModule, BudgetModule, ReservationsModule,
|
||||
TodoModule, PackingModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, LlmParseModule,
|
||||
FilesModule, CollabModule, VacayModule, TripsModule, PlacesModule,
|
||||
PermissionsModule, AuditModule, AddonsModule, CollectionsModule, AtlasModule,
|
||||
NotificationsModule, TripMembershipModule, JournalRpcModule,
|
||||
WeatherModule,
|
||||
TagsModule,
|
||||
CategoriesModule,
|
||||
BudgetModule,
|
||||
ReservationsModule,
|
||||
TodoModule,
|
||||
PackingModule,
|
||||
DaysModule,
|
||||
DayNotesModule,
|
||||
AccommodationsModule,
|
||||
AssignmentsModule,
|
||||
LlmParseModule,
|
||||
FilesModule,
|
||||
CollabModule,
|
||||
VacayModule,
|
||||
TripsModule,
|
||||
PlacesModule,
|
||||
PermissionsModule,
|
||||
AuditModule,
|
||||
AddonsModule,
|
||||
CollectionsModule,
|
||||
AtlasModule,
|
||||
NotificationsModule,
|
||||
TripMembershipModule,
|
||||
JournalRpcModule,
|
||||
],
|
||||
providers: [
|
||||
PluginsService,
|
||||
|
||||
@@ -1,24 +1,49 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Put, Query, Req, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Request } from 'express';
|
||||
import { PluginsService, MissingRequiredSettingError } from './plugins.service';
|
||||
import { PluginRuntimeService, PluginConsentRequired, PluginDependencyError } from './plugin-runtime.service';
|
||||
import { DependencyCycleError } from './dependencies';
|
||||
import { PluginRegistryService, RegistryError } from './registry/registry.service';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { AdminGuard } from '../auth-core/admin.guard';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { getClientIp } from '../audit/client-ip';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { devLinkEnabled } from './dev-link';
|
||||
import { PluginActivateDto, PluginConfigDto, PluginEgressHostsDto, PluginInstallDto, PluginLinkDto, PluginRetrustDto, PluginUninstallDto, PluginUpdateDto } from './plugins.dto';
|
||||
import { ManagedForbidden, isManagedBlocked, MANAGED_FORBIDDEN_ERROR } from '../common/managed';
|
||||
import type { PluginActionResult, PluginInstanceConfigResponse, PluginInstanceConfigUpdated } from '@trek/shared';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
// Straight from sessionManager, not the src/mcp barrel: that one evaluates
|
||||
// readEnv().mcp at module scope and installs the sweep interval, which a domain
|
||||
// module must not drag into every test that mocks app-config partially.
|
||||
import { invalidateMcpSessions } from '../../mcp/sessionManager';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { getClientIp } from '../audit/client-ip';
|
||||
import { AdminGuard } from '../auth-core/admin.guard';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ManagedForbidden, isManagedBlocked, MANAGED_FORBIDDEN_ERROR } from '../common/managed';
|
||||
import { DependencyCycleError } from './dependencies';
|
||||
import { devLinkEnabled } from './dev-link';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { PluginRuntimeService, PluginConsentRequired, PluginDependencyError } from './plugin-runtime.service';
|
||||
import {
|
||||
PluginActivateDto,
|
||||
PluginConfigDto,
|
||||
PluginEgressHostsDto,
|
||||
PluginInstallDto,
|
||||
PluginLinkDto,
|
||||
PluginRetrustDto,
|
||||
PluginUninstallDto,
|
||||
PluginUpdateDto,
|
||||
} from './plugins.dto';
|
||||
import { PluginsService, MissingRequiredSettingError } from './plugins.service';
|
||||
import { PluginRegistryService, RegistryError } from './registry/registry.service';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Req,
|
||||
UploadedFile,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { PluginActionResult, PluginInstanceConfigResponse, PluginInstanceConfigUpdated } from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Flatten a registry/install failure into the error envelope — CARRYING THE CODE.
|
||||
@@ -98,10 +123,9 @@ export class PluginsController {
|
||||
}
|
||||
|
||||
/** Sideload a plugin from an uploaded .zip/.tar.gz (registers INACTIVE). */
|
||||
@ManagedForbidden(
|
||||
'a sideloaded archive skips the signature check every registry install performs',
|
||||
{ enforcedInHandler: true },
|
||||
)
|
||||
@ManagedForbidden('a sideloaded archive skips the signature check every registry install performs', {
|
||||
enforcedInHandler: true,
|
||||
})
|
||||
@Post('upload')
|
||||
@HttpCode(200)
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 + 4096 } }))
|
||||
@@ -129,7 +153,8 @@ export class PluginsController {
|
||||
@HttpCode(200)
|
||||
async link(@Body() body: PluginLinkDto) {
|
||||
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
|
||||
if (!devLinkEnabled()) throw new HttpException({ error: 'Dev-link is disabled (set TREK_PLUGINS_DEV_LINK=1)' }, 403);
|
||||
if (!devLinkEnabled())
|
||||
throw new HttpException({ error: 'Dev-link is disabled (set TREK_PLUGINS_DEV_LINK=1)' }, 403);
|
||||
const dir = body?.path?.trim();
|
||||
if (!dir) throw new HttpException({ error: 'path is required' }, 400);
|
||||
try {
|
||||
@@ -252,7 +277,10 @@ export class PluginsController {
|
||||
// Re-enabling a plugin whose update widened its permissions must NOT grant
|
||||
// them silently — surface a distinct code so the UI opens the consent dialog.
|
||||
if (e instanceof PluginConsentRequired) {
|
||||
throw new HttpException({ error: e.message, code: 'CONSENT_REQUIRED', newPermissions: e.newPermissions, newEgress: e.newEgress }, 409);
|
||||
throw new HttpException(
|
||||
{ error: e.message, code: 'CONSENT_REQUIRED', newPermissions: e.newPermissions, newEgress: e.newEgress },
|
||||
409,
|
||||
);
|
||||
}
|
||||
// Unmet dependency (disabled addon / missing / version-mismatched plugin) —
|
||||
// the UI offers the right fix (enable addon, or download the dependency).
|
||||
@@ -284,14 +312,18 @@ export class PluginsController {
|
||||
@HttpCode(200)
|
||||
async reload(@Param('id') id: string) {
|
||||
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
|
||||
if (!devLinkEnabled()) throw new HttpException({ error: 'Dev-link is disabled (set TREK_PLUGINS_DEV_LINK=1)' }, 403);
|
||||
if (!devLinkEnabled())
|
||||
throw new HttpException({ error: 'Dev-link is disabled (set TREK_PLUGINS_DEV_LINK=1)' }, 403);
|
||||
try {
|
||||
await this.runtime.reload(id);
|
||||
} catch (e) {
|
||||
// A rebuilt manifest that widened permissions must still re-consent, exactly
|
||||
// like activate — surface the same codes so the admin UI reacts identically.
|
||||
if (e instanceof PluginConsentRequired) {
|
||||
throw new HttpException({ error: e.message, code: 'CONSENT_REQUIRED', newPermissions: e.newPermissions, newEgress: e.newEgress }, 409);
|
||||
throw new HttpException(
|
||||
{ error: e.message, code: 'CONSENT_REQUIRED', newPermissions: e.newPermissions, newEgress: e.newEgress },
|
||||
409,
|
||||
);
|
||||
}
|
||||
if (e instanceof PluginDependencyError) {
|
||||
throw new HttpException({ error: e.message, code: e.code, ...e.detail }, 409);
|
||||
@@ -353,7 +385,10 @@ export class PluginsController {
|
||||
if (!body?.version) throw new HttpException({ error: 'version is required' }, 400);
|
||||
if (!body?.publicKey) throw new HttpException({ error: 'publicKey is required' }, 400);
|
||||
try {
|
||||
const res = await this.runtime.retrust(id, body.version, body.publicKey, { userId: user?.id ?? null, ip: getClientIp(req) });
|
||||
const res = await this.runtime.retrust(id, body.version, body.publicKey, {
|
||||
userId: user?.id ?? null,
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
invalidateMcpSessions();
|
||||
return res;
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
import {
|
||||
pluginActivateRequestSchema,
|
||||
pluginEgressHostsRequestSchema,
|
||||
@@ -12,6 +11,8 @@ import {
|
||||
pluginUserSettingsUpdateRequestSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
/**
|
||||
* Nest DTO classes for the plugin surfaces — thin wrappers over the shared
|
||||
* contracts in @trek/shared (plugins.schema.ts), which carry the schemas, the
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { PluginsController } from './plugins.controller';
|
||||
import { PluginsFeedController } from './plugins-feed.controller';
|
||||
import { PluginsProxyController } from './plugins-proxy.controller';
|
||||
import { PluginFrameController } from './plugin-frame.controller';
|
||||
import { PluginActivityController } from './plugin-activity.controller';
|
||||
import { PluginUserSettingsController } from './plugin-user-settings.controller';
|
||||
import { PluginsRuntimeModule } from './plugins-runtime.module';
|
||||
import { PluginOAuthModule } from './oauth/plugin-oauth.module';
|
||||
import { PluginContributionsModule } from './contributions/plugin-contributions.module';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { PluginCapabilityAudit } from '../../db/entities/PluginCapabilityAudit.entity';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { PluginContributionsModule } from './contributions/plugin-contributions.module';
|
||||
import { PluginOAuthModule } from './oauth/plugin-oauth.module';
|
||||
import { PluginActivityController } from './plugin-activity.controller';
|
||||
import { PluginFrameController } from './plugin-frame.controller';
|
||||
import { PluginUserSettingsController } from './plugin-user-settings.controller';
|
||||
import { PluginsFeedController } from './plugins-feed.controller';
|
||||
import { PluginsProxyController } from './plugins-proxy.controller';
|
||||
import { PluginsRuntimeModule } from './plugins-runtime.module';
|
||||
import { PluginsController } from './plugins.controller';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Plugin system (#plugins), composition root.
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../db/repositories/Plugins.repository';
|
||||
import { PluginErrorLog } from '../../db/entities/PluginErrorLog.entity';
|
||||
import type { PluginErrorLogRepository } from '../../db/repositories/PluginErrorLog.repository';
|
||||
import { PluginEgressHosts } from '../../db/entities/PluginEgressHosts.entity';
|
||||
import type { PluginEgressHostsRepository } from '../../db/repositories/PluginEgressHosts.repository';
|
||||
import { PluginSettingsFields } from '../../db/entities/PluginSettingsFields.entity';
|
||||
import type { PluginSettingsFieldsRepository } from '../../db/repositories/PluginSettingsFields.repository';
|
||||
import { PluginActions } from '../../db/entities/PluginActions.entity';
|
||||
import type { PluginActionsRepository } from '../../db/repositories/PluginActions.repository';
|
||||
import { PluginUserConfig } from '../../db/entities/PluginUserConfig.entity';
|
||||
import type { PluginUserConfigRepository } from '../../db/repositories/PluginUserConfig.repository';
|
||||
import { PluginCapabilityAudit } from '../../db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginEgressHosts } from '../../db/entities/PluginEgressHosts.entity';
|
||||
import { PluginErrorLog } from '../../db/entities/PluginErrorLog.entity';
|
||||
import { PluginSettingsFields } from '../../db/entities/PluginSettingsFields.entity';
|
||||
import { PluginUserConfig } from '../../db/entities/PluginUserConfig.entity';
|
||||
import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import type { PluginActionsRepository } from '../../db/repositories/PluginActions.repository';
|
||||
import type { PluginCapabilityAuditRepository } from '../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { devLinkEnabled } from './dev-link';
|
||||
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
|
||||
import { readAudit } from './host/plugin-audit';
|
||||
import { keyFingerprint } from './signature-status';
|
||||
import { pluginBudgetUsage } from './host/plugin-host-state';
|
||||
import { safeParseConfig as safeParse } from './plugin-config-parse';
|
||||
import { isFilled, parseDefaultValue, settingDefaults } from './settings-defaults';
|
||||
import type { PluginEgressHostsRepository } from '../../db/repositories/PluginEgressHosts.repository';
|
||||
import type { PluginErrorLogRepository } from '../../db/repositories/PluginErrorLog.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginUserConfigRepository } from '../../db/repositories/PluginUserConfig.repository';
|
||||
import type { PluginsRepository } from '../../db/repositories/Plugins.repository';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { parseDependencies, disabledRequiredAddons, resolveDependencyState, type PluginDepRow, type PluginDependencies, type VersionMismatch } from './dependencies';
|
||||
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
|
||||
import {
|
||||
parseDependencies,
|
||||
disabledRequiredAddons,
|
||||
resolveDependencyState,
|
||||
type PluginDepRow,
|
||||
type PluginDependencies,
|
||||
type VersionMismatch,
|
||||
} from './dependencies';
|
||||
import { devLinkEnabled } from './dev-link';
|
||||
import { readAudit } from './host/plugin-audit';
|
||||
import { pluginBudgetUsage } from './host/plugin-host-state';
|
||||
import { bypassedRange, hostSatisfies, hostVersion, trekRangeBypassed } from './install/host-compat';
|
||||
import type { TrekRangeBypass } from './install/host-compat';
|
||||
import type { PluginDependency } from './install/manifest';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { safeParseConfig as safeParse } from './plugin-config-parse';
|
||||
import { isFilled, parseDefaultValue, settingDefaults } from './settings-defaults';
|
||||
import { keyFingerprint } from './signature-status';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { PluginSettingsField } from '@trek/shared';
|
||||
|
||||
const SECRET_MASK = '••••••••';
|
||||
@@ -194,13 +201,14 @@ export class PluginsService {
|
||||
// Mirrors the order of assertActivatable's gate, so the card explains the same
|
||||
// blocker the activate call would hit rather than a second, lesser one.
|
||||
const trekBypass = bypassedRange(r.trek_range);
|
||||
const dependencyStatus: PluginDependencyStatus = !hostSatisfies(r.trek_range) && !trekBypass
|
||||
? 'hostIncompatible'
|
||||
: disabledAddons.length
|
||||
? 'addonDisabled'
|
||||
: state.missing.length || state.versionMismatch.length
|
||||
? 'missingPlugin'
|
||||
: 'ok';
|
||||
const dependencyStatus: PluginDependencyStatus =
|
||||
!hostSatisfies(r.trek_range) && !trekBypass
|
||||
? 'hostIncompatible'
|
||||
: disabledAddons.length
|
||||
? 'addonDisabled'
|
||||
: state.missing.length || state.versionMismatch.length
|
||||
? 'missingPlugin'
|
||||
: 'ok';
|
||||
const {
|
||||
dependencies: _raw,
|
||||
operator_egress: _oe,
|
||||
@@ -293,7 +301,10 @@ export class PluginsService {
|
||||
secret: row.secret === 1,
|
||||
default: parseDefaultValue(row.default_value),
|
||||
// Stored as manifest-validated JSON ({value,label} pairs) — parse, don't re-check.
|
||||
options: typeof row.options === 'string' && row.options ? (safeArray(row.options) as PluginSettingsField['options']) : undefined,
|
||||
options:
|
||||
typeof row.options === 'string' && row.options
|
||||
? (safeArray(row.options) as PluginSettingsField['options'])
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -375,7 +386,11 @@ export class PluginsService {
|
||||
* stored secret (non-empty ciphertext) counts as filled. A `checkbox` is exempt — required
|
||||
* would demand `true`, which is a consent flow, not a settings field.
|
||||
*/
|
||||
private async assertRequiredFilled(id: string, scope: 'instance' | 'user', config: Record<string, unknown>): Promise<void> {
|
||||
private async assertRequiredFilled(
|
||||
id: string,
|
||||
scope: 'instance' | 'user',
|
||||
config: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const required = await this.pluginSettingsFields.listRequiredFieldKeys(id, scope);
|
||||
const defaults = await settingDefaults(this.pluginSettingsFields, id, scope);
|
||||
for (const fieldKey of required) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sanitiseAssistantText } from './text-sanitize';
|
||||
import {
|
||||
PLUGIN_POI_CATEGORY_ID_RE,
|
||||
PLUGIN_POI_COLOR_RE,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
pluginPoiCategorySchema,
|
||||
type PluginPoiCategory,
|
||||
} from '@trek/shared';
|
||||
import { sanitiseAssistantText } from './text-sanitize';
|
||||
|
||||
/**
|
||||
* Reading a plugin's `capabilities.poiCategories` (#1781), in one place for the three
|
||||
@@ -55,7 +55,8 @@ function readLabels(raw: unknown): { ok: true; value?: Record<string, string> }
|
||||
}
|
||||
const out: Record<string, string> = {};
|
||||
for (const [code, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (!LANGUAGE_KEY_RE.test(code)) return { ok: false, reason: `labels: "${code.slice(0, 20)}" is not a language code` };
|
||||
if (!LANGUAGE_KEY_RE.test(code))
|
||||
return { ok: false, reason: `labels: "${code.slice(0, 20)}" is not a language code` };
|
||||
const label = rawLabel(value);
|
||||
if (!label) return { ok: false, reason: `labels.${code} is required (max ${PLUGIN_POI_LABEL_MAX} chars)` };
|
||||
const clean = cleanLabel(label);
|
||||
@@ -69,7 +70,8 @@ export function readPoiCategory(raw: unknown): PoiCategoryRead {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, reason: 'entries must be objects' };
|
||||
const p = raw as Record<string, unknown>;
|
||||
const id = typeof p.id === 'string' ? p.id : '';
|
||||
if (!PLUGIN_POI_CATEGORY_ID_RE.test(id)) return { ok: false, reason: 'id must be lowercase [a-z][a-z0-9-], max 24 chars' };
|
||||
if (!PLUGIN_POI_CATEGORY_ID_RE.test(id))
|
||||
return { ok: false, reason: 'id must be lowercase [a-z][a-z0-9-], max 24 chars' };
|
||||
const label = rawLabel(p.label);
|
||||
if (!label) return { ok: false, reason: `"${id}" label is required (max ${PLUGIN_POI_LABEL_MAX} chars)` };
|
||||
if (!isPluginPoiIcon(p.icon)) {
|
||||
|
||||
@@ -52,8 +52,19 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
trip: {
|
||||
table: 'trips',
|
||||
columns: [
|
||||
'id', 'user_id', 'title', 'description', 'start_date', 'end_date', 'currency', 'cover_image',
|
||||
'is_archived', 'reminder_days', 'created_at', 'updated_at', 'reminder_sent_for',
|
||||
'id',
|
||||
'user_id',
|
||||
'title',
|
||||
'description',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'currency',
|
||||
'cover_image',
|
||||
'is_archived',
|
||||
'reminder_days',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'reminder_sent_for',
|
||||
],
|
||||
// The sole credential of the anonymous calendar feed.
|
||||
withheld: ['feed_token'],
|
||||
@@ -63,17 +74,53 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
place: {
|
||||
table: 'places',
|
||||
columns: [
|
||||
'id', 'trip_id', 'name', 'description', 'lat', 'lng', 'address', 'category_id', 'price', 'currency',
|
||||
'reservation_status', 'reservation_notes', 'reservation_datetime', 'place_time', 'end_time',
|
||||
'duration_minutes', 'notes', 'image_url', 'google_place_id', 'google_ftid', 'website', 'phone',
|
||||
'transport_mode', 'created_at', 'updated_at', 'osm_id', 'route_geometry', 'route_color', 'stop_type',
|
||||
'fill_percent', 'amap_poi_id', 'source', 'email', 'opening_hours',
|
||||
'id',
|
||||
'trip_id',
|
||||
'name',
|
||||
'description',
|
||||
'lat',
|
||||
'lng',
|
||||
'address',
|
||||
'category_id',
|
||||
'price',
|
||||
'currency',
|
||||
'reservation_status',
|
||||
'reservation_notes',
|
||||
'reservation_datetime',
|
||||
'place_time',
|
||||
'end_time',
|
||||
'duration_minutes',
|
||||
'notes',
|
||||
'image_url',
|
||||
'google_place_id',
|
||||
'google_ftid',
|
||||
'website',
|
||||
'phone',
|
||||
'transport_mode',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'osm_id',
|
||||
'route_geometry',
|
||||
'route_color',
|
||||
'stop_type',
|
||||
'fill_percent',
|
||||
'amap_poi_id',
|
||||
'source',
|
||||
'email',
|
||||
'opening_hours',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
derived: [
|
||||
'category_name', 'category_color', 'category_icon', 'tour_place_id', 'category', 'tags', 'ratings',
|
||||
'rating_avg', 'rating_count',
|
||||
'category_name',
|
||||
'category_color',
|
||||
'category_icon',
|
||||
'tour_place_id',
|
||||
'category',
|
||||
'tags',
|
||||
'ratings',
|
||||
'rating_avg',
|
||||
'rating_count',
|
||||
],
|
||||
},
|
||||
day: {
|
||||
@@ -86,23 +133,65 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
reservation: {
|
||||
table: 'reservations',
|
||||
columns: [
|
||||
'id', 'trip_id', 'day_id', 'end_day_id', 'place_id', 'assignment_id', 'title', 'accommodation_id',
|
||||
'reservation_time', 'reservation_end_time', 'location', 'confirmation_number', 'notes', 'status', 'type',
|
||||
'created_at', 'metadata', 'day_plan_position', 'needs_review', 'external_source', 'external_id',
|
||||
'external_owner_user_id', 'external_synced_at', 'sync_enabled', 'external_hash', 'url', 'ingest_state',
|
||||
'id',
|
||||
'trip_id',
|
||||
'day_id',
|
||||
'end_day_id',
|
||||
'place_id',
|
||||
'assignment_id',
|
||||
'title',
|
||||
'accommodation_id',
|
||||
'reservation_time',
|
||||
'reservation_end_time',
|
||||
'location',
|
||||
'confirmation_number',
|
||||
'notes',
|
||||
'status',
|
||||
'type',
|
||||
'created_at',
|
||||
'metadata',
|
||||
'day_plan_position',
|
||||
'needs_review',
|
||||
'external_source',
|
||||
'external_id',
|
||||
'external_owner_user_id',
|
||||
'external_synced_at',
|
||||
'sync_enabled',
|
||||
'external_hash',
|
||||
'url',
|
||||
'ingest_state',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
derived: [
|
||||
'day_number', 'place_name', 'accommodation_place_id', 'accommodation_name', 'accommodation_start_day_id',
|
||||
'accommodation_end_day_id', 'day_positions', 'endpoints', 'travelers',
|
||||
'day_number',
|
||||
'place_name',
|
||||
'accommodation_place_id',
|
||||
'accommodation_name',
|
||||
'accommodation_start_day_id',
|
||||
'accommodation_end_day_id',
|
||||
'day_positions',
|
||||
'endpoints',
|
||||
'travelers',
|
||||
],
|
||||
},
|
||||
packingItem: {
|
||||
table: 'packing_items',
|
||||
columns: [
|
||||
'id', 'trip_id', 'name', 'checked', 'category', 'sort_order', 'created_at', 'weight_grams', 'bag_id',
|
||||
'quantity', 'updated_at', 'is_private', 'owner_id', 'packed_quantity',
|
||||
'id',
|
||||
'trip_id',
|
||||
'name',
|
||||
'checked',
|
||||
'category',
|
||||
'sort_order',
|
||||
'created_at',
|
||||
'weight_grams',
|
||||
'bag_id',
|
||||
'quantity',
|
||||
'updated_at',
|
||||
'is_private',
|
||||
'owner_id',
|
||||
'packed_quantity',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -111,21 +200,54 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
tripFile: {
|
||||
table: 'trip_files',
|
||||
columns: [
|
||||
'id', 'trip_id', 'place_id', 'reservation_id', 'filename', 'original_name', 'file_size', 'mime_type',
|
||||
'description', 'created_at', 'note_id', 'uploaded_by', 'starred', 'deleted_at', 'message_id',
|
||||
'id',
|
||||
'trip_id',
|
||||
'place_id',
|
||||
'reservation_id',
|
||||
'filename',
|
||||
'original_name',
|
||||
'file_size',
|
||||
'mime_type',
|
||||
'description',
|
||||
'created_at',
|
||||
'note_id',
|
||||
'uploaded_by',
|
||||
'starred',
|
||||
'deleted_at',
|
||||
'message_id',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
derived: [
|
||||
'reservation_title', 'uploaded_by_name', 'uploaded_by_avatar', 'url', 'linked_reservation_ids',
|
||||
'linked_place_ids', 'linked_budget_item_ids',
|
||||
'reservation_title',
|
||||
'uploaded_by_name',
|
||||
'uploaded_by_avatar',
|
||||
'url',
|
||||
'linked_reservation_ids',
|
||||
'linked_place_ids',
|
||||
'linked_budget_item_ids',
|
||||
],
|
||||
},
|
||||
budgetItem: {
|
||||
table: 'budget_items',
|
||||
columns: [
|
||||
'id', 'trip_id', 'category', 'name', 'total_price', 'persons', 'days', 'note', 'sort_order', 'created_at',
|
||||
'paid_by_user_id', 'expense_date', 'reservation_id', 'currency', 'exchange_rate', 'ticket_json', 'place_id',
|
||||
'id',
|
||||
'trip_id',
|
||||
'category',
|
||||
'name',
|
||||
'total_price',
|
||||
'persons',
|
||||
'days',
|
||||
'note',
|
||||
'sort_order',
|
||||
'created_at',
|
||||
'paid_by_user_id',
|
||||
'expense_date',
|
||||
'reservation_id',
|
||||
'currency',
|
||||
'exchange_rate',
|
||||
'ticket_json',
|
||||
'place_id',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -134,8 +256,19 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
assignment: {
|
||||
table: 'day_assignments',
|
||||
columns: [
|
||||
'id', 'day_id', 'place_id', 'order_index', 'notes', 'assignment_time', 'assignment_end_time', 'end_day',
|
||||
'leg_transport_mode', 'incoming_leg_transport_mode', 'route_excluded', 'accommodation_id', 'created_at',
|
||||
'id',
|
||||
'day_id',
|
||||
'place_id',
|
||||
'order_index',
|
||||
'notes',
|
||||
'assignment_time',
|
||||
'assignment_end_time',
|
||||
'end_day',
|
||||
'leg_transport_mode',
|
||||
'incoming_leg_transport_mode',
|
||||
'route_excluded',
|
||||
'accommodation_id',
|
||||
'created_at',
|
||||
],
|
||||
withheld: [],
|
||||
// The assignment read model names its fields one by one, its `place` included.
|
||||
@@ -163,8 +296,18 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
reservationEndpoint: {
|
||||
table: 'reservation_endpoints',
|
||||
columns: [
|
||||
'id', 'reservation_id', 'role', 'sequence', 'name', 'code', 'lat', 'lng', 'timezone', 'local_time',
|
||||
'local_date', 'created_at',
|
||||
'id',
|
||||
'reservation_id',
|
||||
'role',
|
||||
'sequence',
|
||||
'name',
|
||||
'code',
|
||||
'lat',
|
||||
'lng',
|
||||
'timezone',
|
||||
'local_time',
|
||||
'local_date',
|
||||
'created_at',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -182,8 +325,18 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
todo: {
|
||||
table: 'todo_items',
|
||||
columns: [
|
||||
'id', 'trip_id', 'name', 'checked', 'category', 'sort_order', 'due_date', 'description', 'assigned_user_id',
|
||||
'priority', 'created_at', 'reminded_at',
|
||||
'id',
|
||||
'trip_id',
|
||||
'name',
|
||||
'checked',
|
||||
'category',
|
||||
'sort_order',
|
||||
'due_date',
|
||||
'description',
|
||||
'assigned_user_id',
|
||||
'priority',
|
||||
'created_at',
|
||||
'reminded_at',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -193,8 +346,17 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
accommodation: {
|
||||
table: 'day_accommodations',
|
||||
columns: [
|
||||
'id', 'trip_id', 'place_id', 'start_day_id', 'end_day_id', 'check_in', 'check_in_end', 'check_out',
|
||||
'confirmation', 'notes', 'created_at',
|
||||
'id',
|
||||
'trip_id',
|
||||
'place_id',
|
||||
'start_day_id',
|
||||
'end_day_id',
|
||||
'check_in',
|
||||
'check_in_end',
|
||||
'check_out',
|
||||
'confirmation',
|
||||
'notes',
|
||||
'created_at',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -218,7 +380,16 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
collabNote: {
|
||||
table: 'collab_notes',
|
||||
columns: [
|
||||
'id', 'trip_id', 'user_id', 'category', 'title', 'content', 'color', 'pinned', 'created_at', 'updated_at',
|
||||
'id',
|
||||
'trip_id',
|
||||
'user_id',
|
||||
'category',
|
||||
'title',
|
||||
'content',
|
||||
'color',
|
||||
'pinned',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'website',
|
||||
],
|
||||
withheld: [],
|
||||
@@ -239,14 +410,34 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
derived: [
|
||||
'username', 'avatar', 'reply_text', 'reply_username', 'user_avatar', 'avatar_url', 'reactions', 'attachments',
|
||||
'username',
|
||||
'avatar',
|
||||
'reply_text',
|
||||
'reply_username',
|
||||
'user_avatar',
|
||||
'avatar_url',
|
||||
'reactions',
|
||||
'attachments',
|
||||
],
|
||||
},
|
||||
journey: {
|
||||
table: 'journeys',
|
||||
columns: [
|
||||
'id', 'user_id', 'title', 'subtitle', 'cover_gradient', 'status', 'created_at', 'updated_at', 'cover_image',
|
||||
'show_trip_tracks', 'show_verdict', 'show_mood', 'show_weather', 'status_override', 'photo_location',
|
||||
'id',
|
||||
'user_id',
|
||||
'title',
|
||||
'subtitle',
|
||||
'cover_gradient',
|
||||
'status',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'cover_image',
|
||||
'show_trip_tracks',
|
||||
'show_verdict',
|
||||
'show_mood',
|
||||
'show_weather',
|
||||
'status_override',
|
||||
'photo_location',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -256,10 +447,32 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
journalEntry: {
|
||||
table: 'journey_entries',
|
||||
columns: [
|
||||
'id', 'journey_id', 'source_trip_id', 'source_place_id', 'author_id', 'type', 'title', 'story', 'entry_date',
|
||||
'entry_time', 'location_name', 'location_lat', 'location_lng', 'mood', 'weather', 'tags', 'visibility',
|
||||
'sort_order', 'created_at', 'updated_at', 'pros_cons', 'stats_excluded', 'dismissed', 'country_code',
|
||||
'source_assignment_id', 'is_draft',
|
||||
'id',
|
||||
'journey_id',
|
||||
'source_trip_id',
|
||||
'source_place_id',
|
||||
'author_id',
|
||||
'type',
|
||||
'title',
|
||||
'story',
|
||||
'entry_date',
|
||||
'entry_time',
|
||||
'location_name',
|
||||
'location_lat',
|
||||
'location_lng',
|
||||
'mood',
|
||||
'weather',
|
||||
'tags',
|
||||
'visibility',
|
||||
'sort_order',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'pros_cons',
|
||||
'stats_excluded',
|
||||
'dismissed',
|
||||
'country_code',
|
||||
'source_assignment_id',
|
||||
'is_draft',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -275,8 +488,18 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
bucketItem: {
|
||||
table: 'bucket_list',
|
||||
columns: [
|
||||
'id', 'user_id', 'name', 'lat', 'lng', 'country_code', 'notes', 'created_at', 'target_date', 'visited_at',
|
||||
'visited_source', 'region_code',
|
||||
'id',
|
||||
'user_id',
|
||||
'name',
|
||||
'lat',
|
||||
'lng',
|
||||
'country_code',
|
||||
'notes',
|
||||
'created_at',
|
||||
'target_date',
|
||||
'visited_at',
|
||||
'visited_source',
|
||||
'region_code',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
@@ -286,7 +509,16 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
collection: {
|
||||
table: 'collections',
|
||||
columns: [
|
||||
'id', 'owner_id', 'name', 'description', 'color', 'icon', 'cover_image', 'links', 'sort_order', 'created_at',
|
||||
'id',
|
||||
'owner_id',
|
||||
'name',
|
||||
'description',
|
||||
'color',
|
||||
'icon',
|
||||
'cover_image',
|
||||
'links',
|
||||
'sort_order',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
],
|
||||
withheld: [],
|
||||
@@ -312,8 +544,17 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
vacayPlan: {
|
||||
table: 'vacay_plans',
|
||||
columns: [
|
||||
'id', 'owner_id', 'block_weekends', 'holidays_enabled', 'holidays_region', 'school_holidays_enabled',
|
||||
'company_holidays_enabled', 'carry_over_enabled', 'created_at', 'weekend_days', 'week_start',
|
||||
'id',
|
||||
'owner_id',
|
||||
'block_weekends',
|
||||
'holidays_enabled',
|
||||
'holidays_region',
|
||||
'school_holidays_enabled',
|
||||
'company_holidays_enabled',
|
||||
'carry_over_enabled',
|
||||
'created_at',
|
||||
'weekend_days',
|
||||
'week_start',
|
||||
],
|
||||
withheld: [],
|
||||
wholeRow: true,
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
import { readEnv } from '../../../app-config';
|
||||
import { PluginActions } from '../../../db/entities/PluginActions.entity';
|
||||
import { PluginErrorLog } from '../../../db/entities/PluginErrorLog.entity';
|
||||
import { PluginSettingsFields } from '../../../db/entities/PluginSettingsFields.entity';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginActionsRepository } from '../../../db/repositories/PluginActions.repository';
|
||||
import type { PluginErrorLogRepository } from '../../../db/repositories/PluginErrorLog.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { UnitOfWork } from '../../database/unit-of-work';
|
||||
import { discoverPlugins, type DiscoveryRepos } from '../install/discovery';
|
||||
import { bypassedRange, hostSatisfies, hostVersion, normalizedHost, trekRangeBypassed, warnRangeBypass } from '../install/host-compat';
|
||||
import {
|
||||
bypassedRange,
|
||||
hostSatisfies,
|
||||
hostVersion,
|
||||
normalizedHost,
|
||||
trekRangeBypassed,
|
||||
warnRangeBypass,
|
||||
} from '../install/host-compat';
|
||||
import type { TrekRangeBypass } from '../install/host-compat';
|
||||
import type { PluginDependency } from '../install/manifest';
|
||||
import { parseJsonText, parseManifest } from '../install/manifest';
|
||||
@@ -8,27 +24,18 @@ import { scanForNativeBinaries } from '../install/native-scan';
|
||||
import { extractArchive } from '../install/safe-extract';
|
||||
import { safeDownload, sha256Matches } from '../install/safe-fetch';
|
||||
import { verifyAuthorSignature, SignatureError } from '../install/verify-signature';
|
||||
import { MCP_TOOLS_MAX, TOOL_DESCRIPTION_MAX, TOOL_TITLE_MAX } from '../mcp-tool-schema';
|
||||
import { pluginCodeDir, pluginsCodeRoot, pluginsDataRoot } from '../paths';
|
||||
import { poiCategoriesFrom } from '../poi-categories';
|
||||
import { clearUpdateBlock, isSignatureCode, setUpdateBlock, RETRUSTABLE_CODE } from '../signature-status';
|
||||
import { Injectable, Optional } from '@nestjs/common';
|
||||
import { sanitiseAssistantText } from '../text-sanitize';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Plugins } from '../../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import { PluginActions } from '../../../db/entities/PluginActions.entity';
|
||||
import type { PluginActionsRepository } from '../../../db/repositories/PluginActions.repository';
|
||||
import { PluginSettingsFields } from '../../../db/entities/PluginSettingsFields.entity';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import { PluginErrorLog } from '../../../db/entities/PluginErrorLog.entity';
|
||||
import type { PluginErrorLogRepository } from '../../../db/repositories/PluginErrorLog.repository';
|
||||
import { UnitOfWork } from '../../database/unit-of-work';
|
||||
import { Injectable, Optional } from '@nestjs/common';
|
||||
import type { PluginPoiCategory } from '@trek/shared';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import semver from 'semver';
|
||||
import { MCP_TOOLS_MAX, TOOL_DESCRIPTION_MAX, TOOL_TITLE_MAX } from '../mcp-tool-schema';
|
||||
import { sanitiseAssistantText } from '../text-sanitize';
|
||||
import { poiCategoriesFrom } from '../poi-categories';
|
||||
import type { PluginPoiCategory } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* TREK-side of the plugin registry (#plugins, M5). Fetches the single aggregated
|
||||
@@ -201,7 +208,13 @@ export class PluginRegistryService {
|
||||
|
||||
private get discoveryRepos(): DiscoveryRepos {
|
||||
if (!this.uow) throw new Error('UnitOfWork not provided — tests that exercise plugin discovery must pass one');
|
||||
return { plugins: this.plugins, actions: this.pluginActions, settingsFields: this.pluginSettingsFields, errorLog: this.pluginErrorLog, uow: this.uow };
|
||||
return {
|
||||
plugins: this.plugins,
|
||||
actions: this.pluginActions,
|
||||
settingsFields: this.pluginSettingsFields,
|
||||
errorLog: this.pluginErrorLog,
|
||||
uow: this.uow,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -349,7 +362,8 @@ export class PluginRegistryService {
|
||||
publishedAt: latest?.publishedAt ?? null,
|
||||
requiredAddons: latest?.requiredAddons ?? [],
|
||||
pluginDependencies: latest?.pluginDependencies ?? [],
|
||||
screenshotUrl: entry.screenshotUrl ?? (latest ? rawFileUrl(entry.repo, latest.commitSha, 'docs/screenshot.png') : null),
|
||||
screenshotUrl:
|
||||
entry.screenshotUrl ?? (latest ? rawFileUrl(entry.repo, latest.commitSha, 'docs/screenshot.png') : null),
|
||||
signed: !!entry.authorPublicKey && !!latest?.signature,
|
||||
authorPublicKey: entry.authorPublicKey ?? null,
|
||||
// The version picker's data: every published version with its OWN server-computed
|
||||
@@ -481,7 +495,8 @@ export class PluginRegistryService {
|
||||
try {
|
||||
await this.verifySignatureAndTofu(id, bytes, entry, ver, opts?.retrustKey);
|
||||
} catch (e) {
|
||||
if (e instanceof RegistryError && isSignatureCode(e.code)) await setUpdateBlock(this.plugins, id, e.code, e.message, ver.version);
|
||||
if (e instanceof RegistryError && isSignatureCode(e.code))
|
||||
await setUpdateBlock(this.plugins, id, e.code, e.message, ver.version);
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -607,7 +622,13 @@ export class PluginRegistryService {
|
||||
* binaries) — only the registry sha256/signature checks are absent, because a
|
||||
* sideload has no registry entry. Throws (and self-cleans staging) on failure.
|
||||
*/
|
||||
stageUpload(bytes: Buffer): { id: string; version: string; root: string; stagingDir: string; trekRangeBypassed: TrekRangeBypass | null } {
|
||||
stageUpload(bytes: Buffer): {
|
||||
id: string;
|
||||
version: string;
|
||||
root: string;
|
||||
stagingDir: string;
|
||||
trekRangeBypassed: TrekRangeBypass | null;
|
||||
} {
|
||||
if (bytes.length > MAX_UPLOAD_BYTES) throw new RegistryError('archive exceeds the 50MB limit');
|
||||
const stagingDir = path.join(pluginsDataRoot(), '.staging', `upload-${Date.now()}`);
|
||||
try {
|
||||
|
||||
@@ -84,8 +84,7 @@ function expandV6(ip: string): number[] | null {
|
||||
if (halves.length > 2) return null;
|
||||
const head = halves[0] ? halves[0].split(':') : [];
|
||||
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
||||
const groups =
|
||||
halves.length === 2 ? [...head, ...new Array(8 - head.length - tail.length).fill('0'), ...tail] : head;
|
||||
const groups = halves.length === 2 ? [...head, ...new Array(8 - head.length - tail.length).fill('0'), ...tail] : head;
|
||||
if (groups.length !== 8) return null;
|
||||
const nums = groups.map((x) => (x === '' ? Number.NaN : Number.parseInt(x, 16)));
|
||||
return nums.some((n) => !Number.isInteger(n) || n < 0 || n > 0xffff) ? null : nums;
|
||||
|
||||
@@ -9,15 +9,29 @@
|
||||
* MUST NOT import any privileged server module (db, config, websocket). Its only
|
||||
* imports are the pure protocol + SDK.
|
||||
*/
|
||||
|
||||
import path from 'node:path';
|
||||
import net from 'node:net';
|
||||
import dns from 'node:dns';
|
||||
import dgram from 'node:dgram';
|
||||
import { createRequire } from 'node:module';
|
||||
import { createPluginContext, definePlugin, PLUGIN_API_VERSION, type ChildTransport, type PluginContext, type PluginDefinition } from './plugin-sdk';
|
||||
import { isBlockedIp, makeHostAllow, classifyConnect, unwrapConnectArgs, dgramSendTarget, dgramConnectTarget } from './egress-policy';
|
||||
import type { Envelope, RpcError } from '../protocol/envelope';
|
||||
import {
|
||||
isBlockedIp,
|
||||
makeHostAllow,
|
||||
classifyConnect,
|
||||
unwrapConnectArgs,
|
||||
dgramSendTarget,
|
||||
dgramConnectTarget,
|
||||
} from './egress-policy';
|
||||
import {
|
||||
createPluginContext,
|
||||
definePlugin,
|
||||
PLUGIN_API_VERSION,
|
||||
type ChildTransport,
|
||||
type PluginContext,
|
||||
type PluginDefinition,
|
||||
} from './plugin-sdk';
|
||||
|
||||
import dgram from 'node:dgram';
|
||||
import dns from 'node:dns';
|
||||
import { createRequire } from 'node:module';
|
||||
import net from 'node:net';
|
||||
import path from 'node:path';
|
||||
|
||||
const pluginId = process.argv[2] || process.env.TREK_PLUGIN_ID || 'unknown';
|
||||
const pluginDir = process.argv[3] || '';
|
||||
@@ -33,8 +47,7 @@ let seq = 0;
|
||||
// Capture the raw IPC write ONCE, before installIpcGuard() locks `process.send`
|
||||
// to a throwing stub. The transport keeps sending through this closure; plugin
|
||||
// code no longer has any path to the channel. See installIpcGuard().
|
||||
const realSend: (msg: Envelope) => void =
|
||||
typeof process.send === 'function' ? process.send.bind(process) : () => {};
|
||||
const realSend: (msg: Envelope) => void = typeof process.send === 'function' ? process.send.bind(process) : () => {};
|
||||
function send(msg: Envelope): void {
|
||||
realSend(msg);
|
||||
}
|
||||
@@ -94,7 +107,8 @@ function functionsOf(impl: unknown): string[] {
|
||||
try {
|
||||
for (let o: object | null = impl; o && o !== Object.prototype; o = Object.getPrototypeOf(o) as object | null) {
|
||||
for (const key of Object.getOwnPropertyNames(o)) {
|
||||
if (key !== 'constructor' && typeof Object.getOwnPropertyDescriptor(o, key)?.value === 'function') names.add(key);
|
||||
if (key !== 'constructor' && typeof Object.getOwnPropertyDescriptor(o, key)?.value === 'function')
|
||||
names.add(key);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -142,7 +156,11 @@ async function boot(config: Record<string, unknown>): Promise<void> {
|
||||
// synchronous: the host never asks the child what tools it has, it
|
||||
// intersects this with the signed manifest.
|
||||
const mcpTools = (def.hooks?.mcpToolProvider?.tools ?? []).filter((t) => typeof t === 'string');
|
||||
send({ k: 'evt', topic: 'loaded', data: { routes, jobs, hooks, hookFns, events, exports: exportNames, subscriptions, mcpTools } });
|
||||
send({
|
||||
k: 'evt',
|
||||
topic: 'loaded',
|
||||
data: { routes, jobs, hooks, hookFns, events, exports: exportNames, subscriptions, mcpTools },
|
||||
});
|
||||
activated = true; // past load: a later async throw is a runtime CRASH, not a load failure
|
||||
// An immediate first heartbeat confirms liveness without waiting a full interval.
|
||||
send({ k: 'evt', topic: 'heartbeat', data: { rss: process.memoryUsage().rss } });
|
||||
@@ -372,8 +390,14 @@ function installIpcGuard(): void {
|
||||
const GUARDED = new Set(['message', 'internalMessage']);
|
||||
const ee = process as unknown as Record<string, (...a: unknown[]) => unknown>;
|
||||
const emitterMethods = [
|
||||
'on', 'addListener', 'prependListener', 'once', 'prependOnceListener',
|
||||
'off', 'removeListener', 'removeAllListeners',
|
||||
'on',
|
||||
'addListener',
|
||||
'prependListener',
|
||||
'once',
|
||||
'prependOnceListener',
|
||||
'off',
|
||||
'removeListener',
|
||||
'removeAllListeners',
|
||||
] as const;
|
||||
for (const m of emitterMethods) {
|
||||
const real = ee[m].bind(process);
|
||||
@@ -428,16 +452,21 @@ function installEgressGuard(egress: string[]): void {
|
||||
for (const name of ['binding', '_linkedBinding'] as const) {
|
||||
try {
|
||||
Object.defineProperty(process, name, {
|
||||
value: () => { throw new Error(`egress: process.${name} is disabled for plugins`); },
|
||||
writable: false, configurable: false,
|
||||
value: () => {
|
||||
throw new Error(`egress: process.${name} is disabled for plugins`);
|
||||
},
|
||||
writable: false,
|
||||
configurable: false,
|
||||
});
|
||||
} catch { /* already locked / non-configurable */ }
|
||||
} catch {
|
||||
/* already locked / non-configurable */
|
||||
}
|
||||
}
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
if (typeof realFetch === 'function') {
|
||||
globalThis.fetch = ((input: unknown, init?: unknown) => {
|
||||
const url = typeof input === 'string' ? input : (input as { url?: string })?.url ?? String(input);
|
||||
const url = typeof input === 'string' ? input : ((input as { url?: string })?.url ?? String(input));
|
||||
let host: string;
|
||||
try {
|
||||
host = new URL(url).hostname.replace(/^\[/, '').replace(/\]$/, '');
|
||||
@@ -467,7 +496,9 @@ function installEgressGuard(egress: string[]): void {
|
||||
const list = Array.isArray(address) ? address : [{ address: address as string }];
|
||||
for (const a of list) {
|
||||
if (blockPrivate && isBlockedIp((a as { address: string }).address)) {
|
||||
return cb(new Error(`egress: ${hostname} resolves to a blocked address (${(a as { address: string }).address})`));
|
||||
return cb(
|
||||
new Error(`egress: ${hostname} resolves to a blocked address (${(a as { address: string }).address})`),
|
||||
);
|
||||
}
|
||||
}
|
||||
cb(null, address as unknown, family);
|
||||
@@ -503,7 +534,8 @@ function installEgressGuard(egress: string[]): void {
|
||||
// Hostname: inject the resolving guard. Preserve an existing lookup by
|
||||
// wrapping the args' options object.
|
||||
const first = args[0];
|
||||
const options = first && typeof first === 'object' ? { ...(first as object) } : { host: target.host, port: args[0] };
|
||||
const options =
|
||||
first && typeof first === 'object' ? { ...(first as object) } : { host: target.host, port: args[0] };
|
||||
(options as { lookup?: unknown }).lookup = guardedLookup;
|
||||
const rest = first && typeof first === 'object' ? args.slice(1) : args.slice(typeof args[1] === 'string' ? 2 : 1);
|
||||
return realConnect.call(this, options, ...rest);
|
||||
@@ -538,7 +570,10 @@ function installEgressGuard(egress: string[]): void {
|
||||
// a private/metadata address is refused (the TCP path's rebind backstop, for UDP).
|
||||
const injectLookup = (arg: unknown): { type?: unknown; lookup: unknown } =>
|
||||
typeof arg === 'string' ? { type: arg, lookup: guardedLookup } : { ...(arg as object), lookup: guardedLookup };
|
||||
const dgramApi = dgram as unknown as { createSocket: (...a: unknown[]) => unknown; Socket: new (o?: unknown, cb?: unknown) => unknown };
|
||||
const dgramApi = dgram as unknown as {
|
||||
createSocket: (...a: unknown[]) => unknown;
|
||||
Socket: new (o?: unknown, cb?: unknown) => unknown;
|
||||
};
|
||||
const realCreateSocket = dgramApi.createSocket;
|
||||
dgramApi.createSocket = function (this: unknown, ...args: unknown[]): unknown {
|
||||
args[0] = injectLookup(args[0]);
|
||||
@@ -553,7 +588,11 @@ function installEgressGuard(egress: string[]): void {
|
||||
|
||||
// Lock the wrapped choke points so a plugin can't restore the originals.
|
||||
const lock = (obj: object, key: string, value: unknown) => {
|
||||
try { Object.defineProperty(obj, key, { value, writable: false, configurable: false }); } catch { /* noop */ }
|
||||
try {
|
||||
Object.defineProperty(obj, key, { value, writable: false, configurable: false });
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
};
|
||||
lock(proto, 'connect', proto.connect);
|
||||
lock(dgramProto, 'send', dgramProto.send);
|
||||
@@ -566,8 +605,20 @@ function installEgressGuard(egress: string[]): void {
|
||||
// itself must be a declared host. Covers the callback module fns, the promise
|
||||
// API, and per-Resolver instances (which share Resolver.prototype).
|
||||
const DNS_METHODS = [
|
||||
'lookup', 'resolve', 'resolve4', 'resolve6', 'resolveAny', 'resolveCaa', 'resolveCname',
|
||||
'resolveMx', 'resolveNaptr', 'resolveNs', 'resolvePtr', 'resolveSoa', 'resolveSrv', 'resolveTxt',
|
||||
'lookup',
|
||||
'resolve',
|
||||
'resolve4',
|
||||
'resolve6',
|
||||
'resolveAny',
|
||||
'resolveCaa',
|
||||
'resolveCname',
|
||||
'resolveMx',
|
||||
'resolveNaptr',
|
||||
'resolveNs',
|
||||
'resolvePtr',
|
||||
'resolveSoa',
|
||||
'resolveSrv',
|
||||
'resolveTxt',
|
||||
];
|
||||
const gateDnsMethods = (obj: Record<string, unknown> | undefined): void => {
|
||||
if (!obj) return;
|
||||
@@ -589,7 +640,8 @@ function installEgressGuard(egress: string[]): void {
|
||||
gateDnsMethods(dns.promises as unknown as Record<string, unknown>);
|
||||
const resolverProto = (dns as unknown as { Resolver?: { prototype: Record<string, unknown> } }).Resolver?.prototype;
|
||||
gateDnsMethods(resolverProto);
|
||||
const promisesResolverProto = (dns.promises as unknown as { Resolver?: { prototype: Record<string, unknown> } })?.Resolver?.prototype;
|
||||
const promisesResolverProto = (dns.promises as unknown as { Resolver?: { prototype: Record<string, unknown> } })
|
||||
?.Resolver?.prototype;
|
||||
gateDnsMethods(promisesResolverProto);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,10 +21,7 @@ import type { PluginsRepository } from '../../db/repositories/Plugins.repository
|
||||
* for them, not even a disabled one.
|
||||
*/
|
||||
export type SignatureCode =
|
||||
| 'SIGNATURE_MISSING'
|
||||
| 'SIGNATURE_INCOMPLETE'
|
||||
| 'SIGNATURE_KEY_CHANGED'
|
||||
| 'SIGNATURE_INVALID';
|
||||
'SIGNATURE_MISSING' | 'SIGNATURE_INCOMPLETE' | 'SIGNATURE_KEY_CHANGED' | 'SIGNATURE_INVALID';
|
||||
|
||||
/** The one code an admin may override, via POST /api/admin/plugins/:id/retrust. */
|
||||
export const RETRUSTABLE_CODE: SignatureCode = 'SIGNATURE_KEY_CHANGED';
|
||||
@@ -67,7 +64,13 @@ export function keyFingerprint(pubkey: string | null | undefined): string | null
|
||||
* old code. A blocked update is not a broken runtime, and conflating them would
|
||||
* make the isolation-health dot lie.
|
||||
*/
|
||||
export async function setUpdateBlock(plugins: PluginsRepository, id: string, code: SignatureCode, detail: string, version: string | null): Promise<void> {
|
||||
export async function setUpdateBlock(
|
||||
plugins: PluginsRepository,
|
||||
id: string,
|
||||
code: SignatureCode,
|
||||
detail: string,
|
||||
version: string | null,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await plugins.setUpdateBlockColumns(id, code, detail, version);
|
||||
} catch {
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
import fs from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { fork, type ChildProcess } from 'node:child_process';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import { readEnv } from '../../../app-config';
|
||||
import { resolveChildEntry, pluginCodeDir, pluginRealCodeDir, pluginPermissionArgs, ensurePluginModuleType } from '../paths';
|
||||
import { HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, type Envelope, type RpcError, type RpcRequest } from '../protocol/envelope';
|
||||
import type { PluginRpcHost } from '../host/rpc-host';
|
||||
import { scheduleJobs, stopJobs, type ScheduledJob } from '../host/plugin-jobs';
|
||||
import { SNAPSHOT_GRANT, type PluginEventMeta } from '../../../plugin-event-sink';
|
||||
import { RpcRateLimiter, DEFAULT_RPC_LIMIT, TokenBucket, DEFAULT_LOG_LIMIT } from '../host/rate-limit';
|
||||
import { withRequestContext } from '../../database/request-context';
|
||||
import { traceEntry } from '../../audit/entry-trace.logger';
|
||||
import { withRequestContext } from '../../database/request-context';
|
||||
import { scheduleJobs, stopJobs, type ScheduledJob } from '../host/plugin-jobs';
|
||||
import { RpcRateLimiter, DEFAULT_RPC_LIMIT, TokenBucket, DEFAULT_LOG_LIMIT } from '../host/rate-limit';
|
||||
import type { PluginRpcHost } from '../host/rpc-host';
|
||||
import {
|
||||
resolveChildEntry,
|
||||
pluginCodeDir,
|
||||
pluginRealCodeDir,
|
||||
pluginPermissionArgs,
|
||||
ensurePluginModuleType,
|
||||
} from '../paths';
|
||||
import {
|
||||
HOOK_PERMISSION,
|
||||
USER_DATA_PERMISSION,
|
||||
EVENTS_PERMISSION,
|
||||
type Envelope,
|
||||
type RpcError,
|
||||
type RpcRequest,
|
||||
} from '../protocol/envelope';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
import { fork, type ChildProcess } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
|
||||
export interface PluginRouteInfo {
|
||||
i: number;
|
||||
@@ -124,8 +138,11 @@ export class PluginSupervisor {
|
||||
// (no persistence, so no DB writes on the broadcast fast-path), bounded per plugin
|
||||
// and TTL'd. Grants + snapshot gating are re-evaluated at replay time from the
|
||||
// CURRENT grant set, never trusted from when the event was buffered.
|
||||
private readonly pendingEvents = new Map<string, Array<{ tripId: number; event: string; meta?: PluginEventMeta; expiresAt: number }>>();
|
||||
private static readonly EVENT_BUFFER_MAX = 200; // events held per plugin (drop oldest past this)
|
||||
private readonly pendingEvents = new Map<
|
||||
string,
|
||||
Array<{ tripId: number; event: string; meta?: PluginEventMeta; expiresAt: number }>
|
||||
>();
|
||||
private static readonly EVENT_BUFFER_MAX = 200; // events held per plugin (drop oldest past this)
|
||||
private static readonly EVENT_BUFFER_TTL_MS = 15 * 60_000; // a buffered event older than this is dropped unreplayed
|
||||
|
||||
constructor(
|
||||
@@ -151,7 +168,12 @@ export class PluginSupervisor {
|
||||
}
|
||||
|
||||
/** Spawn a plugin and resolve once it reports `loaded` (or reject on load error). */
|
||||
activate(id: string, granted: ReadonlySet<string>, config: Record<string, unknown> = {}, egress: string[] = []): Promise<void> {
|
||||
activate(
|
||||
id: string,
|
||||
granted: ReadonlySet<string>,
|
||||
config: Record<string, unknown> = {},
|
||||
egress: string[] = [],
|
||||
): Promise<void> {
|
||||
const existing = this.running.get(id);
|
||||
if (existing) {
|
||||
// A live plugin (starting/active) is idempotent — already activated.
|
||||
@@ -314,7 +336,8 @@ export class PluginSupervisor {
|
||||
subscribersOf(sourceId: string, event: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const [id, sup] of this.running) {
|
||||
if (sup.status === 'active' && sup.subscriptions.some((s) => s.plugin === sourceId && s.event === event)) out.push(id);
|
||||
if (sup.status === 'active' && sup.subscriptions.some((s) => s.plugin === sourceId && s.event === event))
|
||||
out.push(id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -350,7 +373,12 @@ export class PluginSupervisor {
|
||||
const { snapshot, ...hint } = meta ?? {};
|
||||
const grant = hint.entity ? SNAPSHOT_GRANT[hint.entity] : undefined;
|
||||
const withSnapshot = snapshot !== undefined && grant !== undefined && sup.granted.has(grant);
|
||||
this.invoke(sup.id, 'invoke.event', { event, tripId, ...hint, ...(withSnapshot ? { snapshot } : {}) }, { actingUserId: undefined, timeoutMs: 5000 }).catch(() => {
|
||||
this.invoke(
|
||||
sup.id,
|
||||
'invoke.event',
|
||||
{ event, tripId, ...hint, ...(withSnapshot ? { snapshot } : {}) },
|
||||
{ actingUserId: undefined, timeoutMs: 5000 },
|
||||
).catch(() => {
|
||||
/* a subscriber that errors or times out is ignored — events are best-effort */
|
||||
});
|
||||
}
|
||||
@@ -358,7 +386,10 @@ export class PluginSupervisor {
|
||||
/** Append an event to a subscriber's bounded redelivery buffer (drop-oldest past the cap). */
|
||||
private bufferEvent(id: string, tripId: number, event: string, meta?: PluginEventMeta): void {
|
||||
let q = this.pendingEvents.get(id);
|
||||
if (!q) { q = []; this.pendingEvents.set(id, q); }
|
||||
if (!q) {
|
||||
q = [];
|
||||
this.pendingEvents.set(id, q);
|
||||
}
|
||||
q.push({ tripId, event, meta, expiresAt: Date.now() + PluginSupervisor.EVENT_BUFFER_TTL_MS });
|
||||
if (q.length > PluginSupervisor.EVENT_BUFFER_MAX) q.splice(0, q.length - PluginSupervisor.EVENT_BUFFER_MAX);
|
||||
}
|
||||
@@ -388,9 +419,11 @@ export class PluginSupervisor {
|
||||
deliverScheduled(id: string, name: string, payload: unknown): void {
|
||||
const sup = this.running.get(id);
|
||||
if (!sup || sup.status !== 'active') return;
|
||||
void this.invoke(id, 'invoke.scheduled', { name, payload }, { actingUserId: undefined, timeoutMs: 60_000 }).catch(() => {
|
||||
/* a scheduled task that errors/times out is ignored — best-effort like jobs */
|
||||
});
|
||||
void this.invoke(id, 'invoke.scheduled', { name, payload }, { actingUserId: undefined, timeoutMs: 60_000 }).catch(
|
||||
() => {
|
||||
/* a scheduled task that errors/times out is ignored — best-effort like jobs */
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -420,11 +453,19 @@ export class PluginSupervisor {
|
||||
* gated by the same hook:user-data grant. Returns the plugin's exported payload,
|
||||
* or undefined if it is inactive, ungranted, doesn't implement the hook, or errors.
|
||||
*/
|
||||
async collectUserExport(id: string, userId: number): Promise<{ ok: true; data: unknown } | { ok: false } | undefined> {
|
||||
async collectUserExport(
|
||||
id: string,
|
||||
userId: number,
|
||||
): Promise<{ ok: true; data: unknown } | { ok: false } | undefined> {
|
||||
const sup = this.running.get(id);
|
||||
if (!sup || sup.status !== 'active' || !sup.granted.has(USER_DATA_PERMISSION)) return undefined; // not applicable
|
||||
try {
|
||||
const res = (await this.invoke(id, 'invoke.exportUserData', { userId }, { actingUserId: undefined, timeoutMs: 30_000 })) as { data?: unknown } | undefined;
|
||||
const res = (await this.invoke(
|
||||
id,
|
||||
'invoke.exportUserData',
|
||||
{ userId },
|
||||
{ actingUserId: undefined, timeoutMs: 30_000 },
|
||||
)) as { data?: unknown } | undefined;
|
||||
return { ok: true, data: res?.data };
|
||||
} catch {
|
||||
return { ok: false }; // errored/timed out — the caller flags this as incomplete, not "no data"
|
||||
@@ -583,7 +624,12 @@ export class PluginSupervisor {
|
||||
// sweep. A throttled call is refused with HOST_ERROR (retryable) rather than
|
||||
// executed; a legitimate plugin never hits the generous burst.
|
||||
if (!sup.rpcLimiter.tryAcquire(Date.now())) {
|
||||
sup.child?.send({ k: 'res', id: req.id, ok: false, error: { code: 'HOST_ERROR', message: 'rate limit exceeded — slow down ctx.* calls' } } satisfies RpcError);
|
||||
sup.child?.send({
|
||||
k: 'res',
|
||||
id: req.id,
|
||||
ok: false,
|
||||
error: { code: 'HOST_ERROR', message: 'rate limit exceeded — slow down ctx.* calls' },
|
||||
} satisfies RpcError);
|
||||
return;
|
||||
}
|
||||
const inv = req.params as { _inv?: unknown } | undefined;
|
||||
@@ -617,7 +663,12 @@ export class PluginSupervisor {
|
||||
// refusal a few lines up, THEN throw for host-side visibility. The
|
||||
// dispatch still never runs either way — this only changes whether
|
||||
// the caller ever hears back.
|
||||
sup.child?.send({ k: 'res', id: req.id, ok: false, error: { code: 'HOST_ERROR', message: 'no ORM available to build a request context' } } satisfies RpcError);
|
||||
sup.child?.send({
|
||||
k: 'res',
|
||||
id: req.id,
|
||||
ok: false,
|
||||
error: { code: 'HOST_ERROR', message: 'no ORM available to build a request context' },
|
||||
} satisfies RpcError);
|
||||
throw new Error('PluginSupervisor: no ORM available to build a request context for this RPC dispatch');
|
||||
}
|
||||
// One unit of work per RPC, with its own correlation id and one log line;
|
||||
@@ -650,7 +701,11 @@ export class PluginSupervisor {
|
||||
if (msg.k === 'evt') {
|
||||
switch (msg.topic) {
|
||||
case 'hello':
|
||||
sup.child?.send({ k: 'evt', topic: 'init', data: { config: sup.config, egress: sup.egress } } satisfies Envelope);
|
||||
sup.child?.send({
|
||||
k: 'evt',
|
||||
topic: 'init',
|
||||
data: { config: sup.config, egress: sup.egress },
|
||||
} satisfies Envelope);
|
||||
break;
|
||||
case 'heartbeat': {
|
||||
sup.lastBeat = Date.now();
|
||||
@@ -667,8 +722,13 @@ export class PluginSupervisor {
|
||||
if (this.running.get(sup.id) !== sup || sup.status !== 'starting') break;
|
||||
sup.lastBeat = Date.now();
|
||||
const d = msg.data as {
|
||||
routes?: PluginRouteInfo[]; jobs?: ScheduledJob[]; hooks?: string[]; hookFns?: unknown; events?: string[];
|
||||
exports?: string[]; subscriptions?: Array<{ plugin: string; event: string }>;
|
||||
routes?: PluginRouteInfo[];
|
||||
jobs?: ScheduledJob[];
|
||||
hooks?: string[];
|
||||
hookFns?: unknown;
|
||||
events?: string[];
|
||||
exports?: string[];
|
||||
subscriptions?: Array<{ plugin: string; event: string }>;
|
||||
mcpTools?: string[];
|
||||
};
|
||||
sup.routes = d.routes ?? [];
|
||||
@@ -681,7 +741,10 @@ export class PluginSupervisor {
|
||||
sup.exports = Array.isArray(d.exports) ? d.exports.filter((e): e is string => typeof e === 'string') : [];
|
||||
sup.mcpTools = Array.isArray(d.mcpTools) ? d.mcpTools.filter((t): t is string => typeof t === 'string') : [];
|
||||
sup.subscriptions = Array.isArray(d.subscriptions)
|
||||
? d.subscriptions.filter((s): s is { plugin: string; event: string } => !!s && typeof s.plugin === 'string' && typeof s.event === 'string')
|
||||
? d.subscriptions.filter(
|
||||
(s): s is { plugin: string; event: string } =>
|
||||
!!s && typeof s.plugin === 'string' && typeof s.event === 'string',
|
||||
)
|
||||
: [];
|
||||
this.clearActivationTimer(sup);
|
||||
this.setStatus(sup, 'active');
|
||||
@@ -690,7 +753,9 @@ export class PluginSupervisor {
|
||||
// egress. Wrapped so a scheduling hiccup can never break activation.
|
||||
try {
|
||||
sup.jobTasks = scheduleJobs(sup.granted, sup.jobs, (jobId) => {
|
||||
void this.invoke(sup.id, 'invoke.job', { jobId }, { actingUserId: undefined, timeoutMs: 60_000 }).catch(() => {});
|
||||
void this.invoke(sup.id, 'invoke.job', { jobId }, { actingUserId: undefined, timeoutMs: 60_000 }).catch(
|
||||
() => {},
|
||||
);
|
||||
});
|
||||
} catch {
|
||||
/* a scheduler error must never stop a plugin from going live */
|
||||
|
||||
@@ -32,7 +32,10 @@ export function stripEmoji(s: string): string {
|
||||
// run is only ever walked from its own start — plugin text must not make ` +$` restart
|
||||
// inside every space of a long one.
|
||||
if (stripped === s) return s;
|
||||
return stripped.replace(/[^\S\r\n]{2,}/g, ' ').replace(/(^|[^ ]) +$/gm, '$1').trim();
|
||||
return stripped
|
||||
.replace(/[^\S\r\n]{2,}/g, ' ')
|
||||
.replace(/(^|[^ ]) +$/gm, '$1')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** True if the string contains at least one emoji — used by the dev/validate warnings. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PluginIdPermissionRow } from '../../db/repositories/Plugins.repository';
|
||||
import type { PluginUserErasureQueueRepository } from '../../db/repositories/PluginUserErasureQueue.repository';
|
||||
import type { PluginIdPermissionRow } from '../../db/repositories/Plugins.repository';
|
||||
|
||||
/**
|
||||
* Enqueue a durable GDPR erasure (`INSERT OR IGNORE`, idempotent) for every
|
||||
|
||||
Reference in New Issue
Block a user