Split PluginsModule into four, and gate coverage per domain

PluginsModule was 21 controllers, 24 domain imports and 10 providers in one
class, which made it the hub most of the Nest graph ran through: AdminModule
imported it for a single cascade-disable call and inherited all of it. It is now
PluginsRuntimeModule (supervisor, capability router, hook contracts),
PluginContributionsModule (the 14 read-only hook controllers, moved to
contributions/), PluginOAuthModule (the credential leaf, moved to oauth/) and a
composition root that keeps the install and delivery controllers. AdminModule
imports the runtime alone.

The three plugin files that reached for the db singleton alongside the injected
DatabaseService no longer do. plugin-host-state and signature-status take the
connection from the caller, and the three per-user settings functions that were
bare exports 'so the RPC host wiring can call them directly' are now
PluginUserSettingsService - the host wiring is providers, so it injects them.

Coverage moves from one repo-wide 80% to a per-domain ratchet. The single number
let a well-covered domain subsidise a thin one: booking-import sits at 50% and
integrations at 20%, and the aggregate still cleared the bar, so either could
have lost another ten points unnoticed. Each domain now carries its own measured
floor, regenerated by scripts/coverage-thresholds.mjs.

Two test-side findings on the way:

expect(undefined).toContain(SomeClass) PASSES in this vitest version - it only
throws for a string needle. Every '<X> is listed in its module providers' guard
was written that way, so all twelve of them silently stopped guarding the moment
their class moved. They go through expectRegisteredProvider now, which asserts
the array shape first.

