Fix/plugin audit findings (#2031)

* fix(plugins): enforce manifest apiVersion at install and activation

* test(plugins): exercise the absent-apiVersion default

* feat(plugins): generate the core-event catalog into host-facts

* docs(plugins): explain the packing.listBags write-permission binding

* test(plugins): cover apiVersion upload refusal; tidy docblocks and generator header

* fix(plugin-sdk): validate settings options and oauth like the host

* fix(plugin-sdk): model the full manifest shape and stop dropping fields

* fix(plugin-sdk): drop non-string routeProfiles icons like the host

* docs(plugin-sdk): document host limits, oauth contract, and ignored asUserId

* feat(plugin-sdk): enforce daily budgets and meta quotas in the mock host

* feat(plugin-sdk): expose the generated core-event catalog

* feat(plugin-sdk): scaffold trek range >=3.4.0 <5.0.0 ahead of TREK 4.0

* feat(plugin-sdk): scaffold the oauth broker settings for oauth:client plugins

* chore(plugin-sdk): fix stale mirror docs and the colliding permissions export

* docs(plugin-sdk): add the rate-limit string; restore trek docblock; match host meta sizing

* feat(plugin-sdk): raise the scaffold trek floor to 4.0.0

* docs(wiki): bring the plugin pages in line with the current runtime

* docs: bring the workspace CLAUDE.md guides up to date and make them committable

* feat(plugin-sdk): roll back failed publishes, add unrelease, sync the fork, retro-sign updates

* docs(wiki): document the publish rollback, unrelease, fork sync, and retro-signing

* chore(plugin-sdk): 1.6.0
This commit is contained in:
jubnl
2026-08-24 23:48:36 +02:00
committed by GitHub
parent 4bac447ac8
commit d110b3bb6d
48 changed files with 1895 additions and 169 deletions
+6 -2
View File
@@ -10,6 +10,7 @@ Scope: the **`@trek/server`** workspace. See the repo-root `CLAUDE.md` for the m
npm run dev # scripts/dev.mjs: tsc -w then node --watch dist/index.js (server on :3001)
npm run build # scripts/build.mjs — see "emit-anyway" note below
npm run typecheck # tsc --noEmit (the real type gate; build does NOT fail on type errors)
npm run typecheck:tests # tsc over tests/ — CI runs this too; vitest green does NOT mean typed mocks compile
npm run lint # eslint --fix on src/apps/libs/test
npm run lint:check # eslint, no fix
npm run test # vitest run (all of tests/**)
@@ -18,6 +19,8 @@ npm run test:integration # tests/integration
npm run test:ws # tests/websocket
npm run test:e2e # tests/e2e (boots Nest modules against a temp in-memory SQLite)
npm run test:coverage # istanbul coverage; per-domain ratchet over src/nest/** (floor ≥80%)
npm run gen:plugin-facts # regenerate the plugin-protocol tables into plugin-sdk/ + shared/
npm run check:plugin-facts # CI gate — fails if the generated copies drifted from envelope.ts
```
Single test:
@@ -41,10 +44,11 @@ Nest owns everything: the strangler migration **completed 2026-08-10**, and the
- **`src/db/`** — `better-sqlite3` (WAL, FK on). `database.ts` boots and runs `schema.ts` → `migrations.ts` → `seeds.ts`. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
- **`src/websocket.ts`** — JWT-authed `ws` server on `/ws`, room-per-trip, heartbeat, per-connection rate limiting. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.
- **`src/mcp/`** — process-wide MCP state (scopes, sessionManager, tuning knobs, rate-limit map, `nest-mcp-policy.ts` boot gate). The HTTP transport is `src/nest/mcp-transport/` (a `@Public` controller + service); the tools/resources/prompts live in decorator-driven `<domain>.mcp.ts` files under `src/nest/` — `src/mcp/tools.ts` is registry-attach-only. Every tool invocation writes an `mcp.tool_call` audit row (user, OAuth client, tool name, ip) via the nest-mcp `onInvoke` seam.
- **`src/nest-mcp/`** — the decorator/registry layer itself (`@McpController`/`@Tool`/`@Resource`/`@Prompt`, `McpRegistry`, `McpModule`, result helpers) that the `<domain>.mcp.ts` files build on. Formerly the standalone `@trek/nest-mcp` workspace, folded in 2026-08-22; see its `README.md` for the API and invariants (self-contained apart from a type-only `../mcp/scopes` import; no scope semantics of its own). Tests: `tests/unit/nest-mcp/`.
- **`src/nest/scheduling/`** — `CronRegistrarService`, the one way TREK schedules a cron (`@nestjs/schedule` + the `cron` package). Every job is a `*.job.ts` provider in its owning domain, registered from `onApplicationBootstrap`; the registrar refuses to schedule under `NODE_ENV=test` (the shared `buildApp()` harness must never tick — `tests/integration/scheduler-gate.test.ts` pins it) and stops everything on `nestApp.close()`. Never use a `@Cron` decorator — decorator jobs bypass the gate.
- **`src/nest/plugins/`** — sandboxed plugin runtime in three layers: `supervisor/` + `runtime/plugin-host-entry.ts` + `protocol/envelope.ts` (forked child per plugin, IPC envelopes, rate/RSS policing — **intentionally not Nest**, it's the security boundary); `host/rpc-host.ts` (enforcement: a method is registered at spawn only if the plugin holds the unlocking permission — registration = authorization); `host/plugin-host-deps.factory.ts` (dependency wiring — an `@Injectable()` factory injecting the domain services; the RPC surface is decorator-driven since 2026-08-09, with `PluginsModule` split into four and per-domain coverage gates) + `host/plugin-host-state.ts` (process-wide data-DB/budget maps, module-level on purpose). Install-time gates in `install/` (manifest, safe-extract, Ed25519 signature verify, egress). ⚠️ `runtime/egress-policy.ts` and `HOOK_PERMISSION` in `supervisor/plugin-supervisor.ts` are mirrored (egress-policy **byte-identical**) into `plugin-sdk/` and guarded by parity tests there — keep both sides in sync when touching either.
- **`src/nest/plugins/`** — sandboxed plugin runtime in three layers: `supervisor/` + `runtime/plugin-host-entry.ts` + `protocol/envelope.ts` (forked child per plugin, IPC envelopes, rate/RSS policing — **intentionally not Nest**, it's the security boundary); `host/rpc-host.ts` (enforcement: a method is registered at spawn only if the plugin holds the unlocking permission — registration = authorization); `host/plugin-host-deps.factory.ts` (dependency wiring — an `@Injectable()` factory injecting the domain services; the RPC surface is decorator-driven since 2026-08-09, with `PluginsModule` split into four and per-domain coverage gates) + `host/plugin-host-state.ts` (process-wide data-DB/budget maps, module-level on purpose). Install-time gates in `install/` (manifest, safe-extract, Ed25519 signature verify, egress). ⚠️ The protocol tables — permissions, RPC methods, hooks, and the core-event catalog — live in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts` for the event families) and are **generated** into `plugin-sdk/src/generated/host-facts.ts` and `shared/src/plugin-permissions.ts` by `npm run gen:plugin-facts`; `check:plugin-facts` is the CI gate, so run it after touching any of them and commit the regenerated files. `runtime/egress-policy.ts` is still a hand-kept **byte-identical** mirror into `plugin-sdk/`, guarded by parity tests there — keep both sides in sync when touching either.
## Direction (from the 2026 audit — `audit_report/TREK_audit_reports/`)
## Direction (post-migration guardrails, from the 2026 audit)
**Nest is the destination — and as of 2026-08-10 the code is there.** These rules now guard against regression rather than describe a migration in flight:
+19 -1
View File
@@ -21,12 +21,13 @@ import {
HOOK_PERMISSION, KNOWN_METHODS, KNOWN_PERMISSIONS, METHOD_PERMISSION,
EVENTS_PERMISSION, JOBS_PERMISSION, USER_DATA_PERMISSION, HTTP_OUTBOUND_PREFIX,
} from '../src/nest/plugins/protocol/envelope';
import { SNAPSHOT_GRANT, ENTITY_ID_KEYS } from '../src/plugin-event-sink';
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const HEADER = [
'// GENERATED — do not edit by hand.',
'// Source: server/src/nest/plugins/protocol/envelope.ts',
'// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts',
'// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts',
'',
].join('\n');
@@ -43,6 +44,8 @@ const pairs = (o: Readonly<Record<string, string>>) =>
* source-breaking type change for any plugin author doing a dynamic lookup. Strictness
* belongs on the host side, where the data source lives.
*/
const EVENT_FAMILIES = [...new Set([...Object.keys(ENTITY_ID_KEYS), ...Object.keys(SNAPSHOT_GRANT)])].sort();
const SDK_FACTS = `${HEADER}
export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
${pairs(HOOK_PERMISSION)}
@@ -64,6 +67,21 @@ export const USER_DATA_PERMISSION = '${USER_DATA_PERMISSION}';
export const EVENTS_PERMISSION = '${EVENTS_PERMISSION}';
export const JOBS_PERMISSION = '${JOBS_PERMISSION}';
export const HTTP_OUTBOUND_PREFIX = '${HTTP_OUTBOUND_PREFIX}';
/**
* Core-event catalog. Delivery names are the WebSocket broadcast names,
* \`<family>:<verb>\` (e.g. \`place:created\`). A subscribed plugin receives
* \`{event, tripId, entity?, entityId?, snapshot?}\`; \`snapshot\` is delivered only
* when the plugin also holds EVENT_SNAPSHOT_GRANT[family]. Delete/reorder/bulk
* events carry no snapshot.
*/
export const EVENT_FAMILIES: readonly string[] = [
${list(EVENT_FAMILIES)}
];
export const EVENT_SNAPSHOT_GRANT: Readonly<Record<string, string>> = {
${pairs(SNAPSHOT_GRANT)}
};
`;
const SHARED_FACTS = `${HEADER}
+12 -2
View File
@@ -1,5 +1,5 @@
import semver from 'semver';
import { isKnownPermission } from '../protocol/envelope';
import { isKnownPermission, PLUGIN_API_VERSION } from '../protocol/envelope';
import { isValidTrekRange, minTrekOf } from './host-compat';
import type { NotifEventType } from '../../notifications/notification-events';
@@ -220,11 +220,21 @@ export function parseManifest(raw: unknown, opts?: { requireTrek?: boolean }): P
: 'missing "trek" version range — declare the TREK versions this plugin supports, e.g. ">=3.2.0 <4.0.0"',
);
}
const rawApi = m.apiVersion;
if (rawApi !== undefined && (typeof rawApi !== 'number' || !Number.isInteger(rawApi) || rawApi < 1)) {
throw new ManifestError('apiVersion must be a positive integer');
}
const apiVersion = (rawApi as number | undefined) ?? 1;
if (opts?.requireTrek && apiVersion > PLUGIN_API_VERSION) {
throw new ManifestError(`plugin requires plugin-API v${apiVersion}; this TREK supports v${PLUGIN_API_VERSION}`);
}
return {
id,
name: str(m.name, 'name'),
version,
apiVersion: typeof m.apiVersion === 'number' ? m.apiVersion : 1,
apiVersion,
author: optStr(m.author),
description: optStr(m.description),
homepage: optStr(m.homepage),
@@ -33,7 +33,7 @@ import type { PluginDependency } from './install/manifest';
import type { VersionMismatch, PluginDepRow } from './dependencies';
import { parseDependencies, disabledRequiredAddons, resolveDependencyState, enableOrder, findDependentsTransitive, DependencyCycleError } from './dependencies';
import { HTTP_OUTBOUND_PREFIX as HTTP_OUTBOUND } from './protocol/envelope';
import { HTTP_OUTBOUND_PREFIX as HTTP_OUTBOUND, PLUGIN_API_VERSION } from './protocol/envelope';
// Mirrors HOST_RE in install/manifest.ts: an exact hostname or a `*.`-prefixed wildcard
// with a real multi-label suffix. Rejects a bare `*`, a whole-TLD wildcard, a scheme and
@@ -85,7 +85,9 @@ export type PluginDependencyCode =
/** The plugin's declared TREK range doesn't admit the running host. */
| 'TREK_VERSION_INCOMPATIBLE'
/** The plugin never declared a range, so we can't know that it does. */
| 'TREK_VERSION_UNKNOWN';
| 'TREK_VERSION_UNKNOWN'
/** The plugin's manifest apiVersion is newer than this TREK's plugin-API surface. */
| 'API_VERSION_INCOMPATIBLE';
/**
* Thrown when a plugin can't activate because a required addon is disabled, a declared
@@ -478,11 +480,12 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
/**
* Read-only activation gate for one plugin — throws (without mutating) if it may
* not activate. Checks run most- to least-severe: TREK-version compatibility →
* permission re-consent → required addon disabled → missing/mismatched plugin dependency.
* plugin-API version compatibility → permission re-consent → required addon disabled →
* missing/mismatched plugin dependency.
*/
private assertActivatable(id: string, installed: Map<string, PluginDepRow>, consentWiden: boolean): void {
const row = this.db.prepare('SELECT permissions, granted_permissions, dependencies, trek_range FROM plugins WHERE id = ?').get(id) as
| { permissions: string; granted_permissions: string; dependencies: string | null; trek_range: string | null }
const row = this.db.prepare('SELECT permissions, granted_permissions, dependencies, trek_range, api_version FROM plugins WHERE id = ?').get(id) as
| { permissions: string; granted_permissions: string; dependencies: string | null; trek_range: string | null; api_version: number | null }
| undefined;
if (!row) throw new Error(`plugin ${id} not found`);
@@ -505,6 +508,16 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
{ trekRange: row.trek_range, hostVersion: hostVersion() },
);
}
// Same reasoning as the TREK-version gate above: a plugin whose manifest apiVersion
// outpaces this TREK's plugin-API surface can never run correctly, so it must be
// refused before any consent dialog is offered.
const apiVersion = row.api_version ?? 1;
if (apiVersion > PLUGIN_API_VERSION) {
throw new PluginDependencyError(
`plugin requires plugin-API v${apiVersion}; this TREK supports v${PLUGIN_API_VERSION}`,
'API_VERSION_INCOMPATIBLE',
);
}
const declared = parseArray(row.permissions).filter(isKnownPermission);
const granted = parseArray(row.granted_permissions);
@@ -7,6 +7,14 @@
* or the websocket server. Keep it dependency-free.
*/
/**
* The plugin-API surface version (#plugins, M4) — bumped on any breaking change to the
* ctx methods / manifest shape a plugin author can rely on. Mirrored into every
* manifest as `apiVersion`; the install and activation gates refuse a plugin declaring
* a version newer than this one.
*/
export const PLUGIN_API_VERSION = 1;
export type PluginErrCode =
| 'PERMISSION_DENIED' // a real method the plugin was not granted
| 'UNKNOWN_METHOD' // not a method the host exposes at all
@@ -202,6 +210,10 @@ export const METHOD_PERMISSION = {
'packing.create': 'db:write:packing',
'packing.update': 'db:write:packing',
'packing.delete': 'db:write:packing',
// Intentional: bags are the write-side organizational structure of packing —
// a read-only consumer uses packing.list; only bag-managing (write) plugins
// need the bag tree. Moving this to db:read:packing would strip access from
// every installed write-only plugin and force consent re-prompts.
'packing.listBags': 'db:write:packing',
'packing.createBag': 'db:write:packing',
'packing.updateBag': 'db:write:packing',
@@ -9,7 +9,7 @@
*/
/** Mirrors the published package's constant — bumped on any breaking API change. */
export const PLUGIN_API_VERSION = 1 as const;
export { PLUGIN_API_VERSION } from '../protocol/envelope';
export interface PluginContext {
readonly id: string;
@@ -93,7 +93,12 @@ export interface PluginContext {
update(tripId: number, itemId: number, input: Record<string, unknown>): Promise<unknown>;
/** Delete a packing item. Needs 'db:write:packing' + 'packing_edit'. */
delete(tripId: number, itemId: number): Promise<{ deleted: boolean }>;
/** List/create/update/delete packing bags + set members (no privacy). Needs 'db:write:packing' + 'packing_edit'. */
/**
* List/create/update/delete packing bags + set members (no privacy). Bag methods need
* 'db:write:packing' + the acting user's 'packing_edit' trip permission — except this
* one: listBags is a read, but the envelope still gates it on the write scope
* (intentional — bags are the write-side structure; packing.list is the read surface).
*/
listBags(tripId: number): Promise<unknown[]>;
createBag(tripId: number, input: { name: string; color?: string }): Promise<unknown>;
updateBag(tripId: number, bagId: number, input: Record<string, unknown>): Promise<unknown>;
+1 -1
View File
@@ -37,7 +37,7 @@ export function emitPluginEvent(tripId: number, event: string, meta?: PluginEven
// from leaking: e.g. `budget:member-paid-updated` carries { itemId, userId } and we
// deliberately only read itemId, never userId. Families not listed (settlement/bag
// sub-entities, reorders, bulk position updates) yield no entityId, which is correct.
const ENTITY_ID_KEYS: Readonly<Record<string, readonly string[]>> = {
export const ENTITY_ID_KEYS: Readonly<Record<string, readonly string[]>> = {
place: ['placeId', 'place.id'],
day: ['dayId', 'day.id'],
reservation: ['reservationId', 'reservation.id'],
@@ -12,7 +12,7 @@ const { testDb } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec(`CREATE TABLE plugins (
id TEXT PRIMARY KEY, status TEXT, enabled INTEGER DEFAULT 0, version TEXT, permissions TEXT DEFAULT '[]', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT DEFAULT '',
id TEXT PRIMARY KEY, status TEXT, enabled INTEGER DEFAULT 0, version TEXT, api_version INTEGER DEFAULT 1, permissions TEXT DEFAULT '[]', operator_egress INTEGER DEFAULT 0, granted_permissions TEXT DEFAULT '',
config TEXT DEFAULT '{}', dependencies TEXT DEFAULT '{}', capabilities TEXT DEFAULT '{}', last_error TEXT, updated_at TEXT,
-- Activation refuses a plugin that declares no TREK range, so the fixtures default to a
-- satisfied one: these tests are about permissions/dependencies, and every row would
@@ -722,3 +722,39 @@ describe('TREK host-version gating', () => {
cleanup('both-wrong');
});
});
/**
* The activation gate also refuses a plugin whose manifest `apiVersion` is newer than
* what this TREK's plugin-API surface supports (`PLUGIN_API_VERSION`) — mirrors the
* TREK-version gate above, just for the plugin-API surface instead of the host version.
*/
describe('plugin-API version gating', () => {
const seedApi = (id: string, apiVersion: number) => {
fs.mkdirSync(path.join(codeRoot, id, 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, id, 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
testDb
.prepare(
"INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range, api_version) VALUES (?, 'inactive', 0, '[]', '[]', '{}', '>=3.0.0', ?)",
)
.run(id, apiVersion);
};
const cleanup = (...ids: string[]) => { for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id); };
it('refuses to activate a plugin whose apiVersion this TREK does not support', async () => {
seedApi('future-api', 2);
const err = await createPluginRuntime(new DatabaseService(dbConn)).activate('future-api').catch((e) => e);
expect(err).toBeInstanceOf(PluginDependencyError);
expect(err).toMatchObject({ code: 'API_VERSION_INCOMPATIBLE' });
expect(err.message).toBe('plugin requires plugin-API v2; this TREK supports v1');
cleanup('future-api');
});
it('activates normally when apiVersion is within what this TREK supports', async () => {
seedApi('current-api', 1);
const rt = createPluginRuntime(new DatabaseService(dbConn));
await rt.activate('current-api');
expect(rt.isActive('current-api')).toBe(true);
await rt.deactivate('current-api');
cleanup('current-api');
});
});
@@ -824,6 +824,14 @@ describe('TREK-version gating on install', () => {
const bytes = makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', trek: undefined });
expect(() => svc.stageUpload(bytes)).toThrow(/missing "trek"/);
});
it('refuses an uploaded archive declaring apiVersion 2 (this TREK only speaks plugin-API v1), and writes nothing to the plugin code dir', () => {
// trek range is satisfiable on its own — parseManifest's apiVersion check must
// fire (and stop the upload) before assertHostCompatible is ever reached.
const bytes = makeArtifact({ id: 'my-upload', name: 'Up', version: '1.0.0', type: 'integration', apiVersion: 2 });
expect(() => svc.stageUpload(bytes)).toThrow('plugin requires plugin-API v2; this TREK supports v1');
expect(fs.existsSync(path.join(codeRoot, 'my-upload'))).toBe(false);
});
});
it('installWithDependencies installs the version it RESOLVED, not versions[0]', async () => {
@@ -0,0 +1,15 @@
import { it, expect } from 'vitest';
import { SNAPSHOT_GRANT, ENTITY_ID_KEYS } from '../../../src/plugin-event-sink';
import { KNOWN_PERMISSIONS } from '../../../src/nest/plugins/protocol/envelope';
it('every snapshot grant is a known db:read permission', () => {
for (const p of Object.values(SNAPSHOT_GRANT)) {
expect(KNOWN_PERMISSIONS).toContain(p);
expect(p).toMatch(/^db:read:/);
}
});
it('every snapshot family has an id-key path', () => {
for (const family of Object.keys(SNAPSHOT_GRANT)) {
expect(Object.keys(ENTITY_ID_KEYS)).toContain(family);
}
});
@@ -6,6 +6,7 @@ import { describe, it, expect } from 'vitest';
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
const base = { id: 'flight-tracker', name: 'Flight', version: '1.2.0', type: 'widget', apiVersion: 1 };
const withApi = (apiVersion: unknown) => ({ ...base, apiVersion, trek: '>=3.2.0 <4.0.0' });
describe('parseManifest', () => {
it('parses a valid manifest with defaults', () => {
@@ -99,6 +100,23 @@ describe('parseManifest', () => {
});
});
describe('apiVersion', () => {
it.each([[0], [-3], [1.5], ['1']])('rejects non-positive-integer %p', (v) => {
expect(() => parseManifest(withApi(v))).toThrow('apiVersion must be a positive integer');
});
it('defaults to 1 when absent', () => {
const { apiVersion: _omitted, ...noApi } = base;
expect(parseManifest(noApi).apiVersion).toBe(1);
});
it('tolerates a future apiVersion under discovery (no requireTrek)', () => {
expect(parseManifest(withApi(2)).apiVersion).toBe(2);
});
it('refuses a future apiVersion on install paths (requireTrek)', () => {
expect(() => parseManifest(withApi(2), { requireTrek: true }))
.toThrow('plugin requires plugin-API v2; this TREK supports v1');
});
});
describe('parseManifest capabilities', () => {
it('parses a hero widget slot and defaults to sidebar', () => {
const hero = parseManifest({ ...base, capabilities: { widget: { slot: 'hero', title: 'T' } } });