fix(plugin-sdk): validate checks apiVersion and the manifest rules exactly as an install does

The SDK accepted any number as apiVersion while the host refuses anything
but a positive integer no newer than its plugin API, a false green for an
author. The manifest patterns, sets and caps now live in the host's
protocol/manifest-rules.ts, and gen-plugin-facts writes them and
PLUGIN_API_VERSION into the SDK, so check:plugin-facts covers them. One
manifest corpus is judged by both validators in a server test (the SDK may
only be stricter, case by case), and a typecheck test holds the SDK's plugin
API types to the host child's copy, which gains rawBodyBase64.
This commit is contained in:
Maurice
2026-10-10 15:20:42 +02:00
parent 15db688586
commit 81ec7dd28d
18 changed files with 949 additions and 146 deletions
+45 -89
View File
@@ -2,14 +2,32 @@ import semver from 'semver';
import { isKnownPermission, PLUGIN_API_VERSION } from '../protocol/envelope';
import { isValidTrekRange, minTrekOf, trekRangeBypassed } from './host-compat';
import {
MCP_TOOLS_MAX,
McpToolSchemaError,
TOOL_NAME_RE,
buildToolInputSchema,
normaliseToolSchema,
sanitiseToolText,
} from '../mcp-tool-schema';
import type { NotifEventType } from '../../notifications/notification-events';
import {
ACTIONS_MAX,
ADDON_ID_RE,
CAPABILITY_NAME_RE,
EGRESS_HOST_RE,
MCP_TOOLS_MAX,
PLUGIN_CHANNEL_EVENTS,
PLUGIN_ID_RE,
PLUGIN_SEMVER_RE,
PLUGIN_TYPES,
REPLACEABLE_TABS,
RESERVED_PLUGIN_IDS,
RESERVED_SETTING_KEYS as RESERVED_SETTING_KEY_LIST,
ROUTE_PROFILE_ID_RE,
ROUTE_PROFILES_MAX,
SETTING_FIELD_KEYS,
SETTING_KEY_RE,
TOOL_NAME_RE,
TRIP_PAGE_POSITION_MAX,
WIDGET_SLOTS,
} from '../protocol/manifest-rules';
import { PLUGIN_POI_MAX_CATEGORIES, type PluginPoiCategory } from '@trek/shared';
import { readPoiCategory } from '../poi-categories';
@@ -160,24 +178,20 @@ export interface PluginManifest {
pluginDependencies: PluginDependency[];
}
const ID_RE = /^[a-z][a-z0-9-]{2,39}$/;
// Addon ids are lowercase slugs that may contain underscores (e.g. `llm_parsing`).
// Validated format-only: existence is checked at activation, so a plugin declaring
// an unknown addon still installs but can never enable (matches "allow install").
const ADDON_ID_RE = /^[a-z][a-z0-9_]{1,39}$/;
// An outbound host: an exact hostname (single-label like a `redis` sibling
// service, or a dotted FQDN) OR a `*.`-prefixed wildcard that MUST have a real
// multi-label suffix. Rejects `*`, `*.`, whole-TLD `*.com`, schemes, and any
// embedded space — all of which would otherwise widen egress or inject a CSP
// source token when the host is interpolated into connect-src.
const HOST_RE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i;
// Static path segments under /api/admin/plugins — a plugin id must never shadow them
// (id "registry" would collide with GET registry/:id vs :id/errors routing).
const RESERVED_IDS = new Set(['registry', 'install', 'rescan']);
const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
// 'trip-page' mounts the plugin's sandboxed UI as a tab inside every trip planner
// (tripId-scoped), with no dashboard presence — unlike 'page' (dashboard nav).
const TYPES = new Set(['integration', 'page', 'widget', 'trip-page']);
// The format rules themselves live in protocol/manifest-rules.ts, which
// gen-plugin-facts also writes into the SDK, so `trek-plugin validate` checks the
// same patterns and sets as this loader.
const ID_RE = PLUGIN_ID_RE;
const HOST_RE = EGRESS_HOST_RE;
const SEMVER_RE = PLUGIN_SEMVER_RE;
const RESERVED_IDS: ReadonlySet<string> = new Set(RESERVED_PLUGIN_IDS);
const TYPES: ReadonlySet<string> = new Set(PLUGIN_TYPES);
const SLOTS: ReadonlySet<string> = new Set(WIDGET_SLOTS);
const TABS: readonly string[] = REPLACEABLE_TABS;
const CHANNEL_EVENTS: readonly string[] = PLUGIN_CHANNEL_EVENTS;
const RESERVED_SETTING_KEYS: ReadonlySet<string> = new Set(RESERVED_SETTING_KEY_LIST);
export { PLUGIN_CHANNEL_EVENTS, SETTING_FIELD_KEYS };
export class ManifestError extends Error {}
@@ -335,10 +349,6 @@ function parsePluginDependencies(raw: unknown, selfId: string): PluginDependency
return out;
}
// Export function / event names exposed to other plugins. Kept to a safe
// identifier shape (dots allowed for event names like `rate.updated`).
const CAPABILITY_NAME_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/;
function parseCapabilities(raw: unknown): PluginCapabilities {
if (!raw || typeof raw !== 'object') return {};
const c = raw as Record<string, unknown>;
@@ -346,7 +356,7 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
if (c.widget && typeof c.widget === 'object') {
const w = c.widget as Record<string, unknown>;
const slot = optStr(w.slot);
if (slot && slot !== 'sidebar' && slot !== 'hero' && slot !== 'place-detail' && slot !== 'day-detail' && slot !== 'reservation-detail') throw new ManifestError(`invalid widget slot "${slot}"`);
if (slot && !SLOTS.has(slot)) throw new ManifestError(`invalid widget slot "${slot}"`);
out.widget = {
title: optStr(w.title),
defaultSize: optStr(w.defaultSize),
@@ -360,7 +370,7 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
if (!Array.isArray(tp.replaces)) throw new ManifestError('capabilities.tripPage.replaces must be an array');
const replaces: string[] = [];
for (const v of tp.replaces) {
if (typeof v !== 'string' || !REPLACEABLE_TABS.includes(v)) {
if (typeof v !== 'string' || !TABS.includes(v)) {
throw new ManifestError(`capabilities.tripPage.replaces: "${String(v)}" is not a replaceable tab (${REPLACEABLE_TABS.join(', ')})`);
}
if (!replaces.includes(v)) replaces.push(v);
@@ -368,8 +378,8 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
if (replaces.length) page.replaces = replaces;
}
if (tp.position !== undefined) {
if (typeof tp.position !== 'number' || !Number.isInteger(tp.position) || tp.position < 0 || tp.position > 50) {
throw new ManifestError('capabilities.tripPage.position must be an integer between 0 and 50');
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;
}
@@ -388,7 +398,7 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
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' || !(PLUGIN_CHANNEL_EVENTS as readonly string[]).includes(v)) {
if (typeof v !== 'string' || !CHANNEL_EVENTS.includes(v)) {
throw new ManifestError(
`capabilities.notificationChannel.events: "${String(v)}" is not a plugin-deliverable event (${PLUGIN_CHANNEL_EVENTS.join(', ')})`,
);
@@ -401,13 +411,15 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
}
if (c.routeProfiles !== undefined) {
if (!Array.isArray(c.routeProfiles)) throw new ManifestError('capabilities.routeProfiles must be an array');
if (c.routeProfiles.length > 3) throw new ManifestError('capabilities.routeProfiles: at most 3 profiles');
if (c.routeProfiles.length > ROUTE_PROFILES_MAX) {
throw new ManifestError(`capabilities.routeProfiles: at most ${ROUTE_PROFILES_MAX} profiles`);
}
const profiles: RouteProfileCapability[] = [];
for (const v of c.routeProfiles) {
if (!v || typeof v !== 'object') throw new ManifestError('capabilities.routeProfiles entries must be objects');
const p = v as Record<string, unknown>;
const id = typeof p.id === 'string' ? p.id : '';
if (!/^[a-z][a-z0-9-]{0,23}$/.test(id)) {
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}"`);
@@ -432,40 +444,6 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
return out;
}
/**
* Events a plugin notification channel may carry. Two exclusions, both deliberate:
* `version_available` is admin-scoped (it goes out over the admin's own global
* credentials, and a community plugin is never a recipient of one), and
* `synology_session_cleared` is in-app only.
*
* Spelled out rather than derived from the notification service, so the plugin
* installer carries no runtime dependency on it. The guard below is what keeps the
* two in step — same trick as `_eventKeyDriftGuard` in services/notifications.ts.
*/
export const PLUGIN_CHANNEL_EVENTS = [
'trip_invite',
'booking_change',
'trip_reminder',
'todo_due',
'vacay_invite',
'collection_invite',
'photos_shared',
'collab_message',
'packing_tagged',
'plugin_notification',
] as const;
// Compile-time guard: every id above must still be a real notification event.
// If one is renamed or dropped, this stops compiling.
type _ChannelEventsAreReal = (typeof PLUGIN_CHANNEL_EVENTS)[number] extends NotifEventType ? true : never;
const _channelEventDriftGuard: _ChannelEventsAreReal = true;
void _channelEventDriftGuard;
// Core planner tabs a trip-page plugin may replace while it is active. 'plan' is
// deliberately NOT in this list — a trip always keeps its planner view, so a
// plugin can take over bookings/transports/…, never the whole trip.
const REPLACEABLE_TABS = ['transports', 'buchungen', 'listen', 'finanzplan', 'dateien', 'collab'];
/**
* Validate `capabilities.poiCategories`: the plugin's own chips in the explore pill.
*
@@ -553,28 +531,6 @@ function parseCapabilityNames(raw: unknown, field: string): string[] {
return out;
}
/**
* A settings field key. Constrained because the key is used as a JSON object key in
* the plugin's stored config: an unconstrained one (`__proto__`, `constructor`) resolves
* off Object.prototype on read, so a *required* field with such a name would look
* "configured" for every user who had configured nothing — enough, for a notification
* channel, to be dispatched to everyone without anyone entering credentials.
* (safeParse in plugins.service.ts now uses a null-prototype object too; this is the
* front door, that is the backstop.)
*/
const SETTING_KEY_RE = /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/;
const RESERVED_SETTING_KEYS = new Set(['constructor', 'prototype', '__proto__']);
/**
* Every attribute a settings-field object may carry — parseSettings reads exactly these and
* silently drops anything else. The SDK mirrors this list (`SETTING_FIELD_KEYS` in
* plugin-sdk/src/manifest.ts, parity-tested against this file) so `trek-plugin validate`
* can warn on a typo'd or unsupported attribute instead of letting it vanish at install.
*/
export const SETTING_FIELD_KEYS = [
'key', 'label', 'input_type', 'placeholder', 'hint', 'required', 'secret', 'scope', 'options', 'oauth', 'default',
] as const;
function parseSettings(raw: unknown): ManifestSettingField[] {
if (!Array.isArray(raw)) return [];
return raw
@@ -647,7 +603,7 @@ function parseSettingOptions(raw: unknown): Array<{ value: string; label: string
function parseActions(raw: unknown): ManifestAction[] {
if (raw === undefined) return [];
if (!Array.isArray(raw)) throw new ManifestError('actions must be an array');
if (raw.length > 8) throw new ManifestError('at most 8 actions');
if (raw.length > ACTIONS_MAX) throw new ManifestError(`at most ${ACTIONS_MAX} actions`);
const out: ManifestAction[] = [];
for (const a of raw) {
if (!a || typeof a !== 'object') throw new ManifestError('each action must be an object');
+5 -5
View File
@@ -18,8 +18,11 @@ import { z } from 'zod';
import type { McpZodSchema } from '../../nest-mcp';
/** Tools one plugin may advertise. A long list crowds out the built-ins. */
export const MCP_TOOLS_MAX = 8;
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 };
/**
* Tools all plugins together may advertise.
@@ -30,9 +33,6 @@ export const MCP_TOOLS_MAX = 8;
*/
export const MCP_TOOLS_TOTAL_MAX = 32;
/** Plugin-local tool name. No dot or dash, so the advertised name parses apart. */
export const TOOL_NAME_RE = /^[a-z0-9_]{1,48}$/;
export const TOOL_TITLE_MAX = 80;
export const TOOL_DESCRIPTION_MAX = 1024;
@@ -0,0 +1,128 @@
/**
* The format rules of a plugin manifest (trek-plugin.json): the id, version and host
* patterns, the allowed sets and the caps. `install/manifest.ts` enforces them, and
* `scripts/gen-plugin-facts.ts` writes them into the SDK's `generated/host-facts.ts`,
* so `trek-plugin validate` reads the very values an install does instead of a copy
* that can drift (`check:plugin-facts` fails the build when the two differ).
*
* Pure data, no imports with runtime effect: the generator imports this file in a CI
* job that installs only the server.
*/
import type { NotifEventType } from '../../notifications/notification-events';
/** A plugin id: lowercase slug, 3 to 40 characters. */
export const PLUGIN_ID_RE = /^[a-z][a-z0-9-]{2,39}$/;
/**
* Static path segments under /api/admin/plugins: a plugin id must never shadow them
* (id "registry" would collide with GET registry/:id vs :id/errors routing).
*/
export const RESERVED_PLUGIN_IDS = ['registry', 'install', 'rescan'] as const;
/** A plugin version: plain semver, an optional prerelease, no build metadata. */
export const PLUGIN_SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
/**
* 'trip-page' mounts the plugin's sandboxed UI as a tab inside every trip planner
* (tripId-scoped), with no dashboard presence, unlike 'page' (dashboard nav).
*/
export const PLUGIN_TYPES = ['integration', 'page', 'widget', 'trip-page'] as const;
/**
* Addon ids are lowercase slugs that may contain underscores (e.g. `llm_parsing`).
* Validated format-only: existence is checked at activation.
*/
export const ADDON_ID_RE = /^[a-z][a-z0-9_]{1,39}$/;
/**
* An outbound host: an exact hostname (single-label like a `redis` sibling service,
* or a dotted FQDN) OR a `*.`-prefixed wildcard that MUST have a real multi-label
* suffix. Rejects `*`, `*.`, whole-TLD `*.com`, schemes, and any embedded space, all
* of which would otherwise widen egress or inject a CSP source token when the host is
* interpolated into connect-src.
*/
export const EGRESS_HOST_RE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)$/i;
/** Where a widget mounts: dashboard sidebar (default), hero bar, or a planner detail panel. */
export const WIDGET_SLOTS = ['sidebar', 'hero', 'place-detail', 'day-detail', 'reservation-detail'] as const;
/**
* Core planner tabs a trip-page plugin may replace while it is active. 'plan' is
* deliberately NOT in this list: a trip always keeps its planner view.
*/
export const REPLACEABLE_TABS = ['transports', 'buchungen', 'listen', 'finanzplan', 'dateien', 'collab'] as const;
/** The highest 0-based tab index a trip-page plugin may ask for. */
export const TRIP_PAGE_POSITION_MAX = 50;
/** Route profiles one plugin may declare, and the shape of their ids. */
export const ROUTE_PROFILES_MAX = 3;
export const ROUTE_PROFILE_ID_RE = /^[a-z][a-z0-9-]{0,23}$/;
/** Export function / event names exposed to other plugins (dots allowed, `rate.updated`). */
export const CAPABILITY_NAME_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/;
/** Tools one plugin may advertise. A long list crowds out the built-ins. */
export const MCP_TOOLS_MAX = 8;
/** Plugin-local tool name. No dot or dash, so the advertised name parses apart. */
export const TOOL_NAME_RE = /^[a-z0-9_]{1,48}$/;
/**
* A settings field key. Constrained because the key is used as a JSON object key in
* the plugin's stored config: an unconstrained one (`__proto__`, `constructor`)
* resolves off Object.prototype on read, so a required field with such a name would
* look "configured" for every user who had configured nothing.
*/
export const SETTING_KEY_RE = /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/;
export const RESERVED_SETTING_KEYS = ['constructor', 'prototype', '__proto__'] as const;
/**
* Every attribute a settings-field object may carry: parseSettings reads exactly
* these and silently drops anything else, so `trek-plugin validate` warns on any other.
*/
export const SETTING_FIELD_KEYS = [
'key',
'label',
'input_type',
'placeholder',
'hint',
'required',
'secret',
'scope',
'options',
'oauth',
'default',
] as const;
/** Settings-page action buttons one plugin may declare. */
export const ACTIONS_MAX = 8;
/**
* Events a plugin notification channel may carry. Two exclusions, both deliberate:
* `version_available` is admin-scoped (it goes out over the admin's own global
* credentials, and a community plugin is never a recipient of one), and
* `synology_session_cleared` is in-app only.
*
* Spelled out rather than derived from the notification service, so the plugin
* installer carries no runtime dependency on it; the type guard below keeps the two
* in step.
*/
export const PLUGIN_CHANNEL_EVENTS = [
'trip_invite',
'booking_change',
'trip_reminder',
'todo_due',
'vacay_invite',
'collection_invite',
'photos_shared',
'collab_message',
'packing_tagged',
'plugin_notification',
] as const;
// Compile-time guard: every id above must still be a real notification event.
// If one is renamed or dropped, this stops compiling.
type ChannelEventsAreReal = (typeof PLUGIN_CHANNEL_EVENTS)[number] extends NotifEventType ? true : never;
const channelEventDriftGuard: ChannelEventsAreReal = true;
void channelEventDriftGuard;
@@ -1,8 +1,7 @@
/**
* The plugin-author-facing SDK surface (#plugins, M1) — the minimal in-repo
* version. The published `@trek/plugin-sdk` (M6) will re-export these types; for
* now the runtime ships its own copy so the child has zero external deps.
*
* The plugin API as the isolated child implements it: its own copy of the published
* trek-plugin-sdk types, so the child has zero external deps (plugin-sdk's
* test/host-types.test-d.ts holds the two to the same names and members).
* PURE — no server imports. This runs inside the isolated child. Every ctx
* method is plumbing that turns a call into an RPC message to the host; the
* child holds no db handle, no secrets, no network by default.
@@ -338,6 +337,9 @@ export interface PluginRequest {
* providers; never Cookie/Authorization/session). Empty on authenticated routes.
* Verify a provider signature against a secret you hold in `ctx.config`/`ctx.settings`. */
headers: Record<string, string>;
/** The RAW body, base64 — only on `auth:false` routes (webhooks), else null. Run an HMAC
* over this, never over the parsed `body` (re-serializing does not reproduce the bytes). */
rawBodyBase64?: string | null;
user: { id: number; username: string; isAdmin: boolean } | null;
}
export interface PluginResponse {