The atlas region test paid for the one-off decompression of the multi-MB admin1
bundle inside its own 5s budget, which is why it failed under load and passed
alone. The bundle is warmed in beforeAll instead.
This commit is contained in:
Maurice
2026-08-09 18:20:54 +02:00
committed by Maurice
parent dc81a5365e
commit 6680bc7c74
66 changed files with 649 additions and 326 deletions
@@ -0,0 +1,102 @@
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/atlas-layers — country tint layers plugins draw over the Atlas world
* map via the `atlasLayerProvider` hook (wishlists, travel advisories, …).
* USER-SCOPED: there is no tripId — the layers are for the signed-in user, and
* the hook receives no target parameter (the acting user is host-bound to the
* invocation, so the plugin cannot ask for anyone else's map). No addon gate,
* matching the other /api/addons/atlas routes, which have none either.
*
* DECLARATIVE ONLY — a plugin never touches the map canvas; it returns country
* codes + a tone the host tints. Everything is normalized here: codes must be
* ISO-3166 alpha-2 (uppercase-coerced, anything else dropped), tone is
* enum-whitelisted, strings are String()-coerced + length-capped, and the
* layer/country counts are capped per plugin.
*/
type Tone = 'default' | 'success' | 'warn' | 'danger';
interface AtlasLayerCountry {
code: string;
tone: Tone;
label?: string;
}
interface AtlasLayer {
pluginId: string;
id: string;
name?: string;
countries: AtlasLayerCountry[];
}
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
const CODE_RE = /^[A-Z]{2}$/;
const MAX_LAYERS = 3; // per provider
const MAX_COUNTRIES = 300; // per layer — bounds the render cost
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
function normalizeCountries(raw: unknown): AtlasLayerCountry[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: AtlasLayerCountry[] = [];
for (const c of list) {
if (out.length >= MAX_COUNTRIES) break;
if (!c || typeof c !== 'object') continue;
const code = String(c.code ?? '').toUpperCase();
if (!CODE_RE.test(code)) continue; // not an alpha-2 code — nothing to tint
out.push({
code,
// Check the raw value (not String(c.tone)) so a non-string tone can't slip through
// its toString() and be emitted raw through the Tone-typed API.
tone: TONES.has(c.tone as string) ? (c.tone as Tone) : 'default',
label: c.label != null ? cap(c.label, 80) : undefined,
});
}
return out;
}
function normalize(pluginId: string, raw: unknown): AtlasLayer[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: AtlasLayer[] = [];
for (const l of list) {
if (out.length >= MAX_LAYERS) break;
if (!l || typeof l !== 'object') continue;
const id = cap(l.id, 64);
if (!id) continue; // a layer with no id can't be keyed/deduped — drop it
out.push({
pluginId,
id,
name: l.name != null ? cap(l.name, 60) : undefined,
countries: normalizeCountries(l.countries),
});
}
return out;
}
@Controller('api/atlas-layers')
@UseGuards(JwtAuthGuard)
export class AtlasLayersController {
constructor(private readonly hooks: PluginHooks) {}
@Get()
async get(@Req() req: Request & { user?: { id: number } }): Promise<{ layers: AtlasLayer[] }> {
if (!pluginsEnabled()) return { layers: [] };
const userId = req.user?.id;
if (userId == null) return { layers: [] };
const ids = this.hooks.providersOf('atlasLayerProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<AtlasLayer[]> => {
try {
const raw = await this.hooks.atlasLayers(id, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { layers: perProvider.flat() };
}
}
@@ -0,0 +1,113 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/day-schedule/:tripId — bounded time contributions plugins attach to the
* day plan via the `dayScheduleProvider` hook: "35 min charging at this stop",
* "45 min security before this flight". The planner renders them as host-drawn
* rows anchored to an itinerary item (or the start/end of a day) and folds the
* minutes into the day's route-footer total — the first hook whose output feeds
* displayed timing, which is why `minutes` is clamped to a day.
*
* Same contract as the other provider hooks: additive + fail-safe, declarative
* data only, strings sanitized + capped, counts budgeted per provider. dayIds
* are checked against the trip so a stale/hand-edited contribution can never
* anchor to another trip's day.
*/
type Tone = 'default' | 'success' | 'warn' | 'danger';
export interface DayScheduleItem {
pluginId: string;
id: string;
dayId: number;
assignmentId?: number;
reservationId?: number;
/** Where the row sits when it is not anchored to an item. */
position?: 'start' | 'end';
minutes?: number;
label: string;
tone: Tone;
}
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
const MAX_ITEMS = 60; // per provider, across the trip's days
const MAX_MINUTES = 1440; // a contribution longer than a day is nonsense data
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
// Bound the work, not just the output: an all-invalid raw array (no item ever
// increments out.length) would otherwise be iterated in full. Slice up front, well
// above any legitimate payload, mirroring the other hooks' length pre-checks.
const MAX_RAW_ITEMS = 1000;
function normalize(pluginId: string, tripDayIds: ReadonlySet<number>, raw: unknown): DayScheduleItem[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>).slice(0, MAX_RAW_ITEMS) : [];
const out: DayScheduleItem[] = [];
for (const it of list) {
if (out.length >= MAX_ITEMS) break;
if (!it || typeof it !== 'object') continue;
const id = cap(it.id, 64);
const label = cap(it.label, 120);
const dayId = Number(it.dayId);
// No id, no label, or a day outside this trip — the row is meaningless, drop it.
if (!id || !label || !Number.isInteger(dayId) || !tripDayIds.has(dayId)) continue;
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;
out.push({
pluginId,
id,
dayId,
...(assignmentId !== undefined ? { assignmentId } : {}),
...(reservationId !== undefined ? { reservationId } : {}),
// Raw-value enum check, same rationale as the marker tone guard.
...(it.position === 'start' || it.position === 'end' ? { position: it.position } : {}),
...(minutes !== undefined ? { minutes } : {}),
label,
tone: TONES.has(it.tone as string) ? (it.tone as Tone) : 'default',
});
}
return out;
}
@Controller('api/day-schedule')
@UseGuards(JwtAuthGuard)
export class DayScheduleController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':tripId')
async get(
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ items: DayScheduleItem[] }> {
if (!pluginsEnabled()) return { items: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { items: [] };
const ids = this.hooks.providersOf('dayScheduleProvider');
if (ids.length === 0) return { items: [] };
const dayRows = this.dbs.connection.prepare('SELECT id FROM days WHERE trip_id = ?').all(tripId) as Array<{ id: number }>;
const tripDayIds: ReadonlySet<number> = new Set(dayRows.map((d) => d.id));
const perProvider = await Promise.all(
ids.map(async (id): Promise<DayScheduleItem[]> => {
try {
const raw = await this.hooks.daySchedule(id, tripId, userId);
return normalize(id, tripDayIds, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { items: perProvider.flat() };
}
}
@@ -0,0 +1,202 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/day-tints/:tripId — the colours the planner paints into a day card in the
* Plan sidebar (and into the mobile day chips) via the `dayTintProvider` hook. A trip
* split into colour-coded legs — Tokyo, Kanazawa, Kyoto — becomes readable at a
* glance while scrolling the itinerary.
*
* The card exposes three separately tintable regions — the day-number badge, the
* header row, and the expanded activity list — so a plugin can mark the leg boldly on
* the badge while leaving the dense activity list plain. `tone` / `color` are the
* shorthands that fill every region a contribution does not name.
*
* A region is painted by a tone from the fixed palette or by the plugin's own
* `#rrggbb` — four tones cannot keep a twenty-leg trip's days apart. The split of
* control is: the plugin picks the hue, the host picks how strongly it lands (alpha
* per theme and per region) and clamps it into a readable lightness band, so no
* contribution can produce an unreadable card in either theme.
*
* Why this is its own hook rather than one dayScheduleProvider item per day: that
* hook is capped at MAX_ITEMS = 60 per provider, so a six-month trip would tint its
* first 60 days and silently stop — failing exactly the long multi-destination trips
* this is for. Here the natural bound is the trip's own day count, because a day
* gets at most one tint.
*
* Same contract as the other provider hooks: additive + fail-safe, declarative data
* only, strings sanitized + capped. dayIds are checked against the trip so a
* stale/hand-edited contribution can never tint another trip's day.
*/
type Tone = 'default' | 'success' | 'warn' | 'danger';
export interface DayTint {
pluginId: string;
dayId: number;
/** Per-region paint, already resolved against the contribution's shorthands. Each
* region carries EITHER a tone or a `#rrggbb` colour, never both — one region, one
* paint instruction, so the client never has to break a tie. An absent region is not
* tinted and renders exactly as it does without plugins. */
badgeTone?: Tone;
badgeColor?: string;
headerTone?: Tone;
headerColor?: string;
activityTone?: Tone;
activityColor?: string;
/** Optional tooltip on the tinted day ("Kanazawa leg"). */
label?: string;
}
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
/**
* A plugin's own colour, or undefined for anything that is not exactly six hex digits.
*
* This is a security boundary, not input tidying. The client interpolates the value
* into a `color-mix()` inside an inline `background`, and `background` is a shorthand
* that takes a comma-separated layer list — a string closing the `color-mix(` paren
* early could append a `url(...)` layer and turn everyone viewing the trip into a
* 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;
// 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
// any legitimate payload — a trip has one tint per day, and 2000 days is 5½ years.
const MAX_RAW_TINTS = 2000;
/**
* One region's tone. `undefined` means the region was not named, so the caller falls
* back to the shorthand; naming a region with a bogus value still tints it (as
* `default`) rather than silently doing nothing, because the plugin clearly asked for
* a tint there — same "unknown enum degrades, never fails the item" rule the other
* hooks use for `tone`.
*/
const region = (v: unknown): Tone | undefined =>
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 }
/**
* Resolve one region against the contribution's `tone` / `color` shorthands, in one
* order: what the region names beats the shorthand, and a colour beats a tone at the
* same level. A colour wins because it is the more specific request — and emitting
* only the winner keeps a tie out of the payload for the client to break.
*
* A region that names a colour the host cannot use (`badgeColor: 'chartreuse'`) and
* nothing else degrades to `default` rather than letting the shorthand answer for it —
* exactly what a bogus `badgeTone` already does. The plugin overrode the shorthand on
* purpose here; it just sent junk, and a silently untinted region is the harder
* failure for a plugin author to notice.
*/
function resolveRegion(
rawTone: unknown,
rawColor: unknown,
toneShorthand: Tone | undefined,
colorShorthand: string | undefined,
): RegionTint {
const color = named(rawColor) ? hex(rawColor) : undefined;
if (color) return { color };
const tone = region(rawTone);
if (tone) return { tone };
if (named(rawColor)) return { tone: 'default' };
if (colorShorthand) return { color: colorShorthand };
if (toneShorthand) return { tone: toneShorthand };
return {};
}
function normalize(pluginId: string, tripDayIds: ReadonlySet<number>, raw: unknown): DayTint[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>).slice(0, MAX_RAW_TINTS) : [];
const out: DayTint[] = [];
// One tint per day per provider — a plugin that contradicts itself gets its first
// answer taken, not its last, so the day never depends on array order downstream.
const seen = new Set<number>();
for (const it of list) {
if (!it || typeof it !== 'object') continue;
const dayId = Number(it.dayId);
// A day outside this trip, or one already tinted by this provider — drop it.
if (!Number.isInteger(dayId) || !tripDayIds.has(dayId) || seen.has(dayId)) continue;
seen.add(dayId);
const label = cap(it.label, 60);
const shTone = region(it.tone);
const shColor = hex(it.color);
const badge = resolveRegion(it.badgeTone, it.badgeColor, shTone, shColor);
const header = resolveRegion(it.headerTone, it.headerColor, shTone, shColor);
const activity = resolveRegion(it.activityTone, it.activityColor, shTone, shColor);
// An entry that names no region and carries no usable shorthand still means "tint
// this day" — the dayId is the payload, the colour is decoration. Give it the
// default tone everywhere rather than returning a contribution that paints nothing.
const painted = [badge, header, activity].filter((r) => r.tone || r.color);
if (painted.length === 0) badge.tone = header.tone = activity.tone = 'default';
const tint: DayTint = { pluginId, dayId };
if (badge.tone) tint.badgeTone = badge.tone;
if (badge.color) tint.badgeColor = badge.color;
if (header.tone) tint.headerTone = header.tone;
if (header.color) tint.headerColor = header.color;
if (activity.tone) tint.activityTone = activity.tone;
if (activity.color) tint.activityColor = activity.color;
if (label) tint.label = label;
out.push(tint);
}
return out;
}
@Controller('api/day-tints')
@UseGuards(JwtAuthGuard)
export class DayTintsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':tripId')
async get(
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ tints: DayTint[] }> {
if (!pluginsEnabled()) return { tints: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { tints: [] };
const ids = this.hooks.providersOf('dayTintProvider');
if (ids.length === 0) return { tints: [] };
const dayRows = this.dbs.connection.prepare('SELECT id FROM days WHERE trip_id = ?').all(tripId) as Array<{ id: number }>;
const tripDayIds: ReadonlySet<number> = new Set(dayRows.map((d) => d.id));
const perProvider = await Promise.all(
ids.map(async (id): Promise<DayTint[]> => {
try {
const raw = await this.hooks.dayTints(id, tripId, userId);
return normalize(id, tripDayIds, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
// Precedence across plugins: the first GRANTED provider wins a contested day.
// Promise.all preserves input order, so the flattened array is already in
// providersOf() order — keeping the first occurrence is the whole rule. This is
// deterministic, so a day can never flicker between two plugins' colours.
const claimed = new Set<number>();
const tints: DayTint[] = [];
for (const t of perProvider.flat()) {
if (claimed.has(t.dayId)) continue;
claimed.add(t.dayId);
tints.push(t);
}
return { tints };
}
}
@@ -0,0 +1,104 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JourneyDomainService } from '../../journey/journey-domain.service';
import { AddonsService } from '../../addons/addons.service';
import { ADDON_IDS } from '../../../addons';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/journal-entry-rows/:entryId — extra rows for a journal entry,
* contributed by plugins implementing the `journalEntryProvider` hook. Additive +
* fail-safe like place-details: the entry's journey must be one the caller can
* access (owner/contributor — the same gate as the journal detail routes), the
* Journey addon must be on (an off addon just yields nothing, this endpoint is
* purely additive), each provider runs host->plugin on a short timeout, and one
* that errors/times out contributes nothing.
*
* Unlike place-details, every row is NORMALIZED server-side: strings are
* String()-coerced + length-capped, the row count is capped per plugin, and a
* row url must be http/https/mailto — a javascript:/data: url rendered as an
* <a href> would be click-XSS into the journal page.
*/
interface EntryRow {
label: string;
value?: string;
url?: string;
}
interface ProviderResult {
pluginId: string;
items: EntryRow[];
}
const MAX_ROWS = 12; // per provider — bounds the card footprint
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
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;
} catch {
return undefined;
}
}
function normalize(raw: unknown): EntryRow[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: EntryRow[] = [];
for (const r of list) {
if (out.length >= MAX_ROWS) break;
if (!r || typeof r !== 'object') continue;
const label = cap(r.label, 60);
if (!label) continue; // a row without a label is meaningless — drop it
out.push({
label,
value: r.value != null ? cap(r.value, 200) : undefined,
url: safeUrl(r.url),
});
}
return out;
}
@Controller('api/journal-entry-rows')
@UseGuards(JwtAuthGuard)
export class JournalEntryRowsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
private readonly addons: AddonsService,
private readonly journey: JourneyDomainService,
) {}
@Get(':entryId')
async get(
@Param('entryId') entryIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ providers: ProviderResult[] }> {
if (!pluginsEnabled() || !this.addons.isAddonEnabled(ADDON_IDS.JOURNEY)) return { providers: [] };
const entryId = Number(entryIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(entryId) || userId == null) return { providers: [] };
// The entry's journey must be one the caller can access — same gate as a read.
const row = this.dbs.connection.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as { journey_id: number } | undefined;
if (!row || !this.journey.canAccessJourney(row.journey_id, userId)) return { providers: [] };
const ids = this.hooks.providersOf('journalEntryProvider');
const results = await Promise.all(
ids.map(async (id): Promise<ProviderResult | null> => {
try {
const raw = await this.hooks.journalRows(id, entryId, userId);
const items = normalize(raw);
return items.length > 0 ? { pluginId: id, items } : null;
} catch {
return null; // a slow / failing provider is skipped, never fatal
}
}),
);
return { providers: results.filter((r): r is ProviderResult => r !== null) };
}
}
@@ -0,0 +1,176 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/map-layers/:tripId — bounded vector overlays plugins draw on the trip map
* via the `mapLayerProvider` hook. The marker hook (#587) covers points; this one
* covers the shapes an integration needs to show a computed route, a reachable-range
* corridor or a zone: polylines, polygons and metric circles.
*
* DECLARATIVE ONLY — same contract as map markers: a plugin never runs JS on the map
* canvas, it returns geometry specs the host draws. Styling stays inside the tone
* palette; the only free knobs are clamped numerics (width/opacity/radius) and a
* dash enum, so a layer can never impersonate core UI or smuggle markup. Coordinates
* are range-checked, strings are String()-coerced + emoji-stripped + length-capped,
* and the point budget is capped per provider because every vertex is render cost.
*/
type Tone = 'default' | 'success' | 'warn' | 'danger';
type Dash = 'solid' | 'dash' | 'dot';
export interface MapLayerFeature {
type: 'polyline' | 'polygon' | 'circle';
points?: Array<[number, number]>; // [lat,lng] — polyline/polygon
center?: [number, number]; // circle
radiusM?: number; // circle, metres
tone: Tone;
width: number;
dash: Dash;
opacity: number;
fill: boolean;
label?: string;
}
export interface MapLayer {
pluginId: string;
id: string;
name?: string;
features: MapLayerFeature[];
}
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
const DASHES: ReadonlySet<string> = new Set(['solid', 'dash', 'dot']);
const MAX_LAYERS = 4; // per provider
const MAX_FEATURES = 150; // per provider, across its layers
const MAX_POINTS = 8000; // per provider — total vertex budget, bounds the render cost
const MAX_FEATURE_POINTS = 2000; // one feature can't eat the whole budget
const MAX_RADIUS_M = 2_000_000; // 2000 km — anything larger is a "tint the planet" wash
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
const clamp = (v: unknown, lo: number, hi: number, dflt: number): number => {
const n = Number(v);
return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt;
};
function readPoint(raw: unknown): [number, number] | null {
if (!Array.isArray(raw) || raw.length < 2) return null;
const lat = Number(raw[0]);
const lng = Number(raw[1]);
if (!Number.isFinite(lat) || !Number.isFinite(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
return [lat, lng];
}
function readPoints(raw: unknown, budget: number): Array<[number, number]> | null {
if (!Array.isArray(raw)) return null;
// An oversized shape is dropped whole rather than truncated — a silently clipped
// route would render as a different geometry than the plugin computed, which is
// worse than rendering nothing. Same rule for a shape that overruns the budget.
if (raw.length > MAX_FEATURE_POINTS || raw.length > budget) return null;
const out: Array<[number, number]> = [];
for (const p of raw) {
const pt = readPoint(p);
// One bad vertex invalidates the shape too, for the same reason.
if (!pt) return null;
out.push(pt);
}
return out;
}
// The normalizer bounds its OUTPUT, but a layer/feature that never validates
// (truthy id, zero valid features) doesn't advance the output counters, so an
// oversized raw array would otherwise be iterated in full on the host event loop.
// Slice the raw list up front — well above any legitimate payload — so the work,
// not just the result, is bounded (mirrors readPoints' length pre-check).
const MAX_RAW_LAYERS = 1000;
const MAX_RAW_FEATURES = 2000;
function normalize(pluginId: string, raw: unknown): MapLayer[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>).slice(0, MAX_RAW_LAYERS) : [];
const out: MapLayer[] = [];
let features = 0;
let points = 0;
for (const l of list) {
if (out.length >= MAX_LAYERS) break;
if (!l || typeof l !== 'object') continue;
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) : [];
for (const f of rawFeats) {
if (features >= MAX_FEATURES || points >= MAX_POINTS) break;
if (!f || typeof f !== 'object') continue;
const type = f.type;
// Check the RAW value against the enums (not String(...)) — same rationale as
// the marker tone guard: a toString() match must not let an object through.
const tone: Tone = TONES.has(f.tone as string) ? (f.tone as Tone) : 'default';
const dash: Dash = DASHES.has(f.dash as string) ? (f.dash as Dash) : 'solid';
const base = {
tone,
dash,
width: Math.round(clamp(f.width, 1, 8, 3)),
opacity: clamp(f.opacity, 0.05, 1, 0.8),
label: f.label != null ? cap(f.label, 80) : undefined,
};
if (type === 'polyline' || type === 'polygon') {
const min = type === 'polygon' ? 3 : 2;
const pts = readPoints(f.points, MAX_POINTS - points);
if (!pts || pts.length < min) continue;
points += pts.length;
features++;
feats.push({ ...base, type, points: pts, fill: type === 'polygon' ? f.fill !== false : false });
} else if (type === 'circle') {
const center = readPoint(f.center);
const radiusM = clamp(f.radiusM, 1, MAX_RADIUS_M, 0);
if (!center || radiusM < 1) continue;
points += 1;
features++;
feats.push({ ...base, type, center, radiusM, fill: f.fill !== false });
}
}
if (feats.length === 0) continue;
out.push({
pluginId,
id,
name: l.name != null ? cap(l.name, 60) : undefined,
features: feats,
});
}
return out;
}
@Controller('api/map-layers')
@UseGuards(JwtAuthGuard)
export class MapLayersController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':tripId')
async get(
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ layers: MapLayer[] }> {
if (!pluginsEnabled()) return { layers: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { layers: [] };
const ids = this.hooks.providersOf('mapLayerProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<MapLayer[]> => {
try {
const raw = await this.hooks.mapLayers(id, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { layers: perProvider.flat() };
}
}
@@ -0,0 +1,109 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/map-markers/:tripId — bounded markers plugins overlay on the trip map
* via the `mapMarkerProvider` hook (#587 "show bookings on map"). Additive + fail-safe
* like the other provider-hook controllers: the caller must access the trip, each
* provider runs host->plugin on a short timeout, and one that errors/times out
* contributes nothing.
*
* DECLARATIVE ONLY — a plugin never runs JS on the map canvas; it returns marker
* specs the host draws. Every field is normalized here exactly like view-contributions:
* coordinates are range-checked, strings are String()-coerced + length-capped,
* icon/tone are enum-whitelisted, the popup url must be http/https/mailto (a
* javascript:/data: url would be click-XSS), and the marker count is capped per plugin.
*/
type Tone = 'default' | 'success' | 'warn' | 'danger';
interface MapMarker {
pluginId: string;
id: string;
lat: number;
lng: number;
label?: string;
popupText?: string;
url?: string;
icon?: string;
tone: Tone;
}
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
const MAX_MARKERS = 200; // per provider — bounds the render cost
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
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;
} catch {
return undefined;
}
}
function normalize(pluginId: string, raw: unknown): MapMarker[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: MapMarker[] = [];
for (const m of list) {
if (out.length >= MAX_MARKERS) break;
if (!m || typeof m !== 'object') continue;
const lat = Number(m.lat);
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;
out.push({
pluginId,
id,
lat,
lng,
label: m.label != null ? cap(m.label, 80) : undefined,
popupText: m.popupText != null ? cap(m.popupText, 280) : undefined,
url: safeUrl(m.url),
icon: m.icon != null ? cap(m.icon, 40) : undefined,
// Check the RAW value against the enum (not String(m.tone)) — otherwise an object
// with a matching toString() passes the guard but the raw object is emitted as the
// tone, and a non-string tone crashes the client that renders it.
tone: TONES.has(m.tone as string) ? (m.tone as Tone) : 'default',
});
}
return out;
}
@Controller('api/map-markers')
@UseGuards(JwtAuthGuard)
export class MapMarkersController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':tripId')
async get(
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ markers: MapMarker[] }> {
if (!pluginsEnabled()) return { markers: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { markers: [] };
const ids = this.hooks.providersOf('mapMarkerProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<MapMarker[]> => {
try {
const raw = await this.hooks.mapMarkers(id, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { markers: perProvider.flat() };
}
}
@@ -0,0 +1,105 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/pdf-sections/:tripId — text-only sections plugins append to a trip's
* PDF export via the `pdfSectionProvider` hook. Additive + fail-safe like the
* other provider-hook controllers: the caller must access the trip, each provider
* runs host->plugin on a short timeout, and one that errors/times out contributes
* nothing.
*
* DECLARATIVE ONLY — a plugin never renders into the document; it returns plain
* strings the export escapes and lays out itself. Everything is normalized here:
* strings are String()-coerced + length-capped, paragraph/row/header counts are
* capped, table rows are clipped to the header width, and the section count is
* capped per plugin. No urls in a PDF, so there is nothing to allowlist.
*/
interface PdfTable {
headers: string[];
rows: string[][];
}
interface PdfSection {
pluginId: string;
title: string;
paragraphs: string[];
table?: PdfTable;
}
const MAX_SECTIONS = 5; // per provider — bounds the export size
const MAX_PARAGRAPHS = 20;
const MAX_HEADERS = 8;
const MAX_ROWS = 50;
const TITLE_MAX = 120;
const PARAGRAPH_MAX = 2000;
const HEADER_MAX = 60;
const CELL_MAX = 200;
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
function normalizeTable(raw: unknown): PdfTable | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const t = raw as Record<string, unknown>;
const headers = (Array.isArray(t.headers) ? t.headers : []).slice(0, MAX_HEADERS).map((h) => cap(h, HEADER_MAX));
// A table without headers has no width to clip rows to — drop it.
if (headers.length === 0) return undefined;
const rows = (Array.isArray(t.rows) ? t.rows : [])
.slice(0, MAX_ROWS)
.map((row) => (Array.isArray(row) ? row : []).slice(0, headers.length).map((c) => cap(c, CELL_MAX)));
return { headers, rows };
}
function normalize(pluginId: string, raw: unknown): PdfSection[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: PdfSection[] = [];
for (const s of list) {
if (out.length >= MAX_SECTIONS) break;
if (!s || typeof s !== 'object') continue;
const title = cap(s.title, TITLE_MAX);
if (!title) continue; // a section without a heading is meaningless — drop it
out.push({
pluginId,
title,
paragraphs: (Array.isArray(s.paragraphs) ? s.paragraphs : []).slice(0, MAX_PARAGRAPHS).map((p) => cap(p, PARAGRAPH_MAX)),
table: normalizeTable(s.table),
});
}
return out;
}
@Controller('api/pdf-sections')
@UseGuards(JwtAuthGuard)
export class PdfSectionsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':tripId')
async get(
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ sections: PdfSection[] }> {
if (!pluginsEnabled()) return { sections: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { sections: [] };
const ids = this.hooks.providersOf('pdfSectionProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<PdfSection[]> => {
try {
const raw = await this.hooks.pdfSections(id, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { sections: perProvider.flat() };
}
}
@@ -0,0 +1,97 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/place-details/:placeId — extra info for a place, contributed by plugins
* that implement the `placeDetailProvider` hook (#1429). Additive and fail-safe:
* the place must belong to a trip the caller can access, each provider is called
* host→plugin with a short timeout, and a provider that errors or times out is
* simply skipped — it never delays or breaks the place panel.
*
* Every row is NORMALIZED server-side (same as journal-entry-rows): strings are
* String()-coerced + length-capped, the row count is capped per plugin, and a
* row url must be http/https/mailto — a javascript:/data: url rendered as an
* <a href> would be click-XSS into the place panel.
*/
interface DetailItem {
label: string;
value?: string;
url?: string;
}
interface ProviderResult {
pluginId: string;
items: DetailItem[];
}
const MAX_ITEMS = 12; // per provider — bounds the panel footprint
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
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;
} catch {
return undefined;
}
}
function normalize(raw: unknown): DetailItem[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: DetailItem[] = [];
for (const r of list) {
if (out.length >= MAX_ITEMS) break;
if (!r || typeof r !== 'object') continue;
const label = cap(r.label, 60);
if (!label) continue; // a row without a label is meaningless — drop it
out.push({
label,
value: r.value != null ? cap(r.value, 200) : undefined,
url: safeUrl(r.url),
});
}
return out;
}
@Controller('api/place-details')
@UseGuards(JwtAuthGuard)
export class PlaceDetailsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':placeId')
async get(
@Param('placeId') placeIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ providers: ProviderResult[] }> {
if (!pluginsEnabled()) return { providers: [] };
const placeId = Number(placeIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(placeId) || userId == null) return { providers: [] };
// The place must belong to a trip the caller can access — same gate as a read.
const row = this.dbs.connection.prepare('SELECT trip_id FROM places WHERE id = ?').get(placeId) as { trip_id: number } | undefined;
if (!row || !this.dbs.canAccessTrip(row.trip_id, userId)) return { providers: [] };
const ids = this.hooks.providersOf('placeDetailProvider');
const results = await Promise.all(
ids.map(async (id): Promise<ProviderResult | null> => {
try {
const raw = await this.hooks.placeDetails(id, placeId, userId);
const items = normalize(raw);
return items.length > 0 ? { pluginId: id, items } : null;
} catch {
return null; // a slow / failing provider is skipped, never fatal
}
}),
);
return { providers: results.filter((r): r is ProviderResult => r !== null) };
}
}
@@ -0,0 +1,75 @@
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* Calendar events contributed by plugins that implement the `calendarSource` hook
* (needs `hook:calendar-source`). The core consumer that makes the hook LIVE:
* GET /api/plugin-calendar?start=<ISO>&end=<ISO> — aggregate events for the signed-in
* user across every calendar-source plugin, for embedding in a calendar view or an
* external subscription. Additive + fail-safe: each source is called host→plugin on a
* 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; }
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);
function normalizeEvents(pluginId: string, source: string, raw: unknown): DevEvent[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: DevEvent[] = [];
for (const e of list) {
if (out.length >= MAX_EVENTS) break;
if (!e || typeof e !== 'object') continue;
const id = cap(e.id, 256);
const title = cap(e.title, 300);
const start = isoish(e.start);
const end = isoish(e.end);
if (!id || !title || !start || !end) continue; // an event missing its core fields is dropped
out.push({ id, pluginId, source, title, start, end, allDay: e.allDay === true });
}
return out;
}
@Controller('api/plugin-calendar')
@UseGuards(JwtAuthGuard)
export class PluginCalendarController {
constructor(private readonly hooks: PluginHooks) {}
@Get()
async get(
@Query('start') start: string | undefined,
@Query('end') end: string | undefined,
@Req() req: Request & { user?: { id: number } },
): Promise<{ sources: Array<{ pluginId: string; name: string; events: DevEvent[] }> }> {
if (!pluginsEnabled()) return { sources: [] };
const userId = req.user?.id;
if (userId == null) return { sources: [] };
// Default to a generous window (90 days back → ~1 year out) when unspecified.
const s = isoish(start) ?? new Date(Date.now() - 90 * 864e5).toISOString();
const e = isoish(end) ?? new Date(Date.now() + 366 * 864e5).toISOString();
const ids = this.hooks.providersOf('calendarSource');
const results = await Promise.all(
ids.map(async (id) => {
try {
const [rawName, rawEvents] = await Promise.all([
this.hooks.calendarName(id, userId).catch(() => id),
this.hooks.calendarEvents(id, userId, s, e),
]);
const name = cap(rawName, 80) || id;
const events = normalizeEvents(id, name, rawEvents);
return events.length > 0 ? { pluginId: id, name, events } : null;
} catch {
return null;
}
}),
);
return { sources: results.filter((r): r is { pluginId: string; name: string; events: DevEvent[] } => r !== null) };
}
}
@@ -0,0 +1,50 @@
import { Module } from '@nestjs/common';
import { PluginsRuntimeModule } from '../plugins-runtime.module';
import { AddonsModule } from '../../addons/addons.module';
import { JourneyDomainModule } from '../../journey/journey-domain.module';
import { PlaceDetailsController } from './place-details.controller';
import { TripWarningsController } from './trip-warnings.controller';
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';
/**
* The read-only surface plugins contribute to the app: photos, calendar events,
* place details, trip warnings, table columns, map markers and layers, routes, day
* schedules and tints, PDF sections, atlas layers, journal entry rows, trip cards.
*
* Every one of these is the same shape — fan out over `providersOf(hook)`, call the
* hook through `PluginHooks`, normalize and cap what comes back, skip a provider that
* throws — so they belong together and nowhere else. None of them can install,
* activate or configure anything, which is why they are separated from the CRUD
* surface in PluginsModule.
*/
@Module({
imports: [PluginsRuntimeModule, AddonsModule, JourneyDomainModule],
controllers: [
PlaceDetailsController,
TripWarningsController,
ViewContributionsController,
TripCardContributionsController,
PluginPhotosController,
PluginCalendarController,
MapMarkersController,
MapLayersController,
PluginRoutesController,
DayScheduleController,
DayTintsController,
PdfSectionsController,
AtlasLayersController,
JournalEntryRowsController,
],
})
export class PluginContributionsModule {}
@@ -0,0 +1,115 @@
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* Photo sources contributed by plugins that implement the `photoProvider` hook
* (needs `hook:photo-provider`). This is the core consumer that makes the hook LIVE:
* GET /api/plugin-photos/sources — the installed providers (id + name)
* GET /api/plugin-photos/search?q=&page= — aggregate search across providers
* GET /api/plugin-photos/item?pluginId=&id= — one photo by id from one provider
* The picker fans these into its "plugin sources" tab. Additive + fail-safe: each
* provider is called host→plugin on a short timeout, one that errors/times out is
* 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; }
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. */
function imageUrl(raw: unknown): string | undefined {
if (typeof raw !== 'string' || raw === '' || raw.length > 4096) return undefined;
try {
const p = new URL(raw).protocol;
return p === 'http:' || p === 'https:' ? raw : undefined;
} catch {
return undefined;
}
}
function normalizePhotos(pluginId: string, raw: unknown): DevPhoto[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: DevPhoto[] = [];
for (const p of list) {
if (out.length >= MAX_PHOTOS) break;
if (!p || typeof p !== 'object') continue;
const id = cap(p.id, 256);
const thumb = imageUrl(p.thumbnailUrl);
const full = imageUrl(p.fullUrl);
if (!id || !thumb || !full) continue; // an unusable photo (no id / bad urls) is dropped
out.push({
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,
fullUrl: full,
takenAt: typeof p.takenAt === 'string' ? cap(p.takenAt, 40) : undefined,
});
}
return out;
}
@Controller('api/plugin-photos')
@UseGuards(JwtAuthGuard)
export class PluginPhotosController {
constructor(private readonly hooks: PluginHooks) {}
@Get('sources')
sources(): { sources: Array<{ pluginId: string }> } {
if (!pluginsEnabled()) return { sources: [] };
return { sources: this.hooks.providersOf('photoProvider').map((pluginId) => ({ pluginId })) };
}
@Get('search')
async search(
@Query('q') q: string | undefined,
@Query('page') pageRaw: string | undefined,
@Req() req: Request & { user?: { id: number } },
): Promise<{ providers: Array<{ pluginId: string; photos: DevPhoto[]; total: number; hasMore: boolean }> }> {
if (!pluginsEnabled()) return { providers: [] };
const userId = req.user?.id;
if (userId == null) return { providers: [] };
const query = cap(q, 200);
const page = Math.max(1, Math.min(1000, Number(pageRaw) || 1));
const ids = this.hooks.providersOf('photoProvider');
const results = await Promise.all(
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;
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 };
} catch {
return null;
}
}),
);
return { providers: results.filter((r): r is { pluginId: string; photos: DevPhoto[]; total: number; hasMore: boolean } => r !== null) };
}
@Get('item')
async item(
@Query('pluginId') pluginId: string | undefined,
@Query('id') id: string | undefined,
@Req() req: Request & { user?: { id: number } },
): Promise<{ photo: DevPhoto | null }> {
if (!pluginsEnabled()) return { photo: null };
const userId = req.user?.id;
if (userId == null || !pluginId || !id) return { photo: null };
if (!this.hooks.providersOf('photoProvider').includes(pluginId)) return { photo: null };
try {
const raw = await this.hooks.getPhoto(pluginId, cap(id, 256), userId);
return { photo: normalizePhotos(pluginId, [raw])[0] ?? null };
} catch {
return { photo: null };
}
}
}
@@ -0,0 +1,200 @@
import { Body, Controller, Param, Post, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import type Database from 'better-sqlite3';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* POST /api/plugin-routes/:pluginId/:profileId — ask ONE routeProvider plugin to
* route the given waypoints under one of its declared profiles (an EV profile with
* charging stops, a scenic profile, …). Unlike the fan-out hooks this is targeted:
* the planner's route toggle names a specific plugin profile, so exactly that
* provider is invoked.
*
* The route result is data the client renders exactly like an OSRM response:
* geometry + per-leg distance/duration + optional via points (charging stops).
* Everything is normalized here — coordinates range-checked, the leg list forced
* to exactly waypoints-1 entries (anything else means the plugin routed a
* different request than asked), text emoji-stripped + capped, counts budgeted.
* A failure returns { route: null } so the client falls back to straight lines,
* mirroring how an OSRM outage degrades.
*
* Routing may call an external solver through the plugin's declared egress, so
* the invoke timeout is 20 s — well above the 5 s of the render-blocking hooks;
* the client shows the straight-line route until the result lands.
*/
type Tone = 'default' | 'success' | 'warn' | 'danger';
interface RouteWaypointIn {
lat: number;
lng: number;
name?: string;
placeId?: number;
}
interface RouteLegOut {
distance: number;
duration: number;
note?: string;
}
interface RouteViaOut {
lat: number;
lng: number;
label?: string;
tone: Tone;
dwellSeconds?: number;
}
export interface PluginRouteOut {
pluginId: string;
profile: string;
coordinates: Array<[number, number]>;
distance: number;
duration: number;
legs: RouteLegOut[];
viaPoints: RouteViaOut[];
}
const TONES: ReadonlySet<string> = new Set(['default', 'success', 'warn', 'danger']);
const PROFILE_RE = /^[a-z][a-z0-9-]{0,23}$/;
const MAX_WAYPOINTS = 30;
const MAX_COORDINATES = 10_000; // vertex budget for the returned geometry
const MAX_VIAS = 40;
const MAX_DWELL_S = 86_400; // a "stop" longer than a day is nonsense data
const cap = (v: unknown, n: number): string => stripEmoji(String(v ?? '')).slice(0, n);
function validCoord(lat: unknown, lng: unknown): boolean {
const a = Number(lat);
const b = Number(lng);
return Number.isFinite(a) && Number.isFinite(b) && a >= -90 && a <= 90 && b >= -180 && b <= 180;
}
/** The caller's waypoint list — invalid input is a client bug, answered with null. */
function readWaypoints(raw: unknown): RouteWaypointIn[] | null {
if (!Array.isArray(raw) || raw.length < 2 || raw.length > MAX_WAYPOINTS) return null;
const out: RouteWaypointIn[] = [];
for (const w of raw as Array<Record<string, unknown>>) {
if (!w || typeof w !== 'object' || !validCoord(w.lat, w.lng)) return null;
const name = w.name != null ? cap(w.name, 120) : undefined;
const placeId = Number.isInteger(w.placeId) ? (w.placeId as number) : undefined;
out.push({ lat: Number(w.lat), lng: Number(w.lng), ...(name ? { name } : {}), ...(placeId !== undefined ? { placeId } : {}) });
}
return out;
}
function nonNeg(v: unknown): number | null {
const n = Number(v);
return Number.isFinite(n) && n >= 0 ? n : null;
}
/** The plugin's answer — a malformed route is rejected whole (null), never patched. */
function normalize(pluginId: string, profile: string, waypointCount: number, raw: unknown): PluginRouteOut | null {
if (!raw || typeof raw !== 'object') return null;
const r = raw as Record<string, unknown>;
if (!Array.isArray(r.coordinates) || r.coordinates.length < 2 || r.coordinates.length > MAX_COORDINATES) return null;
const coordinates: Array<[number, number]> = [];
for (const c of r.coordinates) {
if (!Array.isArray(c) || !validCoord(c[0], c[1])) return null;
coordinates.push([Number(c[0]), Number(c[1])]);
}
const distance = nonNeg(r.distance);
const duration = nonNeg(r.duration);
if (distance == null || duration == null) return null;
// Exactly one leg per waypoint pair — a mismatched list means the plugin routed
// something other than the request, and mis-keyed legs would attach wrong times
// to the sidebar connectors.
if (!Array.isArray(r.legs) || r.legs.length !== waypointCount - 1) return null;
const legs: RouteLegOut[] = [];
for (const l of r.legs as Array<Record<string, unknown>>) {
if (!l || typeof l !== 'object') return null;
const legDistance = nonNeg(l.distance);
const legDuration = nonNeg(l.duration);
if (legDistance == null || legDuration == null) return null;
const note = l.note != null ? cap(l.note, 120) : undefined;
legs.push({ distance: legDistance, duration: legDuration, ...(note ? { note } : {}) });
}
// Via points are decorative (charging stops on the drawn route) — a bad entry
// is dropped individually, it can't invalidate the route. Slice the raw array so
// an all-invalid list can't force unbounded iteration (the output is MAX_VIAS,
// but only valid entries advance that counter).
const viaPoints: RouteViaOut[] = [];
if (Array.isArray(r.viaPoints)) {
for (const v of (r.viaPoints as Array<Record<string, unknown>>).slice(0, MAX_VIAS * 4)) {
if (viaPoints.length >= MAX_VIAS) break;
if (!v || typeof v !== 'object' || !validCoord(v.lat, v.lng)) continue;
const dwell = Number(v.dwellSeconds);
const label = v.label != null ? cap(v.label, 80) : undefined;
viaPoints.push({
lat: Number(v.lat),
lng: Number(v.lng),
...(label ? { label } : {}),
// Raw-value enum check, same rationale as the marker tone guard.
tone: TONES.has(v.tone as string) ? (v.tone as Tone) : 'default',
...(Number.isFinite(dwell) && dwell >= 0 ? { dwellSeconds: Math.min(Math.round(dwell), MAX_DWELL_S) } : {}),
});
}
}
return { pluginId, profile, coordinates, distance, duration, legs, viaPoints };
}
@Controller('api/plugin-routes')
@UseGuards(JwtAuthGuard)
export class PluginRoutesController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Post(':pluginId/:profileId')
async route(
@Param('pluginId') pluginId: string,
@Param('profileId') profileId: string,
@Body() body: Record<string, unknown> | undefined,
@Req() req: Request & { user?: { id: number } },
): Promise<{ route: PluginRouteOut | null }> {
if (!pluginsEnabled()) return { route: null };
const userId = req.user?.id;
const tripId = Number(body?.tripId);
if (userId == null || !Number.isFinite(tripId) || !this.dbs.canAccessTrip(tripId, userId)) return { route: null };
if (!PROFILE_RE.test(profileId)) return { route: null };
const waypoints = readWaypoints(body?.waypoints);
if (!waypoints) return { route: null };
const dayIdNum = Number(body?.dayId);
const dayId = Number.isInteger(dayIdNum) ? dayIdNum : null;
// Provider gate (implements the hook AND holds the grant) + the profile must be
// one the manifest declared — re-validated from the DB row like the plugins feed,
// so a hand-edited capabilities blob can't invent profiles.
if (!this.hooks.providersOf('routeProvider').includes(pluginId)) return { route: null };
if (!declaredProfiles(this.dbs.connection, pluginId).includes(profileId)) return { route: null };
try {
const raw = await this.hooks.route(pluginId, { tripId, dayId, profile: profileId, waypoints }, userId);
return { route: normalize(pluginId, profileId, waypoints.length, raw) };
} catch {
return { route: null }; // slow / failing provider — client falls back to straight lines
}
}
}
function declaredProfiles(conn: Database.Database, pluginId: string): string[] {
try {
const row = conn.prepare('SELECT capabilities FROM plugins WHERE id = ?').get(pluginId) as { capabilities?: string } | undefined;
const c = JSON.parse(row?.capabilities || '{}') as { routeProfiles?: Array<{ id?: unknown }> };
if (!Array.isArray(c.routeProfiles)) return [];
return c.routeProfiles
.map((p) => (p && typeof p === 'object' && typeof p.id === 'string' ? p.id : ''))
.filter((id) => PROFILE_RE.test(id));
} catch {
return [];
}
}
@@ -0,0 +1,123 @@
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/trip-card-contributions?tripIds=1,2,3 — host-rendered badges that plugins
* implementing the `tripCardProvider` hook (#plugins) add to the dashboard trip cards.
* The dashboard passes exactly the cards it is showing; the host access-checks each
* one for the acting user before any plugin sees it, then fans out to every granted
* provider ONCE with the full id list (a card grid can hold many trips — one call per
* plugin, not one per trip).
*
* Like view-contributions, every field is NORMALIZED server-side: a contribution only
* ever crosses this boundary as bounded primitives (never HTML/markup). Strings are
* String()-coerced + length-capped, tone/icon are enum/length-bounded, the count is
* capped, and a url must be http/https/mailto — a javascript:/data: url would be
* click-XSS into the dashboard DOM. Additive + fail-safe: a slow/failing provider
* 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; }
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_BADGES_TOTAL = MAX_TRIP_IDS * MAX_BADGES_PER_TRIP; // overall abuse bound
const LABEL_MAX = 64;
const VALUE_MAX = 256;
const URL_MAX = 2048;
const ID_MAX = 64;
const ICON_MAX = 40;
const cap = (v: unknown, max: number): string => stripEmoji(String(v ?? '')).slice(0, max);
/** Allow only http/https/mailto; anything else (or an unparseable value) is dropped —
* a javascript:/data:/vbscript: URL rendered as an <a href> is click-XSS. */
function safeUrl(raw: unknown): string | undefined {
if (typeof raw !== 'string' || raw.length === 0 || raw.length > URL_MAX) return undefined;
try {
const proto = new URL(raw).protocol;
return proto === 'http:' || proto === 'https:' || proto === 'mailto:' ? raw : undefined;
} catch {
return undefined;
}
}
/** Coerce a provider's raw output to bounded badges, keeping only badges whose tripId
* is one the acting user actually asked about (a provider can't inject onto a card the
* dashboard isn't showing / the user can't access). */
function normalize(pluginId: string, raw: unknown, allowed: Set<number>): TripCardBadge[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: TripCardBadge[] = [];
const perTrip = new Map<number, number>(); // cap PER card, not across the whole grid
for (const c of list) {
if (out.length >= MAX_BADGES_TOTAL) break;
if (!c || typeof c !== 'object') continue;
const tripId = typeof c.tripId === 'number' && Number.isFinite(c.tripId) ? c.tripId : undefined;
const id = cap(c.id, ID_MAX);
const label = cap(c.label, LABEL_MAX);
if (tripId === undefined || !allowed.has(tripId) || !id || !label) continue;
const n = perTrip.get(tripId) ?? 0;
if (n >= MAX_BADGES_PER_TRIP) continue; // this card is full; other cards still get theirs
perTrip.set(tripId, n + 1);
out.push({
pluginId,
tripId,
id,
label,
value: c.value !== undefined && c.value !== null ? cap(c.value, VALUE_MAX) : undefined,
icon: typeof c.icon === 'string' && c.icon ? cap(c.icon, ICON_MAX) : undefined,
tone: (TONES.has(c.tone as string) ? c.tone : 'default') as Tone,
url: safeUrl(c.url),
});
}
return out;
}
@Controller('api/trip-card-contributions')
@UseGuards(JwtAuthGuard)
export class TripCardContributionsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get()
async get(
@Query('tripIds') tripIdsRaw: string | undefined,
@Req() req: Request & { user?: { id: number } },
): Promise<{ contributions: TripCardBadge[] }> {
if (!pluginsEnabled()) return { contributions: [] };
const userId = req.user?.id;
if (userId == null) return { contributions: [] };
// Parse + access-check the requested cards; only those the user can actually see
// are handed to any plugin.
const requested = (tripIdsRaw ?? '')
.split(',')
.map((s) => Number(s.trim()))
.filter((n) => Number.isInteger(n) && n > 0)
.slice(0, MAX_TRIP_IDS);
const accessible = [...new Set(requested)].filter((id) => this.dbs.canAccessTrip(id, userId));
if (accessible.length === 0) return { contributions: [] };
const allowed = new Set(accessible);
const ids = this.hooks.providersOf('tripCardProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<TripCardBadge[]> => {
try {
const raw = await this.hooks.tripCards(id, accessible, userId);
return normalize(id, raw, allowed);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { contributions: perProvider.flat() };
}
}
@@ -0,0 +1,68 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/trip-warnings/:tripId — validation/warning contributions from plugins
* that implement the `warningProvider` hook (#1429). Additive and fail-safe: the
* caller must be able to access the trip, each provider is called host→plugin with
* a short timeout, and a provider that errors or times out contributes nothing.
*/
type Level = 'info' | 'warning' | 'error';
interface Warning {
pluginId: string;
level: Level;
message: string;
dayId?: number;
placeId?: number;
}
const MAX_WARNINGS = 20; // per provider — bounds the banner
const MESSAGE_MAX = 300;
@Controller('api/trip-warnings')
@UseGuards(JwtAuthGuard)
export class TripWarningsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':tripId')
async get(
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ warnings: Warning[] }> {
if (!pluginsEnabled()) return { warnings: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { warnings: [] };
const ids = this.hooks.providersOf('warningProvider');
const perProvider = await Promise.all(
ids.map(async (id): Promise<Warning[]> => {
try {
const raw = (await this.hooks.tripWarnings(id, tripId, userId)) as unknown;
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
// Drop non-object elements BEFORE the cap — otherwise one null in the array
// throws inside map() and the catch below discards ALL of this provider's
// 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,
}));
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { warnings: perProvider.flat().filter((w) => w.message) };
}
}
@@ -0,0 +1,134 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
/**
* GET /api/view-contributions/:view/:tripId — host-rendered columns/actions that
* plugins implementing the `tableContributor` hook (#plugins) add into a native
* planner view (reservations/transports/places/day/costs/packing/files/todos). Mirrors place-details.controller (#1429):
* additive + fail-safe — the caller must access the trip, each provider runs
* host->plugin on a short timeout, and one that errors/times out contributes nothing.
*
* Unlike place-details, every field is NORMALIZED server-side: a plugin contribution
* only ever crosses this boundary as bounded primitives (never HTML/markup). Strings
* are String()-coerced + length-capped, kind/tone/icon/target are enum-whitelisted,
* per-provider counts are capped, and a column URL must be http/https/mailto — a
* javascript:/data: URL would be click-XSS into the native DOM.
*/
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; }
type Contribution = Column | Action;
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;
const LABEL_MAX = 64;
const VALUE_MAX = 256;
const URL_MAX = 2048;
const ID_MAX = 64;
const ICON_MAX = 40;
const SUB_MAX = 512;
const cap = (v: unknown, max: number): string => stripEmoji(String(v ?? '')).slice(0, max);
/** Allow only http/https/mailto; anything else (or an unparseable value) is dropped —
* a javascript:/data:/vbscript: URL rendered as an <a href> is click-XSS. */
function safeUrl(raw: unknown): string | undefined {
if (typeof raw !== 'string' || raw.length === 0 || raw.length > URL_MAX) return undefined;
try {
const proto = new URL(raw).protocol;
return proto === 'http:' || proto === 'https:' || proto === 'mailto:' ? raw : undefined;
} catch {
return undefined;
}
}
function normalize(pluginId: string, raw: unknown): Contribution[] {
const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
const out: Contribution[] = [];
// The caps are PER ENTITY (the data model is keyed by entityId) — a global cap would
// make columns vanish from every row past the first MAX_COLUMNS in a large table. A
// generous overall bound still guards against a provider returning millions of rows.
const colsPer = new Map<number, number>();
const actsPer = new Map<number, number>();
const MAX_TOTAL = 5000;
for (const c of list) {
if (out.length >= MAX_TOTAL) break;
if (!c || typeof c !== 'object') continue;
const entityId = typeof c.entityId === 'number' && Number.isFinite(c.entityId) ? c.entityId : undefined;
const id = cap(c.id, ID_MAX);
const label = cap(c.label, LABEL_MAX);
if (entityId === undefined || !id || !label) continue; // an entity-keyed contribution must have all three
const icon = typeof c.icon === 'string' && c.icon ? cap(c.icon, ICON_MAX) : undefined;
if (c.kind === 'column') {
if ((colsPer.get(entityId) ?? 0) >= MAX_COLUMNS) continue;
colsPer.set(entityId, (colsPer.get(entityId) ?? 0) + 1);
out.push({
kind: 'column',
pluginId,
entityId,
id,
label,
value: c.value !== undefined && c.value !== null ? cap(c.value, VALUE_MAX) : undefined,
url: safeUrl(c.url),
icon,
tone: (TONES.has(c.tone as string) ? c.tone : 'default') as Tone,
});
} else if (c.kind === 'action') {
if ((actsPer.get(entityId) ?? 0) >= MAX_ACTIONS) continue;
const t = c.target as Record<string, unknown> | undefined;
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) {
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
actsPer.set(entityId, (actsPer.get(entityId) ?? 0) + 1);
out.push({ kind: 'action', pluginId, entityId, id, label, icon, target });
}
}
return out;
}
@Controller('api/view-contributions')
@UseGuards(JwtAuthGuard)
export class ViewContributionsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
) {}
@Get(':view/:tripId')
async get(
@Param('view') view: string,
@Param('tripId') tripIdRaw: string,
@Req() req: Request & { user?: { id: number } },
): Promise<{ contributions: Contribution[] }> {
if (!pluginsEnabled() || !VIEWS.has(view)) return { contributions: [] };
const tripId = Number(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !this.dbs.canAccessTrip(tripId, userId)) return { contributions: [] };
const ids = this.hooks.providersOf('tableContributor');
const perProvider = await Promise.all(
ids.map(async (id): Promise<Contribution[]> => {
try {
const raw = await this.hooks.tableContributions(id, view, tripId, userId);
return normalize(id, raw);
} catch {
return []; // a slow / failing provider contributes nothing
}
}),
);
return { contributions: perProvider.flat() };
}
}