Move the tags plugin surface onto the decorators

Wires the registry into the host and takes the first domain across, so the kit
lands with a worked example rather than as scaffolding nobody uses yet.

The registry is an additive, optional fourth constructor parameter on
PluginRpcHost, so all 107 existing construction sites keep compiling untouched;
that is what makes the rest of the rollout a per-domain move instead of a
big-bang one. bindInto runs LAST in the constructor, so a method still owned by
one of the has() blocks collides loudly instead of being silently overridden.

tags is the right pilot: four methods, a service that is already DI-native, and
it exercises the read/write permission split, the userless refusal and a
BadParams write. Handler bodies and messages are verbatim; only deps.foo(...)
became this.tags... and uid became ctx.actingUserId.

dispatch now strips the supervisor's _inv marker. The supervisor resolves the
acting user from it before dispatch and then passes the request on untouched, so
it has been visible to every handler and is in effect a reserved param name.
Nothing reads it: auditResource takes named fields only, and the one handler
that touches the params object as a whole (packing.setBagMembers) reads a named
field off it. Dropping it keeps a future strict parse from rejecting calls every
shipped plugin makes.

Two tests carry the rollout from here. rpc-coverage.test.ts derives both owner
sets from the code and proves they partition the method vocabulary exactly, so a
PR that moves a method and forgets to delete the legacy registration fails in
CI. And because a decorated class that no module registers is invisible to
discovery, with every call to it coming back PERMISSION_DENIED and no other
symptom, tags.rpc.test.ts asserts TagsRpc is actually listed in providers.
This commit is contained in:
Maurice
2026-08-09 11:36:17 +02:00
committed by Maurice
parent 6b6fbbd94c
commit 9b3d37ea29
11 changed files with 639 additions and 251 deletions
@@ -38,6 +38,7 @@ import { FilesService } from '../../files/files.service';
import { CollabService } from '../../collab/collab.service';
import { VacayService } from '../../vacay/vacay.service';
import { PluginRpcHost, ForbiddenResource, BadParams } from './rpc-host';
import { PluginRpcRegistryService } from './rpc-kit/registry.service';
import { appendAudit } from './plugin-audit';
import { getPluginDataDb, budgetFor } from './plugin-host-state';
@@ -167,6 +168,10 @@ export class PluginHostDepsFactory {
private readonly notifications: NotificationsService,
private readonly membership: TripMembershipService,
private readonly journey: JourneyDomainService,
// Appended last and OPTIONAL so the hand-wired 26-arg construction in
// plugin-host-deps.factory.test.ts keeps compiling. Handed to every host it
// builds, which is how decorated *.rpc.ts handlers reach the dispatch map.
private readonly rpcRegistry?: PluginRpcRegistryService,
) {}
/**
@@ -858,18 +863,6 @@ export class PluginHostDepsFactory {
listCategories: () => this.categories.list() as unknown[],
tripMembers: (tripId) =>
this.db.prepare('SELECT u.id, u.username, u.display_name, u.avatar FROM trip_members tm JOIN users u ON u.id = tm.user_id WHERE tm.trip_id = ?').all(tripId) as unknown[],
// --- Tags (the acting user's own; ownership re-checked before a write). ---
listTagsForUser: (userId) => this.tags.list(userId) as unknown[],
createTagForUser: (userId, name, color) => this.tags.create(userId, name, color),
updateTagForUser: (userId, tagId, name, color) => {
if (!this.tags.getByIdAndUser(tagId, userId)) throw new ForbiddenResource(`no tag ${tagId} for this user`);
return this.tags.update(tagId, name, color);
},
deleteTagForUser: (userId, tagId) => {
if (!this.tags.getByIdAndUser(tagId, userId)) throw new ForbiddenResource(`no tag ${tagId} for this user`);
this.tags.remove(tagId);
return { deleted: true };
},
// --- Todos (core, trip-scoped; the app's 'packing_edit' permission). ---
canEditTodos: (tripId, userId) => this.canEditTripAs('packing_edit', tripId, userId),
listTodos: (tripId) => this.todos.listItems(String(tripId)) as unknown[],
@@ -939,6 +932,6 @@ export class PluginHostDepsFactory {
.run(id, entityType, entityId, key);
return { deleted: res.changes > 0 };
},
});
}, this.rpcRegistry);
}
}
+37 -60
View File
@@ -21,6 +21,14 @@ import {
import type { PluginDataDb } from './plugin-data.service';
import { stripEmoji } from '../text-sanitize';
import { auditResource, isAuditable } from './plugin-audit';
import { BadParams, ForbiddenResource } from './rpc-errors';
import { asArgs, asPayload, asTxOps, num, str } from './rpc-params';
import type { PluginRpcRegistry } from './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
// so every existing importer keeps working unchanged.
export { BadParams, ForbiddenResource };
/**
* The per-plugin capability router (#plugins, M1) — the ENFORCEMENT POINT.
@@ -33,9 +41,6 @@ import { auditResource, isAuditable } from './plugin-audit';
* Runs in the HOST (parent) process.
*/
/** Thrown by a handler when the acting user may not touch the requested resource. */
export class ForbiddenResource extends Error {}
interface CoreDb {
prepare(sql: string): {
all(...args: unknown[]): unknown[];
@@ -240,10 +245,6 @@ export interface HostDeps {
listCategories(): unknown[];
tripMembers(tripId: number): unknown[];
// --- Tags (the acting user's own; no trip) ---
listTagsForUser(userId: number): unknown[];
createTagForUser(userId: number, name: string, color: string | undefined): unknown;
updateTagForUser(userId: number, tagId: number, name: string | undefined, color: string | undefined): unknown;
deleteTagForUser(userId: number, tagId: number): unknown;
// --- Todos (core, trip-scoped; the 'packing_edit' permission, like the REST path) ---
canEditTodos(tripId: number, userId: number): boolean;
listTodos(tripId: number): unknown[];
@@ -261,17 +262,6 @@ export interface HostDeps {
type Handler = (params: Record<string, unknown>, actingUserId: number | undefined) => unknown;
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;
};
const str = (v: unknown, name: string): string => {
if (typeof v !== 'string') throw new BadParams(`${name} must be a string`);
return v;
};
export class BadParams extends Error {}
// Mirrors the STRING_LIMITS the places REST controller enforces (the @trek/shared
// schema doesn't), so the plugin write path rejects the same oversized fields.
const PLACE_STR_LIMITS: Record<string, number> = { name: 200, description: 2000, address: 500, notes: 2000 };
@@ -289,6 +279,11 @@ export class PluginRpcHost {
private readonly pluginId: string,
granted: ReadonlySet<string>,
private readonly deps: HostDeps,
// Additive and OPTIONAL, the same convention plugin-runtime.service.ts already
// uses for its own late-added params. Every existing
// `new PluginRpcHost(id, granted, deps)` site keeps compiling untouched, which is
// what makes the decorator rollout a per-domain move instead of a big-bang one.
registry?: PluginRpcRegistry,
) {
const has = (p: string) => granted.has(p);
@@ -951,30 +946,7 @@ export class PluginRpcHost {
// Global, read-only reference list — carries no tenant data.
this.methods.set('categories.list', () => deps.listCategories());
}
if (has('db:read:tags')) {
// The acting user's own tags (not trip-scoped) — refuse a userless context.
this.methods.set('tags.list', (_p, uid) => {
if (uid === undefined) throw new ForbiddenResource('tag reads require an authenticated user context');
return deps.listTagsForUser(uid);
});
}
if (has('db:write:tags')) {
this.methods.set('tags.create', (p, uid) => {
if (uid === undefined) throw new ForbiddenResource('tag writes require an authenticated user context');
const input = asPayload(p.input);
if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('tag name is required');
return deps.createTagForUser(uid, input.name, typeof input.color === 'string' ? input.color : undefined);
});
this.methods.set('tags.update', (p, uid) => {
if (uid === undefined) throw new ForbiddenResource('tag writes require an authenticated user context');
const input = asPayload(p.input);
return deps.updateTagForUser(uid, num(p.tagId, 'tagId'), typeof input.name === 'string' ? input.name : undefined, typeof input.color === 'string' ? input.color : undefined);
});
this.methods.set('tags.delete', (p, uid) => {
if (uid === undefined) throw new ForbiddenResource('tag writes require an authenticated user context');
return deps.deleteTagForUser(uid, num(p.tagId, 'tagId'));
});
}
// tags.* now lives in src/nest/tags/tags.rpc.ts, bound through the registry below.
if (has('db:read:todos')) {
this.methods.set('todos.list', (p, uid) => this.tripRead(p, uid, () => deps.listTodos(num(p.tripId, 'tripId'))));
}
@@ -1155,6 +1127,21 @@ export class PluginRpcHost {
if (uid === undefined) return { value: undefined };
return { value: deps.getUserSetting(this.pluginId, uid, str(p.key, 'key')) };
});
// LAST on purpose: a method still owned by one of the has() blocks above then
// collides loudly in bindInto instead of being silently overridden, which is the
// failure mode a half-finished domain move would otherwise have.
//
// `deps.data` is already the lazy per-access getter the factory supplies, so
// passing it through a getter here preserves the disable/re-enable semantics
// exactly and the kit never needs to know about plugin-host-state.
registry?.bindInto(this.methods, granted, (actingUserId) => ({
pluginId,
actingUserId,
get data() {
return deps.data;
},
}));
}
/**
@@ -1242,7 +1229,14 @@ export class PluginRpcHost {
}
async dispatch(req: RpcRequest, actingUserId?: number): Promise<RpcResponse | RpcError> {
const params = (req.params ?? {}) as Record<string, unknown>;
const raw = (req.params ?? {}) as Record<string, unknown>;
// The supervisor resolves the acting user from `_inv` BEFORE dispatch and passes
// the request on untouched, so `_inv` is visible to every handler today and is in
// effect a reserved param name. Strip it here: no handler and no audit reads
// anything but named fields, and dropping it keeps a future strict schema parse
// from rejecting calls every shipped plugin makes.
const { _inv, ...stripped } = raw;
const params = '_inv' in raw ? stripped : raw;
const res = await this.handle(req, params, actingUserId);
// Audit the core-data / broadcast surface (incl. denials) at the boundary.
if (this.deps.audit && isAuditable(req.method)) {
@@ -1301,23 +1295,6 @@ export class PluginRpcHost {
}
}
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. */
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) };
});
}
function asPayload(v: unknown): Record<string, unknown> {
return v && typeof v === 'object' ? (v as Record<string, unknown>) : { value: v };
}
/**
* The reservation body is passthrough by contract, but a malformed `endpoints`
* array would otherwise fail DEEP in the service (NOT-NULL mid-transaction) or be
+12 -5
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { DiscoveryModule } from '@nestjs/core';
import { JourneyDomainModule } from '../journey/journey-domain.module';
import { PluginsController } from './plugins.controller';
import { PluginsFeedController } from './plugins-feed.controller';
@@ -26,6 +27,8 @@ import { PluginsService } from './plugins.service';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginRegistryService } from './registry/registry.service';
import { PluginHostDepsFactory } from './host/plugin-host-deps.factory';
import { PluginRpcRegistryService } from './host/rpc-kit/registry.service';
import { PluginGuards } from './host/plugin-guards.service';
import { TagsModule } from '../tags/tags.module';
import { CategoriesModule } from '../categories/categories.module';
import { BudgetModule } from '../budget/budget.module';
@@ -58,11 +61,15 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module'
@Module({
// The DI-native domain services the plugin host wiring injects
// (PluginHostDepsFactory); DatabaseModule is @Global, so not listed.
imports: [TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule, FilesModule, CollabModule, VacayModule, TripsModule, PermissionsModule, AuditModule, AddonsModule, PlacesModule, CollectionsModule, AtlasModule, NotificationsModule, TripMembershipModule, JourneyDomainModule],
// DiscoveryModule is what lets PluginRpcRegistryService find the @PluginController
// providers at boot.
imports: [DiscoveryModule, TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule, FilesModule, CollabModule, VacayModule, TripsModule, PermissionsModule, AuditModule, AddonsModule, PlacesModule, CollectionsModule, AtlasModule, NotificationsModule, TripMembershipModule, JourneyDomainModule],
controllers: [PluginsController, PluginsFeedController, PluginsProxyController, PluginFrameController, PlaceDetailsController, TripWarningsController, ViewContributionsController, TripCardContributionsController, PluginPhotosController, PluginCalendarController, MapMarkersController, MapLayersController, PluginRoutesController, DayScheduleController, DayTintsController, PdfSectionsController, AtlasLayersController, JournalEntryRowsController, PluginUserSettingsController, PluginOAuthController, PluginActivityController],
providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory],
// Exported so the admin addon-toggle handler can cascade-disable plugins whose
// required addon was just turned off (#plugins dependencies).
exports: [PluginRuntimeService],
providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory, PluginRpcRegistryService, PluginGuards],
// PluginRuntimeService is exported so the admin addon-toggle handler can
// cascade-disable plugins whose required addon was just turned off (#plugins
// dependencies). PluginGuards is exported so a domain module can inject it into
// its own <domain>.rpc.ts without importing the plugin host.
exports: [PluginRuntimeService, PluginGuards],
})
export class PluginsModule {}
+5 -1
View File
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { TagsController } from './tags.controller';
import { TagsMcp } from './tags.mcp';
import { TagsRpc } from './tags.rpc';
import { TagsService } from './tags.service';
import { AuthModule } from '../auth/auth.module';
@@ -8,7 +9,10 @@ import { AuthModule } from '../auth/auth.module';
@Module({
imports: [AuthModule],
controllers: [TagsController],
providers: [TagsService, TagsMcp],
// TagsRpc must stay in providers: the plugin RPC registry discovers marked
// PROVIDERS only, and a missing entry here would leave tags.* answering
// PERMISSION_DENIED with no other symptom.
providers: [TagsService, TagsMcp, TagsRpc],
// For in-container consumers (PluginHostDepsFactory).
exports: [TagsService],
})
+71
View File
@@ -0,0 +1,71 @@
import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
import { asPayload, num } from '../plugins/host/rpc-params';
import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
import { TagsService } from './tags.service';
/**
* The tags surface a plugin may reach (#plugins). Tags are the acting user's own and
* are not trip-scoped, so there is no membership gate here; what every handler does
* need is a HOST-bound acting user, and a write additionally re-checks that the tag
* belongs to that user.
*
* Moved verbatim out of the router and the deps factory. The messages differ by one
* word between the read and the writes ("tag reads" vs "tag writes"), which is why
* the read throws inline instead of going through PluginGuards.requireActor.
*/
@PluginController()
export class TagsRpc {
constructor(private readonly tags: TagsService) {}
@PluginMethod('tags.list', { permission: 'db:read:tags' })
list(_params: Record<string, unknown>, ctx: PluginRpcContext): unknown[] {
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource('tag reads require an authenticated user context');
}
return this.tags.list(ctx.actingUserId) as unknown[];
}
@PluginMethod('tags.create', { permission: 'db:write:tags' })
create(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource('tag writes require an authenticated user context');
}
const input = asPayload(params.input);
if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('tag name is required');
return this.tags.create(ctx.actingUserId, input.name, typeof input.color === 'string' ? input.color : undefined);
}
@PluginMethod('tags.update', { permission: 'db:write:tags' })
update(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource('tag writes require an authenticated user context');
}
const input = asPayload(params.input);
const tagId = num(params.tagId, 'tagId');
this.requireOwnTag(tagId, ctx.actingUserId);
return this.tags.update(
tagId,
typeof input.name === 'string' ? input.name : undefined,
typeof input.color === 'string' ? input.color : undefined,
);
}
@PluginMethod('tags.delete', { permission: 'db:write:tags' })
delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource('tag writes require an authenticated user context');
}
const tagId = num(params.tagId, 'tagId');
this.requireOwnTag(tagId, ctx.actingUserId);
this.tags.remove(tagId);
return { deleted: true };
}
/** Ownership is re-checked per write, so a plugin cannot edit another user's tag. */
private requireOwnTag(tagId: number, userId: number): void {
if (!this.tags.getByIdAndUser(tagId, userId)) {
throw new ForbiddenResource(`no tag ${tagId} for this user`);
}
}
}