refactor(plugins): the plugin RPC kit moves out of the plugins domain into src/nest-rpc

Every domain's *.rpc.ts was written against rpc-kit, rpc-params, rpc-errors
and PluginGuards, and every domain module imported PluginGuardsModule, all
of it inside src/nest/plugins, while PluginsRuntimeModule imports those same
domains so their handlers exist at boot. That made the plugins domain part
of every cycle. The kit imports no domain but the protocol tables and
permissions/addons for the guards, so it moves to src/nest-rpc beside
src/nest-mcp, with its tests, its README and its extraction rule; the
runtime module keeps its domain imports, which the boot-time coverage check
of the wire surface needs in any subset app.
This commit is contained in:
Maurice
2026-10-10 12:19:38 +02:00
parent cc79f561e5
commit e40bc71e9f
92 changed files with 237 additions and 280 deletions
@@ -1,31 +0,0 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { PermissionsModule } from '../../permissions/permissions.module';
import { AddonsModule } from '../../addons/addons.module';
import { Users } from '../../../db/entities/Users.entity';
import { Trips } from '../../../db/entities/Trips.entity';
import { PluginGuards } from './plugin-guards.service';
/**
* A leaf module whose only job is to hand PluginGuards to the domain modules.
*
* It cannot live in PluginsModule: that module imports 22 domain modules, so a
* domain importing it back to reach the guards would close a hard cycle
* (PluginsModule -> TodoModule -> PluginsModule) and the only way out would be
* forwardRef. PermissionsModule and AddonsModule are themselves leaves and
* DatabaseModule is @Global, so this module imports nothing that leads back here.
* `MikroOrmModule.forFeature([Users])` (Plan 3j Task 1 — PluginGuards' own
* role lookup, PG3/PG4, now goes through UsersRepository) is the same kind of
* leaf: it hands out a repository token, not a domain module, so it doesn't
* reopen the cycle either — this module is the one that CONSTRUCTS
* PluginGuards, so it (not each importer) owns the forFeature list.
*
* Same shape and same reason as MailerModule, which broke
* AuthModule <-> NotificationsModule.
*/
@Module({
imports: [PermissionsModule, AddonsModule, MikroOrmModule.forFeature([Users, Trips])],
providers: [PluginGuards],
exports: [PluginGuards],
})
export class PluginGuardsModule {}
@@ -1,130 +0,0 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { PermissionsService } from '../../permissions/permissions.service';
import { AddonsService } from '../../addons/addons.service';
import { Users } from '../../../db/entities/Users.entity';
import type { UsersRepository } from '../../../db/repositories/Users.repository';
import { Trips } from '../../../db/entities/Trips.entity';
import type { TripsRepository } from '../../../db/repositories/Trips.repository';
import { BadParams, ForbiddenResource } from './rpc-errors';
import { num } from './rpc-params';
import type { PluginRpcContext } from './rpc-kit/types';
/**
* The resource gates every plugin RPC handler needs, lifted out of PluginRpcHost's
* private methods and the host factory's canEditTripAs / requireAddon so that
* decorated *.rpc.ts handlers get them by injection instead of through a closure.
*
* Every message string is character-identical to what the legacy router produced.
* Do not "improve" one: rpc-host.test.ts asserts them, and shipped plugins read
* them. Note in particular that trip READS say "trip reads" while requireActor
* appends the word "writes", and that some domains throw their own inline variant
* rather than calling requireActor at all.
*/
@Injectable()
export class PluginGuards {
constructor(
// Plan 4 Task 2 — canAccessTrip's own DatabaseService delegation is gone:
// this injects TripsRepository directly (same constructor slot) and
// calls findAccessible.
@InjectRepository(Trips) private readonly trips: TripsRepository,
private readonly permissions: PermissionsService,
private readonly addons: AddonsService,
@InjectRepository(Users) private readonly users: UsersRepository,
) {}
/**
* Membership-check a trip read against the HOST-bound acting user. The acting user
* comes from the supervisor's invocation map, never from a plugin-supplied field,
* so a plugin cannot read another user's trips by naming their id. A userless
* context (a job, or onLoad) has no acting user and is refused.
*/
async tripRead<T>(params: Record<string, unknown>, ctx: PluginRpcContext, read: (userId: number) => T): Promise<T> {
const tripId = num(params.tripId, 'tripId');
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource('trip reads require an authenticated user context');
}
if (!(await this.trips.findAccessible(tripId, ctx.actingUserId))) {
throw new ForbiddenResource(`no access to trip ${tripId}`);
}
// The read runs only for a bound, membership-checked user, so hand the id through
// and per-user visibility filters (packing's private items) still apply.
return read(ctx.actingUserId);
}
/**
* Every write needs a HOST-bound acting user. `noun` is the domain word, and the
* message appends "writes" to it, so pass 'tag', not 'tag writes'.
*/
requireActor(ctx: PluginRpcContext, noun: string): number {
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource(`${noun} writes require an authenticated user context`);
}
return ctx.actingUserId;
}
/** A write is allowed only if the acting user can access AND edit the trip. */
async requireTripEdit(tripId: number, userId: number, action: string): Promise<void> {
if (!(await this.trips.findAccessible(tripId, userId))) throw new ForbiddenResource(`no access to trip ${tripId}`);
if (!(await this.canEditAs(action, tripId, userId))) throw new ForbiddenResource(`no permission to edit trip ${tripId}`);
}
/**
* The trip-access + role gate every planner write uses, mirroring the app's
* per-domain canEdit. Returns false and never throws, so the caller decides which
* message the refusal carries.
*/
async canEditAs(action: string, tripId: number, userId: number): Promise<boolean> {
const trip = await this.trips.findAccessible(tripId, userId);
if (!trip) return false;
// UsersRepository.getRole (PG3, Plan 3j Task 1) — `SELECT role FROM users
// WHERE id = ?`, converted. Its `string | null` return already folds "no
// row" and "row with a null role" into one value (the `role` column is
// `NOT NULL DEFAULT 'user'`, so the second case cannot occur against the
// real schema), so a null role here IS the "row is gone" refusal the
// legacy `!user` check made. The `?? 'user'` fallback below is kept
// verbatim rather than dropped, even though it is now unreachable code,
// so a future change to getRole's contract can't silently resurrect the
// old defensive gap.
const role = await this.users.getRole(userId);
if (role === null) return false;
return this.permissions.checkPermission(action, role ?? 'user', trip.user_id, userId, trip.user_id !== userId);
}
/**
* A permission that is NOT bound to a trip, so it cannot go through
* requireTripEdit. `trip_create` is the only one today: it has no trip to check
* against yet, which is why the owner id is passed as null.
*/
async canCreateAs(action: string, userId: number): Promise<boolean> {
// Same converted read as canEditAs (PG4, identical statement text). No
// early refusal here, unchanged from the legacy branch: a vanished row
// falls back to role 'user' rather than refusing outright, exactly like
// `user?.role ?? 'user'` did — `trip_create`'s 'everybody' default means
// that fallback alone is enough to let the call through today.
const role = await this.users.getRole(userId);
return this.permissions.checkPermission(action, role ?? 'user', null, userId, false);
}
/**
* A subsystem read is refused when its addon is off, matching the app, where a
* disabled addon means there is simply nothing to read.
*/
async requireAddon(addonId: string, noun: string): Promise<void> {
if (!(await this.addons.isAddonEnabled(addonId))) throw new ForbiddenResource(`the ${noun} addon is disabled`);
}
/**
* The @trek/shared write schemas carry no string-length caps, so mirror the ones
* the REST controllers add. Without this a plugin could write a field the web app
* would reject with 400.
*/
capStrings(input: Record<string, unknown>, limits: Record<string, number>): void {
for (const [field, max] of Object.entries(limits)) {
const value = input[field];
if (typeof value === 'string' && value.length > max) {
throw new BadParams(`${field} must be ${max} characters or fewer`);
}
}
}
}
@@ -3,8 +3,8 @@ import { InjectRepository } from '@mikro-orm/nestjs';
import { PluginCapabilityAudit } from '../../../db/entities/PluginCapabilityAudit.entity';
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
import { PluginRpcHost } from './rpc-host';
import type { PluginRpcRegistry } from './rpc-kit/registry';
import { PluginRpcRegistryService } from './rpc-kit/registry.service';
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
import { PluginRpcRegistryService } from '../../../nest-rpc/rpc-kit/registry.service';
import { appendAudit } from './plugin-audit';
import { getPluginDataDb } from './plugin-host-state';
@@ -1,15 +0,0 @@
/**
* The two error classes the plugin RPC boundary maps onto wire error codes.
*
* handle() in rpc-host.ts translates them: BadParams -> BAD_PARAMS,
* ForbiddenResource -> RESOURCE_FORBIDDEN, anything else -> HOST_ERROR. Lifted out
* of rpc-host.ts so decorated *.rpc.ts handlers can throw them without importing
* the router itself; rpc-host.ts re-exports both, so existing importers are
* unaffected.
*/
/** Thrown by a handler when the acting user may not touch the requested resource. */
export class ForbiddenResource extends Error {}
/** Thrown when a param is missing or has the wrong shape. */
export class BadParams extends Error {}
+2 -2
View File
@@ -8,9 +8,9 @@ import {
} from '../protocol/envelope';
import type { PluginDataDb } from './plugin-data.service';
import { auditResource, isAuditable } from './plugin-audit';
import { BadParams, ForbiddenResource } from './rpc-errors';
import { BadParams, ForbiddenResource } from '../../../nest-rpc/rpc-errors';
import { shapePluginOutput } from '../protocol/output-contract';
import type { PluginRpcRegistry } from './rpc-kit/registry';
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
// Both used to be declared here. They now live in rpc-errors.ts so decorated
// *.rpc.ts handlers can throw them without importing the router, and are re-exported
@@ -1,82 +0,0 @@
# rpc-kit — the plugin RPC decorator layer
Conceptually this is `trek-plugin-host`: `@PluginController`, `@PluginMethod`,
`@PluginOpenMethod` and `@PluginHook`, plus the registry that binds them into the
per-plugin dispatch map. It lives inside `server/` rather than in its own workspace,
and this file records why, and what extracting it later would cost.
## What the decorators buy
The method-to-permission association used to exist twice: declaratively in
`METHOD_PERMISSION` (`../../protocol/envelope.ts`) and imperatively as the
`if (has('...'))` blocks in `../rpc-host.ts`, with nothing asserting they agree.
`protocol-paths.test.ts` checked that each method had *some* permission, never that it
was *the same* permission the router gates on, and `plugin-audit.ts`'s `isAuditable`
silently inherits any drift.
A `@PluginMethod` declaration is checked against that table twice:
- at compile time, because `MethodPermission<M>` resolves to the single literal the
table assigns to `M`, so `@PluginMethod('tags.list', { permission: 'db:write:tags' })`
does not typecheck;
- at boot, in `registry.validate()`, because types evaporate under an `as` cast or a
hand-emitted JS consumer.
`@PluginHook` gets the same treatment against `HOOK_PERMISSION`.
## The import rule
The kit may import:
- `@nestjs/common` and `@nestjs/core`,
- **type-only** from `../../protocol/envelope` and `../plugin-data.service`.
Nothing else. It must not reach into `rpc-host.ts`, the deps factory, the supervisor,
or any domain service. `registry.ts` is the single exception that imports envelope
values (the tables it validates against), which is deliberate: the kit sits in the same
package as its data source, so it can read it directly.
## If this ever becomes its own package
`nest-mcp` was the worked example of the same layer as a separate workspace (it has
since been folded into `server/src/nest-mcp/`, which retired the machinery below), and
the delta is instructive. Because `nest-mcp` could not import the host, it needed a
`declare module` augmentation for its registries plus two `AssertExact` drift guards in
`src/mcp/nest-mcp-policy.ts`, and a permissive `keyof X extends never ? string`
fallback that silently disables all checking if someone forgets to augment.
`rpc-kit` needs none of that today. Extracting it would mean:
1. `PluginRpcContext.data` becomes a generic parameter instead of importing
`PluginDataDb`.
2. The four envelope type imports (`KnownMethod`, `MethodPermission`, `HookKey`,
`HookPermission`) become empty-interface augmentation points, with `AssertExact`
guards in the server proving the augmentation still matches the tables.
3. Root `package.json` `workspaces`, `server/package.json` deps, the root lockfile, the
Dockerfile COPY stages and a source alias in `server/vitest.config.ts` all change.
Note that a workspace would *not* let `trek-plugin-sdk` consume it: `nest-mcp` was
`"private": true`, and so would this be. The SDK gets its copy of the permission facts
from the generated `plugin-sdk/src/generated/host-facts.ts` instead.
## Files
| File | What it is |
|---|---|
| `metadata.ts` | WeakSet/WeakMap keyed by constructor. Deliberately not `reflect-metadata`, so a bare vitest worker can build a registry with no Nest app. |
| `types.ts` | `PluginRpcContext`, the entry union, the option shapes. |
| `decorators.ts` | The four decorators. |
| `registry.ts` | `register` / `validate` / `bindInto` / `hookContracts`. Plain class, no DI. |
| `registry.service.ts` | The DI-discovered subclass. Scans providers at boot and validates. |
| `testing.ts` | `createTestPluginRegistry`, same fail-fast contract as the boot path. |
## The failure mode to know about
A `@PluginController()` class that is missing from its module's `providers: []` is
invisible to discovery. Its methods are simply never bound, and every call to them
comes back `PERMISSION_DENIED` with no other symptom. The compiler cannot see this.
`requireTotalCoverage` is now on, so the app refuses to boot instead: `validate()`
names every `KNOWN_METHOD` left without a handler, and every hook left without a
host-side consumer. `server/tests/unit/plugins/rpc-coverage.test.ts` catches the same
gap in CI, before anyone starts the server.
@@ -1,90 +0,0 @@
import { Injectable } from '@nestjs/common';
import { addEntry, markController, type ClassRef } from './metadata';
import type { HookKey, KnownMethod, MethodPermission, UnconditionalMethod } from '../../protocol/envelope';
import type { PluginHookOptions, PluginRpcEntry } from './types';
/**
* Marks a class as a plugin RPC controller. Implies `@Injectable()`.
*
* The class MUST be listed in its domain module's `providers: []`. Discovery scans
* only marked PROVIDERS (explicit opt-in), so a decorated class nobody registered
* contributes nothing and every call to its methods comes back PERMISSION_DENIED
* with no other symptom. The coverage ledger test catches that in CI, and
* `requireTotalCoverage` turns it into a boot failure once the rollout is done.
*
* NEVER put this on a Nest `@Controller`: `Injectable()` rewrites
* SCOPE_OPTIONS_METADATA and would clobber a `@Controller({ scope })` option.
* register() rejects it.
*/
export function PluginController(): ClassDecorator {
return (target) => {
Injectable()(target);
markController(target as unknown as ClassRef);
};
}
function pluginMethodDecorator(entry: (methodName: string) => PluginRpcEntry): MethodDecorator {
return (target, propertyKey) => {
addEntry((target as { constructor: unknown }).constructor as ClassRef, entry(String(propertyKey)));
};
}
/**
* Registers the method as the handler for RPC method `method`.
* Handler signature: `(params, ctx: PluginRpcContext) => unknown`.
*
* @PluginMethod('tags.list', { permission: 'db:read:tags' })
*
* Both arguments are checked against protocol/envelope.ts at COMPILE time: a name
* outside KNOWN_METHODS does not typecheck, and a permission other than the one
* METHOD_PERMISSION assigns to that method fails with the expected literal named in
* the error. That is the binding the whole kit exists for.
*/
export function PluginMethod<M extends KnownMethod>(
method: M,
options: { permission: MethodPermission<M> },
): MethodDecorator {
return pluginMethodDecorator((methodName) => ({
kind: 'method',
methodName,
method,
permission: options.permission,
}));
}
/**
* The carve-out: a method registered with NO grant check, matching the three the
* router registers outside every has() block.
*
* A separate decorator rather than an option on @PluginMethod, so that "I forgot the
* permission" can never look like the carve-out. It also sidesteps a trap specific to
* this package: server/tsconfig.json has "strict": false, so a `permission: null`
* sentinel would be assignable to every string literal and the check would be void.
*/
export function PluginOpenMethod(method: UnconditionalMethod): MethodDecorator {
return pluginMethodDecorator((methodName) => ({ kind: 'open', methodName, method }));
}
/**
* Declares a HOST-side consumer of one provider-hook function.
*
* @PluginHook('warningProvider', { permission: 'hook:trip-warning-provider', fn: 'getWarnings' })
*
* It does NOT impose a fan-out shape, because the real call graph is not uniform:
* routeProvider is single-target on a 20s budget, calendarSource fans out over two
* fns with different budgets, photoProvider has three separate sites, and
* notificationChannel is invoked from PluginRuntimeService rather than a controller.
* What the declaration buys is the compile-checked hook/permission pair, one place
* where the timeout lives, and the boot assertion that no granted hook is left
* without a consumer.
*/
export function PluginHook<H extends HookKey>(hook: H, options: PluginHookOptions<H>): MethodDecorator {
return pluginMethodDecorator((methodName) => ({
kind: 'hook',
methodName,
hook,
permission: options.permission,
fn: options.fn,
timeoutMs: options.timeoutMs ?? 5000,
}));
}
@@ -1,47 +0,0 @@
import type { PluginRpcEntry } from './types';
/**
* Metadata store. A package-private WeakMap/WeakSet keyed by class constructor
* instead of reflect-metadata: it has zero runtime prerequisites (no polyfill
* import order to get right), works in bare vitest workers and in
* `createTestPluginRegistry` without a Nest app, and is trivially
* extraction-clean. Same reasoning as nest-mcp's metadata store.
*/
/** A class constructor, without using the banned bare `Function` type. */
export type ClassRef = abstract new (...args: never[]) => unknown;
const controllers = new WeakSet<ClassRef>();
const entries = new WeakMap<ClassRef, Map<string, PluginRpcEntry>>();
export function markController(ctor: ClassRef): void {
controllers.add(ctor);
}
export function isPluginController(ctor: unknown): ctor is ClassRef {
return typeof ctor === 'function' && controllers.has(ctor as ClassRef);
}
export function addEntry(ctor: ClassRef, entry: PluginRpcEntry): void {
let map = entries.get(ctor);
if (!map) {
map = new Map();
entries.set(ctor, map);
}
map.set(entry.methodName, entry);
}
/**
* Look up the entry recorded for `methodName`, walking the constructor prototype
* chain so inherited decorated methods are found on subclasses.
*/
export function getEntry(ctor: ClassRef, methodName: string): PluginRpcEntry | undefined {
let current: ClassRef | null = ctor;
while (current) {
const found = entries.get(current)?.get(methodName);
if (found) return found;
const parent: unknown = Object.getPrototypeOf(current);
current = typeof parent === 'function' ? (parent as ClassRef) : null;
}
return undefined;
}
@@ -1,54 +0,0 @@
import { Injectable, type OnModuleInit } from '@nestjs/common';
import { DiscoveryService, MetadataScanner } from '@nestjs/core';
import { isPluginController } from './metadata';
import { PluginRpcRegistry } from './registry';
/**
* DI-discovered registry: at boot, scans every PROVIDER marked with
* `@PluginController()` and records its decorated methods.
*
* `getControllers()` is deliberately not scanned. @PluginController implies
* @Injectable(), which rewrites the scope metadata @Controller() sets, so the
* decorator belongs on provider classes only and register() rejects the rest.
*/
@Injectable()
export class PluginRpcRegistryService extends PluginRpcRegistry implements OnModuleInit {
constructor(
private readonly discovery: DiscoveryService,
private readonly scanner: MetadataScanner,
) {
// The rollout is done: the legacy router map is gone, every KNOWN_METHOD has a
// decorated owner and every hook has a host-side consumer. Boot now FAILS on a
// gap rather than letting it surface as a runtime PERMISSION_DENIED, or as a
// hook:* grant on the consent screen that nothing behind it ever calls.
super({ requireTotalCoverage: true });
}
onModuleInit(): void {
this.scanProviders();
// Fail app boot on a wrong decorator argument, a double-owned method or a gap in
// the surface, rather than failing per-plugin at activation time.
this.validate();
}
/**
* Records every `@PluginController()` provider the container knows about.
*
* Separate from validate() because the two answer different questions: this one is
* about discovery (which providers were found, and once each), validate() is about
* the surface being complete and correctly declared. Keeping them apart lets the
* discovery behaviour be tested without assembling all 113 methods first.
*/
scanProviders(): void {
// A provider can be wrapped once per module that lists it, so dedupe by instance
// or every entry is recorded twice and the duplicate check fires spuriously.
const seen = new Set<object>();
for (const wrapper of this.discovery.getProviders()) {
const { instance, metatype } = wrapper;
if (!instance || typeof instance !== 'object' || seen.has(instance)) continue;
if (!isPluginController(metatype)) continue;
seen.add(instance);
this.register(instance, this.scanner.getAllMethodNames(Object.getPrototypeOf(instance)));
}
}
}
@@ -1,252 +0,0 @@
import {
HOOK_PERMISSION,
KNOWN_METHODS,
METHOD_PERMISSION,
UNCONDITIONAL_METHODS,
isKnownPermission,
} from '../../protocol/envelope';
import { getEntry, isPluginController, type ClassRef } from './metadata';
import type {
PluginHookContract,
PluginRpcContext,
PluginRpcEntry,
PluginRpcListing,
PluginRpcRegistryOptions,
} from './types';
interface BoundEntry {
instance: object;
className: string;
entry: PluginRpcEntry;
}
/** The `ClassName.methodName` convention every problem message uses. */
function describeBound(bound: BoundEntry): string {
return `${bound.className}.${bound.entry.methodName}`;
}
/** Nest's @Controller() path metadata key. Read only to reject a mis-decorated class. */
const NEST_PATH_METADATA = 'path';
/**
* reflect-metadata is loaded by Nest at boot, but the kit deliberately does not
* depend on it (see metadata.ts), so a bare vitest worker may not have it. Probing
* through an optional shape keeps the @Controller guard best-effort instead of a
* hard prerequisite.
*/
const reflectMaybe = Reflect as typeof Reflect & {
hasMetadata?: (metadataKey: string, target: object) => boolean;
};
/** Own + inherited method names, excluding constructor and Object.prototype. */
function enumerateMethodNames(instance: object): string[] {
const names = new Set<string>();
let proto: object | null = Object.getPrototypeOf(instance);
while (proto && proto !== Object.prototype) {
for (const name of Object.getOwnPropertyNames(proto)) {
if (name === 'constructor') continue;
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
if (typeof descriptor?.value === 'function') names.add(name);
}
proto = Object.getPrototypeOf(proto);
}
return [...names];
}
/**
* Holds every decorated plugin RPC entry bound to its provider instance, checks the
* decorator arguments against protocol/envelope.ts, and fills a per-plugin dispatch
* map with the subset that plugin was granted.
*
* Plain class with no DI so `createTestPluginRegistry` can build one without a Nest
* app; `PluginRpcRegistryService` is the DI-discovered subclass.
*/
export class PluginRpcRegistry {
private readonly bound: BoundEntry[] = [];
constructor(private readonly options: PluginRpcRegistryOptions = {}) {}
/**
* Records every decorated method of `instance`. `methodNames` (e.g. from Nest's
* MetadataScanner) narrows the scan; omitted, the prototype chain is enumerated.
*/
register(instance: object, methodNames?: readonly string[]): void {
const ctor = (instance as { constructor: unknown }).constructor;
if (!isPluginController(ctor)) {
throw new Error(`${(ctor as ClassRef).name} is not decorated with @PluginController()`);
}
if (reflectMaybe.hasMetadata?.(NEST_PATH_METADATA, ctor as object)) {
throw new Error(
`${(ctor as ClassRef).name} is a Nest @Controller. @PluginController must go on a provider class, ` +
'because @Injectable() rewrites the scope metadata @Controller() set',
);
}
const className = (ctor as ClassRef).name;
const names = methodNames ?? enumerateMethodNames(instance);
for (const name of new Set(names)) {
const entry = getEntry(ctor as ClassRef, name);
if (entry) this.bound.push({ instance, className, entry });
}
}
/**
* Re-checks every decorator argument against the runtime tables and throws ONCE
* with all problems listed. The type layer already pins these, but types evaporate
* under an `as` cast or a hand-emitted JS consumer, so the same invariant is
* asserted on both paths.
*/
validate(): void {
const problems: string[] = [];
const byMethod = new Map<string, BoundEntry[]>();
const hookFns = new Set<string>();
const coveredHooks = new Set<string>();
for (const bound of this.bound) {
const entry = bound.entry;
if (entry.kind === 'method') {
if (!(KNOWN_METHODS as readonly string[]).includes(entry.method)) {
problems.push(`method "${entry.method}" (${describeBound(bound)}) is not in KNOWN_METHODS`);
continue;
}
const expected = (METHOD_PERMISSION as Record<string, string>)[entry.method];
if (entry.permission !== expected) {
problems.push(
`method "${entry.method}" (${describeBound(bound)}) declares "${entry.permission}" ` +
`but METHOD_PERMISSION says "${expected}"`,
);
}
if (!isKnownPermission(entry.permission)) {
problems.push(
`method "${entry.method}" (${describeBound(bound)}) declares unknown permission "${entry.permission}"`,
);
}
} else if (entry.kind === 'open') {
if (!(UNCONDITIONAL_METHODS as readonly string[]).includes(entry.method)) {
problems.push(`open method "${entry.method}" (${describeBound(bound)}) is not in UNCONDITIONAL_METHODS`);
}
} else {
const expected = (HOOK_PERMISSION as Record<string, string | undefined>)[entry.hook];
if (!expected) {
problems.push(`hook "${entry.hook}" (${describeBound(bound)}) is not a HOOK_PERMISSION key`);
} else if (entry.permission !== expected) {
problems.push(
`hook "${entry.hook}" (${describeBound(bound)}) declares "${entry.permission}" ` +
`but HOOK_PERMISSION says "${expected}"`,
);
}
// Uniqueness is per (hook, fn), NOT one consumer per hook: photoProvider has
// three call sites and calendarSource two distinct fns.
const key = `${entry.hook}#${entry.fn}`;
if (hookFns.has(key)) {
problems.push(`hook fn "${key}" is declared twice (${describeBound(bound)})`);
}
hookFns.add(key);
coveredHooks.add(entry.hook);
}
if (entry.kind !== 'hook') {
const list = byMethod.get(entry.method) ?? [];
list.push(bound);
byMethod.set(entry.method, list);
}
}
for (const [method, list] of byMethod) {
if (list.length > 1) {
problems.push(`method "${method}" is handled by ${list.map(describeBound).join(' and ')}`);
}
}
if (this.options.requireTotalCoverage) {
for (const method of [...KNOWN_METHODS, ...UNCONDITIONAL_METHODS]) {
if (!byMethod.has(method)) problems.push(`method "${method}" has no handler`);
}
for (const hook of Object.keys(HOOK_PERMISSION)) {
if (!coveredHooks.has(hook)) {
problems.push(`hook "${hook}" has no host-side consumer (dead grant on the consent screen)`);
}
}
}
if (problems.length) throw new Error(`Invalid plugin RPC registry: ${problems.join('; ')}`);
}
/**
* Fills `map` with the handlers this plugin's grants unlock. Registration IS
* authorization, exactly as the legacy router does it: an ungranted method is
* ABSENT from the map rather than present-and-guarded, so an ungranted call still
* falls through the untouched miss branch in handle() to PERMISSION_DENIED (known)
* or UNKNOWN_METHOD (unknown).
*
* Per-plugin and per-host, never cached, because grants change on re-consent and
* the supervisor then rebuilds the host.
*
* Throws on a name the caller's map already holds, so a half-migrated method
* registered BOTH in the legacy constructor and here is a loud boot failure
* instead of a silent override.
*/
bindInto(
map: Map<string, (params: Record<string, unknown>, actingUserId: number | undefined) => unknown>,
granted: ReadonlySet<string>,
makeCtx: (actingUserId: number | undefined) => PluginRpcContext,
): void {
for (const bound of this.bound) {
const entry = bound.entry;
if (entry.kind === 'hook') continue;
if (entry.kind === 'method' && !granted.has(entry.permission)) continue;
if (map.has(entry.method)) {
throw new Error(
`plugin RPC method "${entry.method}" is registered twice ` +
`(${describeBound(bound)} and the legacy router)`,
);
}
const handler = (bound.instance as Record<string, (...args: unknown[]) => unknown>)[entry.methodName].bind(
bound.instance,
);
map.set(entry.method, (params, actingUserId) => handler(params, makeCtx(actingUserId)));
}
}
/** Every declared (hook, fn) contract, keyed `${hook}#${fn}`. */
hookContracts(): ReadonlyMap<string, PluginHookContract> {
const contracts = new Map<string, PluginHookContract>();
for (const bound of this.bound) {
const entry = bound.entry;
if (entry.kind !== 'hook') continue;
contracts.set(`${entry.hook}#${entry.fn}`, {
hook: entry.hook,
fn: entry.fn,
permission: entry.permission,
timeoutMs: entry.timeoutMs,
consumer: describeBound(bound),
});
}
return contracts;
}
/** The contract a call site relies on, or a throw naming what it asked for. */
hookContract(hook: string, fn: string): PluginHookContract {
const contract = this.hookContracts().get(`${hook}#${fn}`);
if (!contract) throw new Error(`no @PluginHook declaration for "${hook}#${fn}"`);
return contract;
}
/** The wire methods this registry owns, for the coverage ledger test. */
methodNames(): Set<string> {
const names = new Set<string>();
for (const bound of this.bound) {
if (bound.entry.kind !== 'hook') names.add(bound.entry.method);
}
return names;
}
list(): PluginRpcListing[] {
return this.bound.map(({ className, entry }) => ({
kind: entry.kind,
name: entry.kind === 'hook' ? `${entry.hook}#${entry.fn}` : entry.method,
permission: entry.kind === 'open' ? null : entry.permission,
className,
methodName: entry.methodName,
}));
}
}
@@ -1,19 +0,0 @@
import { PluginRpcRegistry } from './registry';
import type { PluginRpcRegistryOptions } from './types';
/**
* Builds a registry from hand-constructed `@PluginController()` instances, with no
* Nest app required. This is why the metadata store is a WeakMap rather than
* reflect-metadata: a bare vitest worker can assemble the same registry the
* container would.
*/
export function createTestPluginRegistry(
instances: readonly object[],
options: PluginRpcRegistryOptions = {},
): PluginRpcRegistry {
const registry = new PluginRpcRegistry(options);
for (const instance of instances) registry.register(instance);
// Same fail-fast contract as PluginRpcRegistryService.onModuleInit.
registry.validate();
return registry;
}
@@ -1,86 +0,0 @@
import type { HookKey, HookPermission, KnownMethod, UnconditionalMethod } from '../../protocol/envelope';
import type { PluginDataDb } from '../plugin-data.service';
/**
* Everything a plugin RPC handler may see. Built PER DISPATCH, never cached.
*
* `actingUserId` is HOST-bound: the supervisor resolves it from its invocation map
* before dispatch, and it is never taken from params. A plugin could otherwise set
* an `asUserId` field to any id and read another user's trips.
*
* `data` is a GETTER, resolved on every access and never captured. The reason is
* spelled out on `get data()` in plugin-host-deps.factory.ts: disable()/re-enable
* builds a NEW host while the old one's dispose() may still close the handle, so a
* captured handle leaves the new host throwing 'database connection is not open'.
* A constructor-injected DB in a singleton *Rpc class would additionally be a
* cross-plugin data leak, since these classes are per-app, not per-plugin.
*/
export interface PluginRpcContext {
readonly pluginId: string;
readonly actingUserId: number | undefined;
readonly data: PluginDataDb;
/**
* The inter-plugin capabilities. PER HOST, like everything else on this context:
* the router that backs them is created per plugin and binds THIS plugin as the
* caller, which is what lets it authorise a call against the declared dependency
* edge and the target's provides/emits allowlist.
*
* Typed structurally rather than imported, so the kit stays free of host imports
* (see rpc-kit/README.md). The host supplies the real router when it binds.
*/
readonly plugins: PluginRpcPeers;
}
/** What a plugin may do to its declared dependencies. */
export interface PluginRpcPeers {
call(targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
emit(event: string, payload: unknown): Promise<void>;
}
export type PluginRpcHandler = (params: Record<string, unknown>, ctx: PluginRpcContext) => unknown;
/**
* What a decorator records. `methodName` is the name of the decorated class method,
* `method` the wire name it answers to; they are deliberately independent.
*/
export type PluginRpcEntry =
| { kind: 'method'; methodName: string; method: KnownMethod; permission: string }
| { kind: 'open'; methodName: string; method: UnconditionalMethod }
| { kind: 'hook'; methodName: string; hook: HookKey; permission: string; fn: string; timeoutMs: number };
export interface PluginHookOptions<H extends HookKey> {
/** MUST equal HOOK_PERMISSION[hook]. The compiler enforces it, validate() re-checks it. */
permission: HookPermission<H>;
/** The function on the plugin's `hooks.<hook>` object, e.g. 'getWarnings'. */
fn: string;
/** Host to plugin budget for this fn. Defaults to 5000 to match the common case. */
timeoutMs?: number;
}
/** One declared (hook, fn) contract, for the hook call sites and their tests. */
export interface PluginHookContract {
hook: HookKey;
fn: string;
permission: string;
timeoutMs: number;
/** `ClassName.methodName` of the host-side consumer that declared it. */
consumer: string;
}
export interface PluginRpcListing {
kind: PluginRpcEntry['kind'];
/** The wire method, or `${hook}#${fn}` for a hook declaration. */
name: string;
/** null means unconditional (no grant check). */
permission: string | null;
className: string;
methodName: string;
}
export interface PluginRpcRegistryOptions {
/**
* Flip to true once the legacy router map is empty: validate() then also fails when
* a KNOWN_METHOD has no handler, or a hook has no host-side consumer.
*/
requireTotalCoverage?: boolean;
}
@@ -1,55 +0,0 @@
import { BadParams } from './rpc-errors';
/**
* The param coercions every plugin RPC handler shares, lifted verbatim out of
* rpc-host.ts so decorated *.rpc.ts handlers use the same ones.
*
* Their leniency is part of the published contract: num() accepts numeric strings
* and asPayload() wraps a non-object in { value }, so tightening either would reject
* calls that shipped plugins make today.
*/
export const num = (v: unknown, name: string): number => {
const n = typeof v === 'string' ? Number(v) : v;
if (typeof n !== 'number' || !Number.isFinite(n)) throw new BadParams(`${name} must be a number`);
return n;
};
export const str = (v: unknown, name: string): string => {
if (typeof v !== 'string') throw new BadParams(`${name} must be a string`);
return v;
};
export function asArgs(v: unknown): unknown[] {
if (v == null) return [];
if (Array.isArray(v)) return v;
throw new BadParams('args must be an array');
}
/**
* Coerce a db.tx `ops` param into a validated {sql, args}[] before it reaches the
* data db: each op must carry a string sql and, if present, an array of args.
*/
export function asTxOps(v: unknown): Array<{ sql: string; args?: unknown[] }> {
if (!Array.isArray(v)) throw new BadParams('ops must be an array of { sql, args }');
return v.map((op) => {
const o = (op ?? {}) as Record<string, unknown>;
return { sql: str(o.sql, 'ops[].sql'), args: asArgs(o.args) };
});
}
export function asPayload(v: unknown): Record<string, unknown> {
return v && typeof v === 'object' ? (v as Record<string, unknown>) : { value: v };
}
/**
* The message a failed Zod parse should carry into BAD_PARAMS.
*
* Every handler used to inline `error.issues[0]?.message ?? 'bad input'`, twenty
* copies of the same two-branch fallback that no test could reach, because a real
* parse failure always reports at least one issue. One copy is testable; twenty are
* twenty permanently uncovered branches.
*/
export function schemaMessage(error: { issues?: Array<{ message?: string }> }): string {
return error.issues?.[0]?.message ?? 'bad input';
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { PluginController, PluginMethod, PluginOpenMethod } from '../rpc-kit/decorators';
import { asArgs, asTxOps, str } from '../rpc-params';
import type { PluginRpcContext } from '../rpc-kit/types';
import { PluginController, PluginMethod, PluginOpenMethod } from '../../../../nest-rpc/rpc-kit/decorators';
import { asArgs, asTxOps, str } from '../../../../nest-rpc/rpc-params';
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
import { PluginUserSettingsService } from '../../plugin-user-settings.service';
/**
@@ -1,8 +1,8 @@
import { PluginController, PluginMethod } from '../rpc-kit/decorators';
import { PluginGuards } from '../plugin-guards.service';
import { BadParams, ForbiddenResource } from '../rpc-errors';
import { asPayload, num, str } from '../rpc-params';
import type { PluginRpcContext } from '../rpc-kit/types';
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service';
import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors';
import { asPayload, num, str } from '../../../../nest-rpc/rpc-params';
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
import { budgetFor } from '../plugin-host-state';
import { InjectRepository } from '@mikro-orm/nestjs';
import { PluginCapabilityAudit } from '../../../../db/entities/PluginCapabilityAudit.entity';
+5 -5
View File
@@ -1,9 +1,9 @@
import { InjectRepository } from '@mikro-orm/nestjs';
import { PluginController, PluginMethod } from '../rpc-kit/decorators';
import { PluginGuards } from '../plugin-guards.service';
import { BadParams, ForbiddenResource } from '../rpc-errors';
import { num, str } from '../rpc-params';
import type { PluginRpcContext } from '../rpc-kit/types';
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service';
import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors';
import { num, str } from '../../../../nest-rpc/rpc-params';
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
import { PluginEntityMetadata } from '../../../../db/entities/PluginEntityMetadata.entity';
import type { PluginEntityMetadataRepository } from '../../../../db/repositories/PluginEntityMetadata.repository';
import { Trips } from '../../../../db/entities/Trips.entity';
@@ -1,4 +1,4 @@
import { PluginController, PluginHook } from './host/rpc-kit/decorators';
import { PluginController, PluginHook } from '../../nest-rpc/rpc-kit/decorators';
import { PluginRuntimeService } from './plugin-runtime.service';
/** What a notification channel is handed for one message. */
@@ -28,8 +28,8 @@ import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginHooks } from './plugin-hooks.service';
import { PluginRegistryService } from './registry/registry.service';
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
import { PluginRpcRegistryService } from './host/rpc-kit/registry.service';
import { PluginGuardsModule } from './host/plugin-guards.module';
import { PluginRpcRegistryService } from '../../nest-rpc/rpc-kit/registry.service';
import { PluginGuardsModule } from '../../nest-rpc/plugin-guards.module';
import { PluginOAuthModule } from './oauth/plugin-oauth.module';
import { DbRpc } from './host/rpc/db.rpc';
import { MetaRpc } from './host/rpc/meta.rpc';