Finish the plugin RPC decorator rollout

The last 20 wire methods move onto the decorators: db.* and the three
unconditional methods (DbRpc), meta.* (MetaRpc) and the host-mediated surface
of users/broadcasts/notify/ai/oauth/scheduler (HostSurfaceRpc). That closes the
ledger at 113/113, so the legacy has() blocks in rpc-host.ts are gone and the
router is down to what was never domain-specific: build the granted subset of
the dispatch map, dispatch, audit, map errors.

PluginHostDepsFactory was the 26-argument wiring sheet behind those blocks. With
the handlers in the domains it has two dependencies left, so it is now
PluginRpcHostFactory: the plugin's own sqlite handle, the inter-plugin router
bound with this plugin as the caller, and the audit sink.

The 18 host-to-plugin hook calls get the same treatment. They used to spell out
the fn name and the timeout at each controller, which meant nothing checked that
a hook:* grant on the consent screen had a consumer behind it, that the fn
matched what the SDK documents, or that two call sites agreed on the budget.
PluginHooks declares all 18 with @PluginHook and performs them, and the
controllers call it by name.

With both halves complete, requireTotalCoverage goes on: a KNOWN_METHOD without
a handler, or a hook without a consumer, now fails app boot instead of surfacing
as a PERMISSION_DENIED nobody can explain.
This commit is contained in:
Maurice
2026-08-09 17:15:53 +02:00
committed by Maurice
parent 611f94e820
commit f72aba0c91
74 changed files with 1942 additions and 2164 deletions
@@ -15,15 +15,15 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () =>
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { AtlasLayersController } from '../../../src/nest/plugins/atlas-layers.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
atlasLayers: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new AtlasLayersController(runtime), runtime };
}
const layer = (over: Record<string, unknown> = {}) => ({ id: 'l1', countries: [{ code: 'FR' }], ...over });
@@ -53,7 +53,7 @@ describe('AtlasLayersController', () => {
countries: [{ code: 'FR', tone: 'success', label: 'Paris trip' }],
}]);
// user-scoped: empty args, the acting user is bound host-side
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'atlasLayerProvider', 'getLayers', [], 5, 5000);
expect(runtime.atlasLayers).toHaveBeenCalledWith('p1', 5);
});
it('uppercase-coerces codes, drops anything that is not ISO alpha-2, defaults a bad tone', async () => {
@@ -21,15 +21,15 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { DayScheduleController } from '../../../src/nest/plugins/day-schedule.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
daySchedule: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new DayScheduleController(runtime, new DatabaseService(dbConn)), runtime };
}
const item = (over: Record<string, unknown> = {}) => ({ id: 's1', dayId: 10, label: 'Charging', ...over });
@@ -97,6 +97,6 @@ describe('DayScheduleController', () => {
it('skips the day lookup entirely when no provider is active', async () => {
const { c, runtime } = controller(() => [item()], []);
expect((await c.get('1', req(5))).items).toEqual([]);
expect(runtime.invokeHook).not.toHaveBeenCalled();
expect(runtime.daySchedule).not.toHaveBeenCalled();
});
});
@@ -21,15 +21,15 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { DayTintsController } from '../../../src/nest/plugins/day-tints.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
dayTints: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new DayTintsController(runtime, new DatabaseService(dbConn)), runtime };
}
const tint = (over: Record<string, unknown> = {}) => ({ dayId: 10, tone: 'success', ...over });
@@ -222,6 +222,6 @@ describe('DayTintsController', () => {
it('skips the day lookup entirely when no provider is active', async () => {
const { c, runtime } = controller(() => [tint()], []);
expect((await c.get('1', req(5))).tints).toEqual([]);
expect(runtime.invokeHook).not.toHaveBeenCalled();
expect(runtime.dayTints).not.toHaveBeenCalled();
});
});
+549
View File
@@ -0,0 +1,549 @@
/**
* The plugin surface that belongs to no domain: the plugin's own sqlite (DbRpc), its
* namespaced entity metadata (MetaRpc) and the host-mediated calls (HostSurfaceRpc —
* user lookup, broadcasts, notifications, LLM, OAuth, scheduler).
*
* These cases used to live in plugin-host-deps.factory.test.ts, which tested the same
* behaviour through a 26-argument wiring sheet. Same requests, same expected codes;
* what changed is that they now run against three decorated classes and a real
* in-memory core DB, and that the host is built by the production factory.
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const { broadcast, broadcastToUser } = vi.hoisted(() => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// A real in-memory core db, so the metadata SQL and the entity->trip resolution run
// for real. Trip 1 is owned by user 5; user 6 is a member; user 9 shares nothing.
vi.mock('../../../src/db/database', () => {
const Database = require('better-sqlite3');
const d = new Database(':memory:');
d.exec(`
CREATE TABLE trips (id INTEGER PRIMARY KEY, user_id INTEGER);
CREATE TABLE places (id INTEGER PRIMARY KEY, trip_id INTEGER);
CREATE TABLE days (id INTEGER PRIMARY KEY, trip_id INTEGER);
CREATE TABLE reservations (id INTEGER PRIMARY KEY, trip_id INTEGER);
CREATE TABLE day_accommodations (id INTEGER PRIMARY KEY, trip_id INTEGER);
CREATE TABLE users (id INTEGER PRIMARY KEY, role TEXT, username TEXT, display_name TEXT, avatar TEXT, email TEXT);
CREATE TABLE trip_members (trip_id INTEGER, user_id INTEGER);
CREATE TABLE plugin_entity_metadata (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, entity_type TEXT, entity_id INTEGER, key TEXT, value TEXT, updated_at TEXT, UNIQUE(plugin_id, entity_type, entity_id, key));
CREATE TABLE plugin_capability_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, acting_user_id INTEGER, method TEXT, resource TEXT, code TEXT, ts TEXT, prev_hash TEXT, hash TEXT);
CREATE TABLE plugin_scheduled_tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT NOT NULL, name TEXT NOT NULL, due_at INTEGER NOT NULL, payload TEXT NOT NULL DEFAULT 'null', every_ms INTEGER, created_at TEXT DEFAULT (datetime('now')), UNIQUE(plugin_id, name));
`);
d.prepare('INSERT INTO trips (id, user_id) VALUES (1, 5)').run();
d.prepare('INSERT INTO places (id, trip_id) VALUES (7, 1)').run();
d.prepare('INSERT INTO days (id, trip_id) VALUES (3, 1)').run();
d.prepare('INSERT INTO reservations (id, trip_id) VALUES (40, 1)').run();
d.prepare('INSERT INTO day_accommodations (id, trip_id) VALUES (11, 1)').run();
d.prepare("INSERT INTO users (id, role, username, display_name) VALUES (5, 'trip_owner', 'owner', 'Owner')").run();
d.prepare("INSERT INTO users (id, role, username, display_name) VALUES (6, 'user', 'ada', 'Ada')").run();
d.prepare("INSERT INTO users (id, role, username, display_name) VALUES (9, 'user', 'eve', 'Eve')").run();
d.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (1, 6)').run();
return {
db: d,
canAccessTrip: (tripId: number, userId: number) =>
tripId === 1 && (userId === 5 || userId === 6) ? { id: 1, user_id: 5 } : undefined,
};
});
vi.mock('../../../src/websocket', () => ({ broadcast, broadcastToUser }));
const notifySend = vi.fn(async () => undefined);
const { llmExtract } = vi.hoisted(() => ({
llmExtract: vi.fn(async (input: { text?: string }) => [{ text: `answer:${input.text ?? ''}` }]),
}));
vi.mock('../../../src/nest/llm-parse/llm-client.factory', () => ({ createLlmClient: vi.fn(() => ({ extract: llmExtract })) }));
// readUserSettingDecrypted is a bare function export, not an injected service, so it
// stays a path mock.
vi.mock('../../../src/nest/plugins/plugins.service', () => ({
readUserSettingDecrypted: vi.fn((_pid: string, uid: number, key: string) => (uid === 5 && key === 'apiKey' ? 'k-5' : undefined)),
}));
import { PluginRpcHostFactory, type PluginCallRouter } from '../../../src/nest/plugins/host/plugin-rpc-host.factory';
import { PluginRpcRegistryService } from '../../../src/nest/plugins/host/rpc-kit/registry.service';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
import { MetaRpc } from '../../../src/nest/plugins/host/rpc/meta.rpc';
import { HostSurfaceRpc } from '../../../src/nest/plugins/host/rpc/host-surface.rpc';
import { getPluginDataDb, closePluginDataDb } from '../../../src/nest/plugins/host/plugin-host-state';
import { db as mockDb } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver';
import type { PluginOAuthService } from '../../../src/nest/plugins/plugin-oauth.service';
import type { RpcError, RpcResponse } from '../../../src/nest/plugins/protocol/envelope';
const checkPermission = vi.fn(() => true as boolean);
const permissions = { checkPermission } as unknown as PermissionsService;
const addons = { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService;
const notifications = { send: notifySend } as unknown as NotificationsService;
// user 7 has no provider configured; everyone else resolves to a stub config.
const llmConfig = {
resolve: vi.fn((uid: number) => (uid === 7 ? null : { provider: 'openai', model: 'gpt-x', baseUrl: undefined, apiKey: 'sekret' })),
} as unknown as LlmConfigResolver;
const oauth = {
async getAccessToken(_pid: string, uid: number) {
return uid === 5 ? 'tok-5' : null;
},
} as unknown as PluginOAuthService;
const dbs = new DatabaseService(mockDb);
const guards = new PluginGuards(dbs, permissions, addons);
const registry = createTestPluginRegistry([
new DbRpc(),
new MetaRpc(dbs, guards),
new HostSurfaceRpc(dbs, new RealtimeService(), notifications, llmConfig, oauth, guards),
]);
const factory = new PluginRpcHostFactory(dbs, registry as unknown as PluginRpcRegistryService);
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
const makeHost = (id: string, ...perms: string[]) => factory.create(id, new Set(perms), stubRouter);
type Res = RpcResponse & Partial<RpcError>;
// The acting user is a REST arg, not a defaulted one: an explicit `undefined` has to
// stay undefined (that is the userless-context case), and a default parameter would
// quietly turn it back into user 5.
const call = (
host: ReturnType<typeof makeHost>,
method: string,
params: Record<string, unknown> = {},
...uid: (number | undefined)[]
): Promise<Res> => host.dispatch({ k: 'req', id: 'x', method, params }, uid.length ? uid[0] : 5) as Promise<Res>;
let tmp: string;
beforeAll(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'trekplug-hostrpc-'));
process.env.TREK_PLUGINS_DATA_DIR = tmp;
});
afterAll(() => {
closePluginDataDb('wired');
delete process.env.TREK_PLUGINS_DATA_DIR;
fs.rmSync(tmp, { recursive: true, force: true });
});
describe('DbRpc — the plugin\'s own sqlite', () => {
it('HOSTRPC-001 caches one data db per plugin id', () => {
expect(getPluginDataDb('wired')).toBe(getPluginDataDb('wired'));
});
it('HOSTRPC-002 a granted db:own call runs against the plugin db', async () => {
const host = makeHost('wired', 'db:own');
expect((await call(host, 'db.migrate', { id: '001', sql: 'CREATE TABLE t (v TEXT)' })).ok).toBe(true);
expect((await call(host, 'db.exec', { sql: "INSERT INTO t (v) VALUES ('a')" })).ok).toBe(true);
const rows = await call(host, 'db.query', { sql: 'SELECT v FROM t' });
expect(rows.result).toEqual([{ v: 'a' }]);
});
it('HOSTRPC-003 db.tx dispatches an atomic batch; malformed ops are BAD_PARAMS', async () => {
const host = makeHost('wtx', 'db:own');
await call(host, 'db.migrate', { id: '001', sql: 'CREATE TABLE kv (k TEXT, n INTEGER)' });
const res = await call(host, 'db.tx', {
ops: [
{ sql: 'INSERT INTO kv (k, n) VALUES (?, ?)', args: ['a', 1] },
{ sql: 'SELECT n FROM kv WHERE k = ?', args: ['a'] },
],
});
expect((res.result as { results: unknown[] }).results).toEqual([{ changes: 1 }, { rows: [{ n: 1 }] }]);
expect((await call(host, 'db.tx', { ops: [{ sql: 42 }] })).error?.code).toBe('BAD_PARAMS');
closePluginDataDb('wtx');
});
it('HOSTRPC-004 without db:own not one of the four is reachable', async () => {
const host = makeHost('wnogrant');
for (const method of ['db.query', 'db.exec', 'db.migrate', 'db.tx']) {
expect((await call(host, method, { sql: 'SELECT 1', id: '1', ops: [] })).error?.code).toBe('PERMISSION_DENIED');
}
});
it('HOSTRPC-005 two plugins never see each other\'s tables', async () => {
// The regression this guards: DbRpc is a SINGLETON that serves every plugin, so a
// handle captured in a field or a closure would hand plugin B the rows of whichever
// plugin happened to construct it first.
const a = makeHost('tenant-a', 'db:own');
const b = makeHost('tenant-b', 'db:own');
await call(a, 'db.migrate', { id: '001', sql: 'CREATE TABLE secrets (v TEXT)' });
await call(a, 'db.exec', { sql: "INSERT INTO secrets (v) VALUES ('a-only')" });
const leaked = await call(b, 'db.query', { sql: 'SELECT v FROM secrets' });
expect(leaked.ok).toBe(false);
expect(leaked.error?.code).toBe('HOST_ERROR');
expect(leaked.error?.message).toMatch(/no such table/i);
// …and plugin A still reads its own row afterwards.
expect((await call(a, 'db.query', { sql: 'SELECT v FROM secrets' })).result).toEqual([{ v: 'a-only' }]);
closePluginDataDb('tenant-a');
closePluginDataDb('tenant-b');
});
it('HOSTRPC-006 a handle closed WITHOUT eviction is recreated, not reused dead', () => {
const a = getPluginDataDb('closedcache');
expect(a.isOpen()).toBe(true);
// The supervisor's dispose() path: close the handle but leave it cached.
a.close();
const b = getPluginDataDb('closedcache');
expect(b).not.toBe(a);
expect(b.isOpen()).toBe(true);
closePluginDataDb('closedcache');
});
it('HOSTRPC-007 closePluginDataDb drops the cached handle', () => {
const a = getPluginDataDb('transient');
closePluginDataDb('transient');
const b = getPluginDataDb('transient');
expect(a).not.toBe(b);
closePluginDataDb('transient');
});
});
describe('DbRpc — the unconditional three', () => {
afterAll(() => closePluginDataDb('open3'));
it('HOSTRPC-008 plugins.call and events.emit route through the host\'s own router', async () => {
const calls: unknown[] = [];
const emits: unknown[] = [];
const router: PluginCallRouter = {
callPlugin: async (callerId, targetId, fn, args, uid) => {
calls.push({ callerId, targetId, fn, args, uid });
return { echoed: true };
},
emitPluginEvent: (sourceId, event, payload) => {
emits.push({ sourceId, event, payload });
},
};
// No permission granted at all — these two are registered unconditionally.
const host = factory.create('open3', new Set(), router);
const res = await call(host, 'plugins.call', { targetId: 'other', fn: 'sum', args: [1, 2] }, 5);
expect(res.result).toEqual({ echoed: true });
// The caller id comes from the HOST, never from params, which is what lets the
// router authorise the dependency edge.
expect(calls).toEqual([{ callerId: 'open3', targetId: 'other', fn: 'sum', args: [1, 2], uid: 5 }]);
expect((await call(host, 'events.emit', { event: 'ping', payload: { a: 1 } }, 5)).result).toEqual({ ok: true });
expect(emits).toEqual([{ sourceId: 'open3', event: 'ping', payload: { a: 1 } }]);
});
it('HOSTRPC-009 settings.get returns the acting user\'s decrypted value; userless yields undefined', async () => {
const host = makeHost('open3');
expect((await call(host, 'settings.get', { key: 'apiKey' }, 5)).result).toEqual({ value: 'k-5' });
expect((await call(host, 'settings.get', { key: 'apiKey' }, undefined)).result).toEqual({ value: undefined });
// Another user's value is simply not there — the read is per acting user.
expect((await call(host, 'settings.get', { key: 'apiKey' }, 6)).result).toEqual({ value: undefined });
});
it('HOSTRPC-010 a missing key is BAD_PARAMS, not a silent undefined', async () => {
expect((await call(makeHost('open3'), 'settings.get', {}, 5)).error?.code).toBe('BAD_PARAMS');
});
});
describe('MetaRpc — namespaced entity metadata', () => {
beforeEach(() => {
checkPermission.mockReset();
checkPermission.mockReturnValue(true);
});
afterAll(() => closePluginDataDb('meta'));
it('HOSTRPC-011 round-trips and enforces the key/value/access limits', async () => {
const host = makeHost('meta', 'db:meta');
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k', value: { a: 1 } })).ok).toBe(true);
expect((await call(host, 'meta.get', { entityType: 'trip', entityId: 1, key: 'k' })).result).toEqual({ a: 1 });
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k', value: 2 })).ok).toBe(true); // upsert
expect((await call(host, 'meta.list', { entityType: 'place', entityId: 7 })).ok).toBe(true); // place -> trip 1
expect((await call(host, 'meta.delete', { entityType: 'trip', entityId: 1, key: 'k' })).result).toEqual({ deleted: true });
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'x'.repeat(300), value: 1 })).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'big', value: 'y'.repeat(70000) })).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 2, key: 'k', value: 1 })).error?.code).toBe('RESOURCE_FORBIDDEN');
});
it('HOSTRPC-012 an unreadable value comes back as null rather than throwing', async () => {
const host = makeHost('meta', 'db:meta');
await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'corrupt', value: 1 });
(mockDb as unknown as { prepare(sql: string): { run(...a: unknown[]): unknown } })
.prepare("UPDATE plugin_entity_metadata SET value='{not json' WHERE plugin_id='meta' AND key='corrupt'")
.run();
expect((await call(host, 'meta.get', { entityType: 'trip', entityId: 1, key: 'corrupt' })).result).toBeNull();
const listed = (await call(host, 'meta.list', { entityType: 'trip', entityId: 1 })).result as Record<string, unknown>;
expect(listed.corrupt).toBeNull();
await call(host, 'meta.delete', { entityType: 'trip', entityId: 1, key: 'corrupt' });
});
it('HOSTRPC-013a an omitted value is stored as null, not as the string "undefined"', async () => {
const host = makeHost('meta', 'db:meta');
const set = await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'blank' });
expect(set.result).toEqual({ key: 'blank', value: null });
expect((await call(host, 'meta.get', { entityType: 'trip', entityId: 1, key: 'blank' })).result).toBeNull();
await call(host, 'meta.delete', { entityType: 'trip', entityId: 1, key: 'blank' });
});
it('HOSTRPC-013 a key that was never set reads as null, and deleting it reports false', async () => {
const host = makeHost('meta', 'db:meta');
expect((await call(host, 'meta.get', { entityType: 'trip', entityId: 1, key: 'ghost' })).result).toBeNull();
expect((await call(host, 'meta.delete', { entityType: 'trip', entityId: 1, key: 'ghost' })).result).toEqual({ deleted: false });
});
it('HOSTRPC-014 the per-entity key quota is enforced on new keys only', async () => {
const host = makeHost('metaquota', 'db:meta');
for (let i = 0; i < 100; i++) {
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: `k${i}`, value: i })).ok).toBe(true);
}
const overflow = await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k100', value: 1 });
expect(overflow.error?.code).toBe('BAD_PARAMS');
expect(overflow.error?.message).toMatch(/too many metadata keys/);
// An existing key still updates — the quota counts keys, not writes.
expect((await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k0', value: 'again' })).ok).toBe(true);
closePluginDataDb('metaquota');
});
it('HOSTRPC-015 every entity type resolves its own edit action, and a read-only member is refused a write', async () => {
const host = makeHost('meta', 'db:meta');
const seen: string[] = [];
checkPermission.mockImplementation((action: unknown) => {
seen.push(String(action));
return true;
});
for (const [entityType, entityId] of [['trip', 1], ['place', 7], ['day', 3], ['reservation', 40], ['accommodation', 11]] as const) {
expect((await call(host, 'meta.set', { entityType, entityId, key: 'k', value: 1 })).ok).toBe(true);
}
// Accommodations deliberately ride on day_edit, like the accommodation write path.
expect(seen).toEqual(['trip_edit', 'place_edit', 'day_edit', 'reservation_edit', 'day_edit']);
checkPermission.mockReturnValue(false);
const write = await call(host, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k', value: 2 });
expect(write.error?.code).toBe('RESOURCE_FORBIDDEN');
// …but a READ is only access-gated, so it still works for the same user.
expect((await call(host, 'meta.get', { entityType: 'trip', entityId: 1, key: 'k' })).result).toBe(1);
});
it('HOSTRPC-016 an unknown entityType is BAD_PARAMS and a userless context is refused', async () => {
const host = makeHost('meta', 'db:meta');
expect((await call(host, 'meta.set', { entityType: 'user', entityId: 1, key: 'k', value: 1 })).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'meta.get', { entityType: 'trip', entityId: 1, key: 'k' }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
// An entity id that resolves to nothing is refused rather than reported as empty.
expect((await call(host, 'meta.get', { entityType: 'reservation', entityId: 999, key: 'k' })).error?.code).toBe('RESOURCE_FORBIDDEN');
});
it('HOSTRPC-017 one plugin never reads another\'s keys on the same entity', async () => {
const a = makeHost('meta-a', 'db:meta');
const b = makeHost('meta-b', 'db:meta');
await call(a, 'meta.set', { entityType: 'trip', entityId: 1, key: 'shared', value: 'a-value' });
expect((await call(b, 'meta.get', { entityType: 'trip', entityId: 1, key: 'shared' })).result).toBeNull();
expect((await call(b, 'meta.list', { entityType: 'trip', entityId: 1 })).result).toEqual({});
closePluginDataDb('meta-a');
closePluginDataDb('meta-b');
});
it('HOSTRPC-018 without db:meta not one of the four is reachable', async () => {
const host = makeHost('meta', 'db:read:trips');
for (const method of ['meta.get', 'meta.set', 'meta.list', 'meta.delete']) {
expect((await call(host, method, { entityType: 'trip', entityId: 1, key: 'k' })).error?.code).toBe('PERMISSION_DENIED');
}
});
});
describe('HostSurfaceRpc — users, broadcasts, notify, ai, oauth, scheduler', () => {
beforeEach(() => {
checkPermission.mockReset();
checkPermission.mockReturnValue(true);
notifySend.mockClear();
llmExtract.mockClear();
broadcast.mockClear();
broadcastToUser.mockClear();
});
afterAll(() => closePluginDataDb('surface'));
it('HOSTRPC-019 users.getById is scoped to people the acting user shares a trip with', async () => {
const host = makeHost('surface', 'db:read:users');
const shared = await call(host, 'users.getById', { id: 6 }, 5);
expect(shared.result).toEqual({ id: 6, username: 'ada', display_name: 'Ada', avatar: null });
// Reading yourself needs no shared trip.
expect((await call(host, 'users.getById', { id: 5 }, 5)).ok).toBe(true);
// A stranger is refused, which is what stops id enumeration.
expect((await call(host, 'users.getById', { id: 9 }, 5)).error?.code).toBe('RESOURCE_FORBIDDEN');
expect((await call(host, 'users.getById', { id: 6 }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
});
it('HOSTRPC-020 trip broadcasts are force-namespaced and membership-gated', async () => {
const host = makeHost('surface', 'ws:broadcast:trip');
expect((await call(host, 'ws.broadcastToTrip', { tripId: 1, event: 'ping', data: { a: 1 } }, 5)).ok).toBe(true);
expect(broadcast).toHaveBeenCalledWith(1, 'plugin:surface:ping', { a: 1 });
// A primitive payload is wrapped rather than dropped.
await call(host, 'ws.broadcastToTrip', { tripId: 1, event: 'ping', data: 'primitive' }, 5);
expect(broadcast).toHaveBeenLastCalledWith(1, 'plugin:surface:ping', { value: 'primitive' });
broadcast.mockClear();
expect((await call(host, 'ws.broadcastToTrip', { tripId: 2, event: 'x', data: {} }, 5)).error?.code).toBe('RESOURCE_FORBIDDEN');
expect((await call(host, 'ws.broadcastToTrip', { tripId: 1, event: 'x', data: {} }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
expect(broadcast).not.toHaveBeenCalled();
});
it('HOSTRPC-021 a per-user broadcast may only target the acting user', async () => {
const host = makeHost('surface', 'ws:broadcast:user');
expect((await call(host, 'ws.broadcastToUser', { userId: 5, event: 'hi', data: { x: 2 } }, 5)).ok).toBe(true);
expect(broadcastToUser).toHaveBeenCalledWith(5, { type: 'plugin:surface', event: 'hi', x: 2 });
expect((await call(host, 'ws.broadcastToUser', { userId: 6, event: 'hi', data: {} }, 5)).error?.code).toBe('RESOURCE_FORBIDDEN');
expect((await call(host, 'ws.broadcastToUser', { userId: 5, event: 'hi', data: {} }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
});
it('HOSTRPC-022 notify.send forces the recipient and carries the plugin_notification event', async () => {
const host = makeHost('surface', 'notify:send');
expect((await call(host, 'notify.send', { input: { title: 'Delay', body: 'AB123 late', scope: 'user', targetId: 5, link: '/trips/1' } }, 5)).ok).toBe(true);
expect(notifySend).toHaveBeenCalledWith(expect.objectContaining({
event: 'plugin_notification',
actorId: null,
scope: 'user',
targetId: 5,
params: expect.objectContaining({ title: 'Delay', body: 'AB123 late', link: '/trips/1' }),
}));
expect((await call(host, 'notify.send', { input: { title: 't', body: 'b', scope: 'trip', targetId: 1 } }, 5)).ok).toBe(true);
// Another user, a trip the acting user isn't in, and the admin scope are all refused.
expect((await call(host, 'notify.send', { input: { title: 't', body: 'b', scope: 'user', targetId: 9 } }, 5)).error?.code).toBe('RESOURCE_FORBIDDEN');
expect((await call(host, 'notify.send', { input: { title: 't', body: 'b', scope: 'trip', targetId: 2 } }, 5)).error?.code).toBe('RESOURCE_FORBIDDEN');
expect((await call(host, 'notify.send', { input: { title: 't', body: 'b', scope: 'admin', targetId: 0 } }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'notify.send', { input: { title: 't', body: 'b', scope: 'user', targetId: 5 } }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
});
it('HOSTRPC-023 notify.send rejects an off-site link and an empty or emoji-only title', async () => {
const host = makeHost('surface', 'notify:send');
const base = { body: 'b', scope: 'user', targetId: 5 };
for (const link of ['//evil.com', 'https://evil.com/x', '/\\evil.com', 'javascript:alert(1)']) {
expect((await call(host, 'notify.send', { input: { ...base, title: 't', link } }, 5)).error?.code).toBe('BAD_PARAMS');
}
expect((await call(host, 'notify.send', { input: { ...base, title: '' } }, 5)).error?.code).toBe('BAD_PARAMS');
// stripEmoji collapses an all-emoji title to '', so it lands on the same refusal.
expect((await call(host, 'notify.send', { input: { ...base, title: '🎉🎉' } }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'notify.send', { input: { ...base, title: 'x'.repeat(201) } }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'notify.send', { input: { title: 't', body: 'y'.repeat(1001), scope: 'user', targetId: 5 } }, 5)).error?.code).toBe('BAD_PARAMS');
// A non-string title or body lands on the same refusal as an empty one, rather
// than reaching stripEmoji and throwing there.
expect((await call(host, 'notify.send', { input: { ...base, title: 42 } }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'notify.send', { input: { title: 't', body: 42, scope: 'user', targetId: 5 } }, 5)).error?.code).toBe('BAD_PARAMS');
expect(notifySend).not.toHaveBeenCalled();
});
it('HOSTRPC-024 ai.complete/extract run under the resolved provider, with caps', async () => {
const host = makeHost('surface', 'ai:invoke');
const completed = await call(host, 'ai.complete', { prompt: 'Summarize' }, 5);
expect(completed.result).toMatchObject({ text: expect.stringContaining('answer:') });
const extracted = await call(host, 'ai.extract', { text: 'AB123 JFK', jsonSchema: { type: 'object' } }, 5);
expect(Array.isArray((extracted.result as { results: unknown[] }).results)).toBe(true);
// user 7 has no provider configured
expect((await call(host, 'ai.complete', { prompt: 'hi' }, 7)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.complete', { prompt: '' }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.complete', { prompt: 'x'.repeat(20001) }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.extract', { text: 'x', jsonSchema: 'not-an-object' }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.extract', { text: '', jsonSchema: {} }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.extract', { text: 'x'.repeat(20001), jsonSchema: {} }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.complete', { prompt: 'hi' }, undefined)).error?.code).toBe('RESOURCE_FORBIDDEN');
// A non-string prompt/text is the same refusal as an empty one, not a crash.
expect((await call(host, 'ai.complete', { prompt: 42 }, 5)).error?.code).toBe('BAD_PARAMS');
expect((await call(host, 'ai.extract', { text: 42, jsonSchema: {} }, 5)).error?.code).toBe('BAD_PARAMS');
// …and a null jsonSchema is refused despite typeof null === 'object'.
expect((await call(host, 'ai.extract', { text: 'x', jsonSchema: null }, 5)).error?.code).toBe('BAD_PARAMS');
});
it('HOSTRPC-025 the plugin\'s system prompt and extraction hint are passed through, with a default', async () => {
const host = makeHost('surface', 'ai:invoke');
await call(host, 'ai.complete', { prompt: 'p', system: 'be terse' }, 5);
expect(llmExtract).toHaveBeenLastCalledWith(expect.objectContaining({ prompt: 'be terse', text: 'p' }));
await call(host, 'ai.complete', { prompt: 'p' }, 5);
expect(llmExtract).toHaveBeenLastCalledWith(expect.objectContaining({ prompt: expect.stringContaining('helpful assistant') }));
await call(host, 'ai.extract', { text: 't', jsonSchema: { type: 'object' }, prompt: '' }, 5);
expect(llmExtract).toHaveBeenLastCalledWith(expect.objectContaining({ prompt: expect.stringContaining('Extract structured data') }));
});
it('HOSTRPC-026 a model that answers with no text yields an empty string, not undefined', async () => {
llmExtract.mockResolvedValueOnce([{ text: 42 } as never]);
expect((await call(makeHost('surface', 'ai:invoke'), 'ai.complete', { prompt: 'p' }, 5)).result).toEqual({ text: '' });
llmExtract.mockResolvedValueOnce([]);
expect((await call(makeHost('surface', 'ai:invoke'), 'ai.complete', { prompt: 'p' }, 5)).result).toEqual({ text: '' });
});
it('HOSTRPC-027 oauth.getToken returns only the acting user\'s access token', async () => {
const host = makeHost('surface', 'oauth:client');
expect((await call(host, 'oauth.getToken', {}, 5)).result).toEqual({ accessToken: 'tok-5' });
expect((await call(host, 'oauth.getToken', {}, 7)).result).toEqual({ accessToken: null }); // not connected
// A userless context gets null, matching the SDK contract, not RESOURCE_FORBIDDEN.
expect((await call(host, 'oauth.getToken', {}, undefined)).result).toEqual({ accessToken: null });
expect((await call(makeHost('surface'), 'oauth.getToken', {}, 5)).error?.code).toBe('PERMISSION_DENIED');
});
it('HOSTRPC-028 scheduler.set upserts by name with caps; cancel removes', async () => {
const host = makeHost('wsched', 'jobs:run');
const count = () =>
(mockDb as unknown as { prepare(s: string): { get(): { n: number } } })
.prepare("SELECT COUNT(*) AS n FROM plugin_scheduled_tasks WHERE plugin_id='wsched'")
.get().n;
const due = Date.now() + 120_000;
// Userless is fine — a scheduled task is like a job.
expect((await call(host, 'scheduler.set', { name: 'poll', dueAt: due, payload: { a: 1 } }, undefined)).ok).toBe(true);
expect(count()).toBe(1);
expect((await call(host, 'scheduler.set', { name: 'poll', dueAt: due + 1000 }, undefined)).ok).toBe(true);
expect(count()).toBe(1); // upsert by (plugin, name)
expect((await call(host, 'scheduler.cancel', { name: 'poll' }, undefined)).result).toEqual({ cancelled: true });
expect(count()).toBe(0);
expect((await call(host, 'scheduler.cancel', { name: 'ghost' }, undefined)).result).toEqual({ cancelled: false });
});
it('HOSTRPC-029 the scheduler caps bound name, horizon, interval and payload', async () => {
const host = makeHost('wsched2', 'jobs:run');
const due = Date.now() + 120_000;
const bad = async (params: Record<string, unknown>) => (await call(host, 'scheduler.set', params, undefined)).error?.code;
expect(await bad({ name: '', dueAt: due })).toBe('BAD_PARAMS');
expect(await bad({ name: 'x'.repeat(129), dueAt: due })).toBe('BAD_PARAMS');
expect(await bad({ name: 'far', dueAt: Date.now() + 400 * 24 * 60 * 60 * 1000 })).toBe('BAD_PARAMS');
expect(await bad({ name: 'nan', dueAt: Number.POSITIVE_INFINITY })).toBe('BAD_PARAMS');
expect(await bad({ name: 'fast', dueAt: due, everyMs: 5000 })).toBe('BAD_PARAMS');
expect(await bad({ name: 'fat', dueAt: due, payload: { blob: 'z'.repeat(9000) } })).toBe('BAD_PARAMS');
// A dueAt in the past is clamped to now rather than refused, so a plugin that wakes
// up late still gets its task fired on the next sweep.
expect((await call(host, 'scheduler.set', { name: 'late', dueAt: 1 }, undefined)).ok).toBe(true);
const row = (mockDb as unknown as { prepare(s: string): { get(): { due_at: number } } })
.prepare("SELECT due_at FROM plugin_scheduled_tasks WHERE plugin_id='wsched2' AND name='late'")
.get();
expect(row.due_at).toBeGreaterThan(1);
});
it('HOSTRPC-030 a plugin cannot hoard more than 100 scheduled tasks', async () => {
const host = makeHost('wschedmax', 'jobs:run');
const due = Date.now() + 120_000;
for (let i = 0; i < 100; i++) {
expect((await call(host, 'scheduler.set', { name: `t${i}`, dueAt: due }, undefined)).ok).toBe(true);
}
const over = await call(host, 'scheduler.set', { name: 't100', dueAt: due }, undefined);
expect(over.error?.message).toMatch(/too many scheduled tasks/);
// An existing name still upserts — the cap counts entries, not calls.
expect((await call(host, 'scheduler.set', { name: 't0', dueAt: due + 5 }, undefined)).ok).toBe(true);
});
it('HOSTRPC-031 the daily notify + AI budgets are enforced, seeded from today\'s audit rows', async () => {
// Seed the audit with a plugin that has already spent its whole day (default caps
// are 100 notify / 200 ai) so the budget is exhausted on first use.
const today = `${new Date().toISOString().slice(0, 10)}T08:00:00.000Z`;
const insert = (mockDb as unknown as { prepare(s: string): { run(...a: unknown[]): unknown } })
.prepare("INSERT INTO plugin_capability_audit (plugin_id, method, code, ts) VALUES (?, ?, 'ok', ?)");
for (let i = 0; i < 100; i++) insert.run('wbudget', 'notify.send', today);
for (let i = 0; i < 200; i++) insert.run('wbudget', 'ai.complete', today);
const host = makeHost('wbudget', 'notify:send', 'ai:invoke');
const notified = await call(host, 'notify.send', { input: { title: 't', body: 'b', scope: 'user', targetId: 5 } }, 5);
expect(notified.error?.code).toBe('BAD_PARAMS');
expect(notified.error?.message).toMatch(/budget/i);
expect(notifySend).not.toHaveBeenCalled();
expect((await call(host, 'ai.complete', { prompt: 'hi' }, 5)).error?.message).toMatch(/budget/i);
closePluginDataDb('wbudget');
});
it('HOSTRPC-032 every host-surface method is unreachable without its own grant', async () => {
const host = makeHost('surface');
const denied: Record<string, Record<string, unknown>> = {
'users.getById': { id: 6 },
'ws.broadcastToTrip': { tripId: 1, event: 'x' },
'ws.broadcastToUser': { userId: 5, event: 'x' },
'notify.send': { input: { title: 't', body: 'b', scope: 'user', targetId: 5 } },
'ai.complete': { prompt: 'x' },
'ai.extract': { text: 'x', jsonSchema: {} },
'oauth.getToken': {},
'scheduler.set': { name: 'x', dueAt: Date.now() + 1000 },
'scheduler.cancel': { name: 'x' },
};
for (const [method, params] of Object.entries(denied)) {
expect((await call(host, method, params, 5)).error?.code).toBe('PERMISSION_DENIED');
}
});
});
@@ -23,7 +23,7 @@ import type { JourneyDomainService } from '../../../src/nest/journey/journey-dom
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { JournalEntryRowsController } from '../../../src/nest/plugins/journal-entry-rows.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
const addonsStub = { isAddonEnabled } as unknown as AddonsService;
@@ -33,8 +33,8 @@ const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) a
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
journalRows: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new JournalEntryRowsController(runtime, new DatabaseService(dbConn), addonsStub, { canAccessJourney } as unknown as JourneyDomainService), runtime };
}
const row = (over: Record<string, unknown> = {}) => ({ label: 'Distance', value: '12 km', ...over });
@@ -77,7 +77,7 @@ describe('JournalEntryRowsController', () => {
{ label: 'Steps', value: '9000', url: 'mailto:x@y.z' },
],
}]);
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'journalEntryProvider', 'getRows', [7], 5, 5000);
expect(runtime.journalRows).toHaveBeenCalledWith('p1', 7, 5);
});
it('drops javascript:/empty/unparseable urls, caps lengths, drops label-less rows and non-objects', async () => {
@@ -15,7 +15,7 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () =>
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { MapLayersController } from '../../../src/nest/plugins/map-layers.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -23,8 +23,8 @@ const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) a
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
mapLayers: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new MapLayersController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
}
const line = (n = 3, over: Record<string, unknown> = {}) => ({
@@ -14,7 +14,7 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () =>
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { MapMarkersController } from '../../../src/nest/plugins/map-markers.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -22,8 +22,8 @@ const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) a
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
mapMarkers: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new MapMarkersController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
}
const mk = (over: Record<string, unknown> = {}) => ({ id: 'm1', lat: 48.85, lng: 2.35, ...over });
@@ -15,7 +15,7 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () =>
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { PdfSectionsController } from '../../../src/nest/plugins/pdf-sections.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -23,8 +23,8 @@ const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) a
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
pdfSections: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new PdfSectionsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
}
const sec = (over: Record<string, unknown> = {}) => ({ title: 'Weather', ...over });
@@ -56,7 +56,7 @@ describe('PdfSectionsController', () => {
paragraphs: ['Sunny all week'],
table: { headers: ['Day', 'Temp'], rows: [['Mon', '24°C']] },
}]);
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'pdfSectionProvider', 'getSections', [1], 5, 5000);
expect(runtime.pdfSections).toHaveBeenCalledWith('p1', 1, 5);
});
it('drops non-objects, untitled sections and a non-array result; coerces + caps the title', async () => {
@@ -14,16 +14,16 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { PlaceDetailsController } from '../../../src/nest/plugins/place-details.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(over: Partial<PluginRuntimeService> = {}) {
function controller(over: Partial<PluginHooks> = {}) {
const runtime = {
providersOf: vi.fn(() => ['p1', 'p2']),
invokeHook: vi.fn(async (id: string) => (id === 'p2' ? [{ label: 'Rating', value: '4.5' }] : [{ label: 'Reviews', value: '12', url: 'https://x' }])),
placeDetails: vi.fn(async (id: string) => (id === 'p2' ? [{ label: 'Rating', value: '4.5' }] : [{ label: 'Reviews', value: '12', url: 'https://x' }])),
...over,
} as unknown as PluginRuntimeService;
} as unknown as PluginHooks;
return { c: new PlaceDetailsController(runtime, new DatabaseService(dbConn)), runtime };
}
@@ -51,26 +51,26 @@ describe('PlaceDetailsController', () => {
it('merges every provider that returns items and skips one that throws (graceful)', async () => {
const { c, runtime } = controller({
invokeHook: vi.fn(async (id: string) => {
placeDetails: vi.fn(async (id: string) => {
if (id === 'p2') throw new Error('slow provider');
return [{ label: 'Reviews', value: '12' }];
}) as unknown as PluginRuntimeService['invokeHook'],
}) as unknown as PluginHooks['placeDetails'],
});
const res = await c.get('7', req(5));
expect(res.providers).toEqual([{ pluginId: 'p1', items: [{ label: 'Reviews', value: '12' }] }]);
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'placeDetailProvider', 'getDetails', [7], 5, 5000);
expect(runtime.placeDetails).toHaveBeenCalledWith('p1', 7, 5);
});
it('normalizes rows: drops a javascript: url, caps lengths, drops non-objects + label-less rows', async () => {
const { c } = controller({
providersOf: vi.fn(() => ['p1']),
invokeHook: vi.fn(async () => [
placeDetails: vi.fn(async () => [
{ label: 'x'.repeat(200), value: 'y'.repeat(500), url: 'javascript:alert(1)' },
{ label: 'Site', url: 'https://ok.example' },
{ value: 'no label' }, // dropped
'not an object', // dropped
{ label: 'Mail', url: 'mailto:a@b.c' },
]) as unknown as PluginRuntimeService['invokeHook'],
]) as unknown as PluginHooks['placeDetails'],
});
const items = (await c.get('7', req(5))).providers[0].items;
expect(items).toEqual([
@@ -83,11 +83,11 @@ describe('PlaceDetailsController', () => {
it('caps the row count per provider at 12 and drops a provider that yields nothing usable', async () => {
const { c } = controller({
providersOf: vi.fn(() => ['flood', 'empty']),
invokeHook: vi.fn(async (id: string) =>
placeDetails: vi.fn(async (id: string) =>
id === 'flood'
? Array.from({ length: 50 }, (_v, i) => ({ label: `r${i}` }))
: [{ value: 'no label' }, 'junk'],
) as unknown as PluginRuntimeService['invokeHook'],
) as unknown as PluginHooks['placeDetails'],
});
const res = await c.get('7', req(5));
expect(res.providers).toHaveLength(1); // 'empty' contributes nothing -> dropped
@@ -0,0 +1,143 @@
/**
* The host-to-plugin hook contracts.
*
* The 15 hooks used to be invoked straight from the controllers, with the fn name and
* the timeout spelled out at each call site. Nothing checked that a `hook:*` grant on
* the consent screen had a consumer behind it, that the fn name matched what the SDK
* documents, or that two call sites for the same hook agreed on the budget.
*
* These tests pin all three, plus the argument shape each hook is handed.
*/
import { describe, it, expect, vi } from 'vitest';
import { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import { PluginsModule } from '../../../src/nest/plugins/plugins.module';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { HOOK_PERMISSION } from '../../../src/nest/plugins/protocol/envelope';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
type Invocation = [string, string, string, unknown[], number | undefined, number];
function hooks() {
const invokeHook = vi.fn(async () => ({ ok: true }));
const providersOf = vi.fn(() => ['p1', 'p2']);
const runtime = { invokeHook, providersOf } as unknown as PluginRuntimeService;
return { hooks: new PluginHooks(runtime), invokeHook, providersOf };
}
/** The (hook, fn, timeout) triple every call site used to carry on its own. */
const CONTRACTS: Array<[hook: string, fn: string, timeoutMs: number]> = [
['photoProvider', 'search', 5000],
['photoProvider', 'getById', 5000],
['calendarSource', 'getName', 3000],
['calendarSource', 'getEvents', 5000],
['placeDetailProvider', 'getDetails', 5000],
['warningProvider', 'getWarnings', 5000],
['tableContributor', 'getContributions', 5000],
['mapMarkerProvider', 'getMarkers', 5000],
['mapLayerProvider', 'getLayers', 5000],
['routeProvider', 'getRoute', 20_000],
['dayScheduleProvider', 'getSchedule', 5000],
['dayTintProvider', 'getDayTints', 5000],
['pdfSectionProvider', 'getSections', 5000],
['atlasLayerProvider', 'getLayers', 5000],
['journalEntryProvider', 'getRows', 5000],
['tripCardProvider', 'getCards', 5000],
['notificationChannel', 'send', 8000],
['notificationChannel', 'test', 8000],
];
describe('PluginHooks contracts', () => {
const registry = createTestPluginRegistry([new PluginHooks({} as never)]);
it('PLUGHOOK-001 every hook the consent screen offers has a host-side consumer', () => {
const covered = new Set([...registry.hookContracts().values()].map((c) => c.hook));
expect([...Object.keys(HOOK_PERMISSION)].filter((h) => !covered.has(h))).toEqual([]);
});
it('PLUGHOOK-002 the declared (hook, fn) pairs are exactly the ones the host calls', () => {
const declared = [...registry.hookContracts().keys()].sort();
expect(declared).toEqual(CONTRACTS.map(([hook, fn]) => `${hook}#${fn}`).sort());
});
it('PLUGHOOK-003 each contract carries the permission HOOK_PERMISSION assigns and its own budget', () => {
for (const [hook, fn, timeoutMs] of CONTRACTS) {
const contract = registry.hookContract(hook, fn);
expect(contract.permission).toBe((HOOK_PERMISSION as Record<string, string>)[hook]);
expect(contract.timeoutMs).toBe(timeoutMs);
expect(contract.consumer).toMatch(/^PluginHooks\./);
}
});
it('PLUGHOOK-004 a call site asking for a fn nobody declared is a throw, not a silent miss', () => {
expect(() => registry.hookContract('photoProvider', 'searchAll')).toThrow(/no @PluginHook declaration/);
});
it('PLUGHOOK-005 providersOf is passed straight through to the runtime', () => {
const { hooks: h, providersOf } = hooks();
expect(h.providersOf('photoProvider')).toEqual(['p1', 'p2']);
expect(providersOf).toHaveBeenCalledWith('photoProvider');
});
it('PLUGHOOK-006 the read hooks forward their arguments and the acting user', async () => {
const { hooks: h, invokeHook } = hooks();
const last = (): Invocation => invokeHook.mock.calls.at(-1) as unknown as Invocation;
await h.searchPhotos('p', 'beach', 3, 60, 7);
expect(last()).toEqual(['p', 'photoProvider', 'search', ['beach', { page: 3, limit: 60 }], 7, 5000]);
await h.getPhoto('p', 'ph-1', 7);
expect(last()).toEqual(['p', 'photoProvider', 'getById', ['ph-1'], 7, 5000]);
await h.calendarName('p', 9);
expect(last()).toEqual(['p', 'calendarSource', 'getName', [], 9, 3000]);
await h.calendarEvents('p', 9, 'a', 'b');
expect(last()).toEqual(['p', 'calendarSource', 'getEvents', [9, 'a', 'b'], 9, 5000]);
await h.placeDetails('p', 7, 5);
expect(last()).toEqual(['p', 'placeDetailProvider', 'getDetails', [7], 5, 5000]);
await h.tripWarnings('p', 1, 5);
expect(last()).toEqual(['p', 'warningProvider', 'getWarnings', [1], 5, 5000]);
await h.tableContributions('p', 'places', 1, 5);
expect(last()).toEqual(['p', 'tableContributor', 'getContributions', ['places', 1], 5, 5000]);
await h.mapMarkers('p', 1, 5);
expect(last()).toEqual(['p', 'mapMarkerProvider', 'getMarkers', [1], 5, 5000]);
await h.mapLayers('p', 1, 5);
expect(last()).toEqual(['p', 'mapLayerProvider', 'getLayers', [1], 5, 5000]);
await h.daySchedule('p', 1, 5);
expect(last()).toEqual(['p', 'dayScheduleProvider', 'getSchedule', [1], 5, 5000]);
await h.dayTints('p', 1, 5);
expect(last()).toEqual(['p', 'dayTintProvider', 'getDayTints', [1], 5, 5000]);
await h.pdfSections('p', 1, 5);
expect(last()).toEqual(['p', 'pdfSectionProvider', 'getSections', [1], 5, 5000]);
await h.atlasLayers('p', 5);
expect(last()).toEqual(['p', 'atlasLayerProvider', 'getLayers', [], 5, 5000]);
await h.journalRows('p', 7, 5);
expect(last()).toEqual(['p', 'journalEntryProvider', 'getRows', [7], 5, 5000]);
await h.tripCards('p', [1, 2], 5);
expect(last()).toEqual(['p', 'tripCardProvider', 'getCards', [[1, 2]], 5, 5000]);
});
it('PLUGHOOK-007 a route solve gets four times the budget of a plain read', async () => {
const { hooks: h, invokeHook } = hooks();
const request = { tripId: 1, dayId: 7, profile: 'ev', waypoints: [] };
await h.route('p', request, 5);
expect(invokeHook).toHaveBeenCalledWith('p', 'routeProvider', 'getRoute', [request], 5, 20_000);
});
it('PLUGHOOK-008 both notification-channel calls run with NO acting user', async () => {
// A notification is host-initiated for an arbitrary recipient, so the hook is
// handed that recipient's own decrypted config rather than the right to read
// anything as them. A bound acting user here would be exactly that right.
const { hooks: h, invokeHook } = hooks();
const message = { event: 'trip_reminder', title: 't', body: 'b' };
await h.sendNotification('p', message, { token: 'x' });
expect(invokeHook).toHaveBeenCalledWith('p', 'notificationChannel', 'send', [message, { token: 'x' }], undefined, 8000);
await h.testNotification('p', { token: 'x' });
expect(invokeHook).toHaveBeenCalledWith('p', 'notificationChannel', 'test', [{ token: 'x' }], undefined, 8000);
});
it('PLUGHOOK-009 the class is listed in its module providers', () => {
// A decorated class no module registers is invisible to discovery, which would
// now fail boot on "no host-side consumer" rather than fail quietly. Cheapest
// possible guard against getting there.
const providers = Reflect.getMetadata('providers', PluginsModule) as unknown[] | undefined;
expect(providers).toContain(PluginHooks);
});
});
@@ -1,588 +0,0 @@
/**
* The production wiring (PluginHostDepsFactory) that connects a plugin's
* capability host to the real privileged modules (#plugins, M1). Verifies the
* per-plugin data db is cached, a granted db:own call works through the wired
* host, and trip broadcasts are force-namespaced to plugin:{id}:{event}.
* DI-native domains (budget/exchange-rates/reservations/tags/categories/todo/
* packing/day-notes/days/assignments/oauth/llm-config/files/collab/vacay/
* permissions/trips/places/collections/atlas/notifications)
* are constructor-injected stubs; legacy services/* domains stay path-mocked
* until their own DI migration lands.
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const { broadcast, broadcastToUser } = vi.hoisted(() => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
// A real in-memory core db so the metadata deps (inline SQL) and metaEntityTrip
// resolution run for real; trip 1 is owned by user 5. canAccessTrip is stubbed so
// user 5 (owner) can access trip 1 and user 6 cannot.
vi.mock('../../../src/db/database', () => {
const Database = require('better-sqlite3');
const d = new Database(':memory:');
d.exec(`
CREATE TABLE trips (id INTEGER PRIMARY KEY, user_id INTEGER);
CREATE TABLE places (id INTEGER PRIMARY KEY, trip_id INTEGER);
CREATE TABLE days (id INTEGER PRIMARY KEY, trip_id INTEGER);
CREATE TABLE users (id INTEGER PRIMARY KEY, role TEXT, username TEXT, display_name TEXT, avatar TEXT, email TEXT);
CREATE TABLE trip_members (trip_id INTEGER, user_id INTEGER);
CREATE TABLE plugin_entity_metadata (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, entity_type TEXT, entity_id INTEGER, key TEXT, value TEXT, updated_at TEXT, UNIQUE(plugin_id, entity_type, entity_id, key));
CREATE TABLE packing_items (id INTEGER PRIMARY KEY, trip_id INTEGER, is_private INTEGER, owner_id INTEGER);
CREATE TABLE plugin_capability_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, acting_user_id INTEGER, method TEXT, resource TEXT, code TEXT, ts TEXT, prev_hash TEXT, hash TEXT);
CREATE TABLE plugin_scheduled_tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT NOT NULL, name TEXT NOT NULL, due_at INTEGER NOT NULL, payload TEXT NOT NULL DEFAULT 'null', every_ms INTEGER, created_at TEXT DEFAULT (datetime('now')), UNIQUE(plugin_id, name));
`);
d.prepare('INSERT INTO trips (id, user_id) VALUES (1, 5)').run();
d.prepare('INSERT INTO packing_items (id, trip_id, is_private, owner_id) VALUES (70, 1, 0, 5)').run(); // public before an update
d.prepare('INSERT INTO packing_items (id, trip_id, is_private, owner_id) VALUES (71, 1, 1, 5)').run(); // private before an update
d.prepare('INSERT INTO places (id, trip_id) VALUES (7, 1)').run();
d.prepare('INSERT INTO days (id, trip_id) VALUES (3, 1)').run();
d.prepare('INSERT INTO users (id, role) VALUES (5, ?)').run('trip_owner');
d.prepare('INSERT INTO users (id, role) VALUES (6, ?)').run('user');
d.prepare("INSERT INTO users (id, role, email) VALUES (77, 'user', 'demo@trek.app')").run(); // a demo-account member for the DEMO_MODE upload guard
d.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (1, 6)').run(); // user 6 shares trip 1 with owner 5
d.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (1, 77)').run();
return { db: d, canAccessTrip: (tripId: number, userId: number) => (tripId === 1 && (userId === 5 || userId === 6 || userId === 77) ? { id: 1, user_id: 5 } : undefined) };
});
vi.mock('../../../src/websocket', () => ({ broadcast, broadcastToUser }));
// Addon gate — flip per test to exercise the "addon disabled" branch of the reads.
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true as boolean) }));
// DI-native services are constructor-injected into PluginHostDepsFactory below —
// stub instances instead of path mocks (same behaviors as before the DI move).
const budgetStub = {
async create(tid: string, input: Record<string, unknown>) { return { id: 1, trip_id: Number(tid), ...input }; },
async update(id: string, tid: string, input: Record<string, unknown>) {
return id === '404' ? null : { id: Number(id), trip_id: Number(tid), ...input };
},
remove(id: string, _tid: string) { return id !== '404'; },
// The listCostsForTrip/listCostsForUser closures inject this since the budget
// fold (was the legacy listBudgetItems path import).
listBudgetItems: vi.fn(() => []),
} as unknown as BudgetService;
// Edit permission — flip per test to exercise the gates (constructor-injected
// stub since the permissions DI migration).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const checkPermission = vi.fn((..._a: any[]) => true as boolean);
const permissionsStub = { checkPermission } as unknown as PermissionsService;
// Trips are a constructor-injected stub since the trip fold (same behaviors as
// the old services/tripService path mock). The throws use the REAL error
// classes from trips.service so the factory's instanceof mapping keeps
// matching — see the imports below the mocks.
// Exchange rates are a constructor-injected stub since the budget-domain fold
// (was a path mock of the deleted services/exchangeRateService — same behavior).
const exchangeRatesStub = {
getRates: vi.fn(async (base: string) => ({ [base]: 1, USD: 1.08, GBP: 0.85 })),
} as unknown as ExchangeRatesService;
// Places are a constructor-injected stub since the place fold (same behaviors
// as the old services/placeService path mock, mapped onto the PlacesService
// method names). `remove` is asserted by invocation order against the journey
// hook, so it stays a vi.fn.
const removePlaceStub = vi.fn((_tid: string, pid: string) => pid !== '99');
const placesStub = {
create: vi.fn((tid: string, body: Record<string, unknown>) => ({ id: 10, trip_id: Number(tid), ...body })),
update: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
remove: removePlaceStub,
// Trip-scoped read the delete path uses to reject a foreign id before the
// journey hook runs — place 99 belongs to another trip.
get: vi.fn((_tid: string, pid: string) => (pid === '99' ? null : { id: Number(pid) })),
// trips.service (loaded for real since the trip fold) injects this for its
// offline bundle — the stub must carry every method it calls.
list: vi.fn(() => []),
} as unknown as PlacesService;
// Days are a constructor-injected stub (same behaviors as the old path mock,
// mapped onto the DaysService method names).
const daysStub = {
create: vi.fn((tid: number) => ({ id: 20, trip_id: tid, assignments: [] })),
getDay: vi.fn((id: number) => (id === 99 ? undefined : { id, title: null })),
update: vi.fn((id: number) => ({ id, assignments: [] })),
remove: vi.fn(),
list: vi.fn((tid: number) => ({ days: [{ id: 3, trip_id: Number(tid), day_number: 1, assignments: [], notes_items: [] }] })),
listAccommodations: vi.fn((tid: number) => [{ id: 11, trip_id: Number(tid), place_name: 'Ryokan' }]),
// place 999 / day 88 don't belong to the trip
validateAccommodationRefs: vi.fn((_tid: number, placeId?: number, startDayId?: number, endDayId?: number) => {
const errors: { field: string; message: string }[] = [];
if (placeId === 999) errors.push({ field: 'place_id', message: 'Place not found' });
if (startDayId === 88 || endDayId === 88) errors.push({ field: 'start_day_id', message: 'Start day not found' });
return errors;
}),
createAccommodation: vi.fn((tid: number, data: Record<string, unknown>) => ({ id: 60, trip_id: Number(tid), ...data })),
getAccommodation: vi.fn((id: number) => (Number(id) === 404 ? undefined : { id: Number(id), place_id: 7, start_day_id: 3, end_day_id: 4 })),
updateAccommodation: vi.fn((id: number, _existing: unknown, fields: Record<string, unknown>) => ({ id: Number(id), ...fields })),
deleteAccommodation: vi.fn((id: number) => (Number(id) === 61 ? { linkedReservationId: 40, deletedBudgetItemId: 9 } : { linkedReservationId: null, deletedBudgetItemId: null })),
} as unknown as DaysService;
// Assignments is a constructor-injected stub (same behaviors as the old path mock).
const assignmentsStub = {
createAssignment: vi.fn((dayId: number, placeId: number, notes: string | null) => ({ id: 30, day_id: dayId, place_id: placeId, notes })),
deleteAssignment: vi.fn(),
dayExists: vi.fn((dayId: number) => dayId === 3),
placeExists: vi.fn((placeId: number) => placeId === 7),
getAssignmentForTrip: vi.fn((id: number) => (id === 99 ? undefined : { id, day_id: 3 })),
reconcile: vi.fn(),
} as unknown as AssignmentsService;
// Packing is a constructor-injected stub (same behaviors as the old path mock).
const packingStub = {
listItems: vi.fn((tid: number | string, userId?: number) => [{ id: 1, trip_id: tid, name: 'Socks', _uid: userId }]),
// Return the item with the #858 privacy fields the host deps scope on.
createItem: vi.fn((tid: number | string, input: { name: string; visibility?: string; recipient_ids?: number[] }, ownerId?: number) => {
if (input.visibility === 'personal') return { id: 70, trip_id: Number(tid), name: input.name, is_private: 1, owner_id: ownerId, recipients: [] };
if (input.visibility === 'shared') return { id: 70, trip_id: Number(tid), name: input.name, is_private: 1, owner_id: ownerId, recipients: (input.recipient_ids || []).map((id) => ({ user_id: id })) };
return { id: 70, trip_id: Number(tid), name: input.name, is_private: 0, owner_id: ownerId };
}),
// itemId 99 => a stale-write conflict result; otherwise the after-state (is_private per input).
updateItem: vi.fn((tid: number | string, id: string, input: { is_private?: boolean }) =>
Number(id) === 99 ? { conflict: true, server: { id: 99 } } : { id: Number(id), trip_id: Number(tid), is_private: input.is_private ? 1 : 0, owner_id: 5 },
),
// The raw deleted row (owner-only for a private item, no recipients — #858).
deleteItem: vi.fn((_tid: number | string, id: string) => (Number(id) === 404 ? null : Number(id) === 71 ? { id: 71, is_private: 1, owner_id: 5 } : { id: Number(id), is_private: 0 })),
// Mirrors the packing_items rows seeded above: 70 = public, 71 = private (was
// the inline packingItemPrivacy SQL before the DI move).
getItemPrivacy: vi.fn((tid: number | string, id: number | string) =>
Number(tid) === 1 && Number(id) === 70 ? { is_private: 0, owner_id: 5 }
: Number(tid) === 1 && Number(id) === 71 ? { is_private: 1, owner_id: 5 }
: undefined),
listBags: vi.fn((tid: number | string) => [{ id: 80, trip_id: Number(tid), name: 'Backpack' }]),
createBag: vi.fn((tid: number | string, data: { name: string }) => ({ id: 80, trip_id: Number(tid), name: data.name })),
updateBag: vi.fn((_tid: number | string, bagId: string) => (Number(bagId) === 404 ? null : { id: Number(bagId), name: 'Renamed' })),
deleteBag: vi.fn((_tid: number | string, bagId: string) => Number(bagId) !== 404),
setBagMembers: vi.fn((_tid: number | string, bagId: string, userIds: number[]) => (Number(bagId) === 404 ? null : userIds.map((u) => ({ user_id: u })))),
} as unknown as PackingService;
vi.mock('../../../src/nest/common/conflictResult', () => ({ isUpdateConflict: (r: unknown) => !!(r as { conflict?: boolean })?.conflict }));
vi.mock('../../../src/nest/weather/weather.impl', () => ({ getWeather: vi.fn(async (lat: string, lng: string) => ({ lat, lng, temp: 20 })) }));
const categoriesStub = { list: vi.fn(() => [{ id: 1, name: 'Food' }]) } as unknown as CategoriesService;
const tagsStub = {
list: vi.fn((uid: number) => [{ id: 1, user_id: uid, name: 'work' }]),
create: vi.fn((uid: number, name: string, color?: string) => ({ id: 9, user_id: uid, name, color })),
getByIdAndUser: vi.fn((tagId: number, _uid: number) => (Number(tagId) === 404 ? undefined : { id: Number(tagId) })),
update: vi.fn((tagId: number, name?: string) => ({ id: Number(tagId), name })),
remove: vi.fn(),
} as unknown as TagsService;
const todoStub = {
listItems: vi.fn((tid: number) => [{ id: 1, trip_id: Number(tid), name: 'Pack' }]),
createItem: vi.fn((tid: number, data: { name: string }) => ({ id: 90, trip_id: Number(tid), name: data.name })),
updateItem: vi.fn((_tid: number, id: string) => (Number(id) === 404 ? null : { id: Number(id), name: 'Done' })),
deleteItem: vi.fn((_tid: number, id: string) => Number(id) !== 404),
} as unknown as TodoService;
const { testFilesDir } = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const osm = require('node:os') as typeof import('node:os');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const pm = require('node:path') as typeof import('node:path');
return { testFilesDir: pm.join(osm.tmpdir(), 'trek-crh-files-test') };
});
// The load-time constants the factory imports from files.constants — mocked so
// createTripFile's mkdirSync/writeFileSync land in the tmpdir, never in the
// real server/uploads/files (same redirection the old fileService path mock did).
vi.mock('../../../src/nest/files/files.constants', () => ({
filesDir: testFilesDir,
BLOCKED_EXTENSIONS: ['.exe', '.bat', '.sh'],
}));
// Files: injected stub since the fileService DI migration (same behaviors as
// the old path mock).
const filesStub = {
listFiles: vi.fn((tid: number, trash: boolean) => [{ id: 2, trip_id: tid, trash }]),
createFile: vi.fn((tid: number, file: { filename: string; originalname: string; size: number }, uploadedBy: number) => ({ id: 130, trip_id: Number(tid), ...file, uploaded_by: uploadedBy })),
createFileLink: vi.fn(() => [{ file_id: 130 }]),
getFileById: vi.fn((id: number) => (Number(id) === 404 ? undefined : Number(id) === 500 ? { id: 500, filename: 'huge.mp4', original_name: 'huge.mp4', mime_type: 'video/mp4', file_size: 400 * 1024 * 1024, deleted_at: null } : { id: Number(id), filename: 'visa.pdf', original_name: 'visa.pdf', mime_type: 'application/pdf', file_size: 3, deleted_at: null, description: 'old', place_id: null, reservation_id: null })),
resolveFilePath: vi.fn((filename: string) => ({ resolved: `${testFilesDir}/${filename}`, safe: filename !== 'evil' })),
updateFile: vi.fn((id: number, _cur: unknown, updates: unknown) => ({ id: Number(id), ...(updates as object) })),
softDeleteFile: vi.fn(),
// reservation_id/place_id 999 = belongs to another trip
findForeignLinkTarget: vi.fn((_tid: number, opts: { reservation_id?: number | null; place_id?: number | null }) =>
(Number(opts.reservation_id) === 999 ? 'reservation_id' : Number(opts.place_id) === 999 ? 'place_id' : null)),
} as unknown as FilesService;
// Collab: injected stub since the collabService DI migration (same behaviors
// as the old path mock).
const collabStub = {
listNotes: vi.fn((tid: number) => [{ id: 1, trip_id: Number(tid), title: 'Note' }]),
listPolls: vi.fn((tid: number) => [{ id: 2, trip_id: Number(tid), question: 'Q?' }]),
listMessages: vi.fn((tid: number, before?: number) => [{ id: 3, trip_id: Number(tid), text: 'hi', _before: before ?? null }]),
createNote: vi.fn((tid: number, uid: number, data: { title: string }) => ({ id: 140, trip_id: Number(tid), created_by: uid, title: data.title })),
createPoll: vi.fn((tid: number, _uid: number, data: { question: string }) => ({ id: 141, trip_id: Number(tid), question: data.question })),
votePoll: vi.fn((_tid: number, pollId: number, _uid: number, optionIndex: number) =>
(optionIndex > 5 ? { error: 'Invalid option' } : { poll: { id: Number(pollId), votes: 1 } })),
createMessage: vi.fn((tid: number, uid: number, text: string) =>
(text === 'toolong' ? { error: 'Message too long' } : { message: { id: 142, trip_id: Number(tid), user_id: uid, text } })),
} as unknown as CollabService;
// Injected stub since the membership fold (was a path mock of services/tripMembership).
const membershipStub = {
joinTripAsMember: vi.fn((tripId: number, userId: number) => ({ joined: userId !== 5, tripId })), // owner add = no-op
} as unknown as TripMembershipService;
// Notifications are a constructor-injected stub since the notifications fold
// (same behavior as the old services/notificationService path mock).
const notifySend = vi.fn(async () => undefined);
const notificationsStub = { send: notifySend } as unknown as NotificationsService;
// userId 7 = no provider configured; everyone else resolves to a stub config.
// Constructor-injected stub since the resolver became DI-native (settings migration).
const llmConfigStub = {
resolve: vi.fn((uid: number) => (uid === 7 ? null : { provider: 'openai', model: 'gpt-x', baseUrl: undefined, apiKey: 'sekret' })),
} as unknown as LlmConfigResolver;
const { llmExtract } = vi.hoisted(() => ({ llmExtract: vi.fn(async (input: { text?: string }) => [{ text: `answer:${input.text ?? ''}` }]) }));
vi.mock('../../../src/nest/llm-parse/llm-client.factory', () => ({ createLlmClient: vi.fn(() => ({ extract: llmExtract })) }));
// The per-user settings read the runtime deps delegate to (still a path mock —
// readUserSettingDecrypted is a bare function export, not an injected service).
vi.mock('../../../src/nest/plugins/plugins.service', () => ({ readUserSettingDecrypted: vi.fn((_pid: string, uid: number, key: string) => (uid === 5 && key === 'apiKey' ? 'k-5' : undefined)) }));
const oauthStub = { async getAccessToken(_pid: string, uid: number) { return uid === 5 ? 'tok-5' : null; } } as unknown as PluginOAuthService;
// Reservations: injected stub so the reservation deps' side-effect branches
// (accommodation / budget-sync / notify) run.
const reservationsStub = {
create(tid: string, input: Record<string, unknown>) {
return { reservation: { id: 40, trip_id: Number(tid), ...input }, accommodationCreated: input.title === 'Stay' };
},
getReservation(id: string) { return id === '404' ? undefined : { id: Number(id), title: 'Old', type: 'flight' }; },
update(id: string, tid: string, input: Record<string, unknown>) {
return { reservation: { id: Number(id), trip_id: Number(tid), ...input }, accommodationChanged: input.title === 'New' };
},
remove(id: string) {
if (id === '404') return { deleted: undefined, accommodationDeleted: false, deletedBudgetItemId: null };
return { deleted: { id: Number(id), title: 'Gone', type: 'hotel', accommodation_id: 7 }, accommodationDeleted: true, deletedBudgetItemId: 9 };
},
list(tid: string) { return [{ id: 1, trip_id: Number(tid), title: 'Flight' }]; },
syncBudgetOnCreate() {},
syncBudgetOnUpdate() {},
notifyBookingChange() {},
} as unknown as ReservationsService;
// Journey is a constructor-injected stub since the journey fold (same behaviors
// as the old services/journeyService path mock, keyed by the service methods).
const { onPlaceCreated, onPlaceUpdated, onPlaceDeleted } = vi.hoisted(() => ({
onPlaceCreated: vi.fn(), onPlaceUpdated: vi.fn(), onPlaceDeleted: vi.fn(),
}));
const journeyStub = {
// The skeleton hooks the place writes fire (#1705).
onPlaceCreated, onPlaceUpdated, onPlaceDeleted,
listJourneys: vi.fn((uid: number) => [{ id: 1, owner: uid }]),
// journeyId 88 = no access (listEntries self-gates to null); else returns entries
listEntries: vi.fn((journeyId: number, uid: number) => (journeyId === 88 ? null : [{ id: 10, journey_id: journeyId, author_id: uid }])),
// journeyId 99 = not editable by the acting user (canEdit inside returns null/false)
createEntry: vi.fn((journeyId: number, uid: number, data: unknown) => (journeyId === 99 ? null : { id: 120, journey_id: journeyId, created_by: uid, ...(data as object) })),
updateEntry: vi.fn((entryId: number, _uid: number, data: unknown) => (entryId === 99 ? null : { id: entryId, ...(data as object) })),
deleteEntry: vi.fn((entryId: number) => entryId !== 99),
createJourney: vi.fn((uid: number, data: unknown) => ({ id: 130, owner: uid, ...(data as object) })),
deleteJourney: vi.fn((journeyId: number) => journeyId !== 99),
} as unknown as JourneyDomainService;
// Atlas is a constructor-injected stub since the atlas fold (same behaviors as
// the old services/atlasService path mock, keyed by the service method names).
const atlasStub = {
listVisitedCountries: vi.fn(() => [{ country_code: 'JP' }]),
listManuallyVisitedRegions: vi.fn(() => [{ region_code: 'JP-13' }]),
bucketList: vi.fn((uid: number) => [{ id: 5, user_id: uid, name: 'Kyoto' }]),
markCountry: vi.fn(),
unmarkCountry: vi.fn(),
markRegion: vi.fn(),
unmarkRegion: vi.fn(),
createBucketItem: vi.fn((uid: number, data: { name: string }) => ({ id: 110, user_id: uid, name: data.name })),
deleteBucketItem: vi.fn((_uid: number, itemId: number) => Number(itemId) !== 404),
} as unknown as AtlasService;
// Collections is a constructor-injected stub since the collections fold (same
// behaviors as the old services/collectionsService path mock — the service
// throws status-tagged errors the factory maps onto the RPC error classes).
const collectionsHttpError = (status: number, message: string) => { const e = new Error(message) as Error & { status: number }; e.status = status; throw e; };
const collectionsStub = {
listCollections: vi.fn((uid: number) => ({ collections: [{ id: 1, owner: uid }] })),
getCollection: vi.fn((uid: number, id: number) => ({ id, owner: uid, places: [] })),
createCollection: vi.fn((uid: number, body: unknown) => ({ id: 100, owner_id: uid, ...(body as object) })),
// id 99 = viewer-only (403); id 404 = invisible (404) — the service throws status-tagged errors
updateCollection: vi.fn((_uid: number, id: number, body: unknown) => { if (id === 99) collectionsHttpError(403, 'read-only'); if (id === 404) collectionsHttpError(404, 'Collection not found'); return { id, ...(body as object) }; }),
savePlace: vi.fn((uid: number, body: unknown) => ({ id: 101, saved_by: uid, ...(body as object) })),
copyToTrip: vi.fn(() => ({ copied: 2, skipped: [] })),
deletePlace: vi.fn((_uid: number, placeId: number) => { if (placeId === 404) collectionsHttpError(404, 'Collection not found'); }),
} as unknown as CollectionsService;
// Day notes are a constructor-injected stub (same behaviors as the old path mock).
const dayNotesStub = {
list: vi.fn((dayId: number, tripId: number) => [{ id: 1, day_id: dayId, trip_id: tripId }]),
create: vi.fn((dayId: number, _tripId: number, text: string) => ({ id: 50, day_id: dayId, text })),
getNote: vi.fn((id: number) => (id === 99 ? undefined : { id, text: 'Old' })),
update: vi.fn((id: number, _current: unknown, fields: Record<string, unknown>) => ({ id, ...fields })),
remove: vi.fn(),
dayExists: vi.fn((dayId: number) => dayId === 3),
} as unknown as DayNotesService;
// Vacay is a constructor-injected stub (same behaviors as the old path mock).
const vacayStub = {
getPlanData: vi.fn((uid: number) => ({ plan: { id: 1, owner: uid } })),
getActivePlanId: vi.fn(() => 77),
toggleEntry: vi.fn((uid: number, planId: number) => ({ action: 'added', uid, planId })),
toggleCompanyHoliday: vi.fn((planId: number) => ({ action: 'added', planId })),
} as unknown as VacayService;
import { PluginHostDepsFactory, type PluginCallRouter } from '../../../src/nest/plugins/host/plugin-host-deps.factory';
import { getPluginDataDb, closePluginDataDb } from '../../../src/nest/plugins/host/plugin-host-state';
import { db as mockDb } from '../../../src/db/database';
import type { BudgetService } from '../../../src/nest/budget/budget.service';
import type { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
import type { ReservationsService } from '../../../src/nest/reservations/reservations.service';
import type { TagsService } from '../../../src/nest/tags/tags.service';
import type { CategoriesService } from '../../../src/nest/categories/categories.service';
import type { TodoService } from '../../../src/nest/todo/todo.service';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { DayNotesService } from '../../../src/nest/days/day-notes.service';
import type { DaysService } from '../../../src/nest/days/days.service';
import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import type { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import type { PluginOAuthService } from '../../../src/nest/plugins/plugin-oauth.service';
import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver';
import type { FilesService } from '../../../src/nest/files/files.service';
import type { CollabService } from '../../../src/nest/collab/collab.service';
import type { VacayService } from '../../../src/nest/vacay/vacay.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { PlacesService } from '../../../src/nest/places/places.service';
import type { CollectionsService } from '../../../src/nest/collections/collections.service';
import type { AtlasService } from '../../../src/nest/atlas/atlas.service';
import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import type { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { NotFoundError, ValidationError } from '../../../src/nest/trips/trips.service';
// The factory under test, wired exactly like PluginsModule does — but with the
// DI-native domain services replaced by the stubs above. The shim keeps the
// ~45 historical call sites unchanged and supplies a default no-op router.
const addonsStub = { isAddonEnabled } as unknown as import('../../../src/nest/addons/addons.service').AddonsService;
const tripsStub = {
updateTrip: (tripId: number, _u: number, input: Record<string, unknown>) => {
if (input.title === 'boom') throw new ValidationError('bad dates');
if (input.title === 'gone') throw new NotFoundError('no trip');
if (input.title === 'crash') throw new Error('unexpected');
return { updatedTrip: { id: tripId, ...input } };
},
create: (userId: number, input: Record<string, unknown>) => {
if (input.title === 'boom') throw new ValidationError('bad dates');
return { trip: { id: 99, user_id: userId, ...input }, tripId: 99, reminderDays: 3 };
},
list: () => [{ id: 1 }],
removeMember: vi.fn(),
} as unknown as import('../../../src/nest/trips/trips.service').TripsService;
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub, dayNotesStub, assignmentsStub, llmConfigStub, new DatabaseService(mockDb), filesStub, collabStub, vacayStub, daysStub, permissionsStub, exchangeRatesStub, addonsStub, new RealtimeService(), tripsStub, placesStub, collectionsStub, atlasStub, notificationsStub, membershipStub, journeyStub);
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
let tmp: string;
beforeAll(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'trekplug-crh-'));
process.env.TREK_PLUGINS_DATA_DIR = tmp;
});
afterAll(() => {
closePluginDataDb('wired');
delete process.env.TREK_PLUGINS_DATA_DIR;
fs.rmSync(tmp, { recursive: true, force: true });
});
describe('plugin host wiring (PluginHostDepsFactory)', () => {
it('caches one data db per plugin id', () => {
const a = getPluginDataDb('wired');
const b = getPluginDataDb('wired');
expect(a).toBe(b);
});
it('a granted db:own call runs against the plugin db, and a trip broadcast is namespaced', async () => {
const host = createRealRpcHost('wired', new Set(['db:own', 'ws:broadcast:trip']));
const migrated = await host.dispatch({ k: 'req', id: '1', method: 'db.migrate', params: { id: '001', sql: 'CREATE TABLE t (v TEXT)' } });
expect(migrated.ok).toBe(true);
// acting user 5 is a member of trip 1 (mocked canAccessTrip) → broadcast allowed + namespaced
await host.dispatch({ k: 'req', id: '2', method: 'ws.broadcastToTrip', params: { tripId: 1, event: 'ping', data: { a: 1 } } }, 5);
expect(broadcast).toHaveBeenCalledWith(1, 'plugin:wired:ping', { a: 1 });
const bcastUser = createRealRpcHost('wired', new Set(['ws:broadcast:user']));
// a per-user broadcast may only target the acting user themselves
await bcastUser.dispatch({ k: 'req', id: '3', method: 'ws.broadcastToUser', params: { userId: 5, event: 'hi', data: {} } }, 5);
expect(broadcastToUser).toHaveBeenCalledWith(5, { type: 'plugin:wired', event: 'hi' });
});
it('db.tx dispatches an atomic batch through to the plugin db under db:own', async () => {
const host = createRealRpcHost('wtx', new Set(['db:own']));
await host.dispatch({ k: 'req', id: '1', method: 'db.migrate', params: { id: '001', sql: 'CREATE TABLE kv (k TEXT, n INTEGER)' } });
const res = await host.dispatch({ k: 'req', id: '2', method: 'db.tx', params: { ops: [
{ sql: 'INSERT INTO kv (k, n) VALUES (?, ?)', args: ['a', 1] },
{ sql: 'SELECT n FROM kv WHERE k = ?', args: ['a'] },
] } });
expect(res.ok).toBe(true);
expect((res as { result: { results: unknown[] } }).result.results).toEqual([{ changes: 1 }, { rows: [{ n: 1 }] }]);
// malformed ops → BAD_PARAMS, and no db:own grant → not reachable
const bad = await host.dispatch({ k: 'req', id: '3', method: 'db.tx', params: { ops: [{ sql: 42 }] } });
expect(bad.ok).toBe(false);
const noGrant = createRealRpcHost('wtx2', new Set());
expect((await noGrant.dispatch({ k: 'req', id: '4', method: 'db.tx', params: { ops: [] } })).ok).toBe(false);
closePluginDataDb('wtx');
closePluginDataDb('wtx2');
});
it('closePluginDataDb closes and drops the cached handle', () => {
getPluginDataDb('transient');
closePluginDataDb('transient');
// a fresh get after close returns a NEW instance (cache was cleared)
const a = getPluginDataDb('transient');
closePluginDataDb('transient');
const b = getPluginDataDb('transient');
expect(a).not.toBe(b);
closePluginDataDb('transient');
});
it('getPluginDataDb recreates a handle that was closed WITHOUT eviction (terminal-failure dispose)', () => {
const a = getPluginDataDb('closedcache');
expect(a.isOpen()).toBe(true);
// simulate the supervisor's dispose() path: close the handle but leave it cached
a.close();
expect(a.isOpen()).toBe(false);
const b = getPluginDataDb('closedcache'); // must NOT return the dead handle
expect(b).not.toBe(a);
expect(b.isOpen()).toBe(true);
expect(b.exec('CREATE TABLE t (v)').changes).toBe(0); // usable again
closePluginDataDb('closedcache');
});
});
describe('host-deps factory — planner write + metadata deps', () => {
const host = (...perms: string[]) => createRealRpcHost('writer', new Set(perms));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const call = async (h: ReturnType<typeof host>, method: string, params: Record<string, unknown>, uid = 5): Promise<any> =>
h.dispatch({ k: 'req', id: 'x', method, params }, uid);
beforeEach(() => { checkPermission.mockReset(); checkPermission.mockReturnValue(true); });
afterAll(() => closePluginDataDb('writer'));
// places, days and itinerary left this factory with the decorator migration; the
// cases now run in tests/unit/places/ and tests/unit/days/.
// #1705: a place write from a plugin has to update a linked journey the same way
// the REST route does, otherwise the journey shows the old title (or an entry for
// a place that no longer exists) until it is reloaded.
// A journey link that blows up must not turn a successful place write into an
// RPC error — every other caller of these hooks swallows them too.
// #1705: a plugin itinerary write has to reach open sessions exactly like the REST
// route. The delete payload needs the dayId the client reducer evicts by, and both
// directions run the same journey-skeleton reconcile the controller/MCP tool run.
// trips.*, the cross-trip feeds and member management left this factory with the
// decorator migration; the cases now run in tests/unit/trips/trips.rpc.test.ts.
it('metadata: round-trips and enforces the key/value/access limits', async () => {
const h = host('db:meta');
expect((await call(h, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k', value: { a: 1 } })).ok).toBe(true);
expect((await call(h, 'meta.get', { entityType: 'trip', entityId: 1, key: 'k' })).result).toEqual({ a: 1 });
expect((await call(h, 'meta.set', { entityType: 'trip', entityId: 1, key: 'k', value: 2 })).ok).toBe(true); // upsert path
expect((await call(h, 'meta.list', { entityType: 'place', entityId: 7 })).ok).toBe(true); // place → trip 1
expect((await call(h, 'meta.delete', { entityType: 'trip', entityId: 1, key: 'k' })).result).toEqual({ deleted: true });
expect((await call(h, 'meta.set', { entityType: 'trip', entityId: 1, key: 'x'.repeat(300), value: 1 })).error.code).toBe('BAD_PARAMS');
expect((await call(h, 'meta.set', { entityType: 'trip', entityId: 1, key: 'big', value: 'y'.repeat(70000) })).error.code).toBe('BAD_PARAMS');
expect((await call(h, 'meta.set', { entityType: 'trip', entityId: 2, key: 'k', value: 1 })).error.code).toBe('RESOURCE_FORBIDDEN');
});
// costs, reservations and accommodations left this factory with the decorator
// migration; the cases now run in tests/unit/budget/ and tests/unit/reservations/.
it('users.getById is scoped to people the acting user shares a trip with', async () => {
const h = host('db:read:users');
expect((await call(h, 'users.getById', { id: 6 }, 5)).ok).toBe(true); // 5 (owner) + 6 (member) share trip 1
expect((await call(h, 'users.getById', { id: 999 }, 5)).error.code).toBe('RESOURCE_FORBIDDEN');
});
});
// The 'reservations, day notes, cross-trip + addon reads' suite is gone: every case in it moved onto the decorators.
// The packing write deps left this factory with the decorator migration. The #858
// transitions are asserted in tests/unit/packing/packing.rpc.test.ts, against the
// PackingService methods the REST controller uses too, so there is one copy now.
// The Wave 1 wiring suite is gone: weather, categories, rates, tags, todos, the
// roster and the packing bags all moved onto the decorators, so there was nothing
// left in it. Their cases live in the domain suites now.
// The 'Wave 2 wiring' suite is gone: every case in it moved onto the decorators.
// The 'Wave 3 wiring' suite is gone: every case in it moved onto the decorators.
describe('host-deps factory — Wave 4 wiring (notify / ai)', () => {
const host = (...perms: string[]) => createRealRpcHost('w4', new Set(perms))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const call = async (h: ReturnType<typeof host>, method: string, params: Record<string, unknown>, uid: number | undefined = 5): Promise<any> =>
h.dispatch({ k: 'req', id: 'x', method, params }, uid)
beforeEach(() => { notifySend.mockClear(); llmExtract.mockClear() })
afterAll(() => closePluginDataDb('w4'))
it('notify.send delegates to notificationService with the plugin_notification event + forced target', async () => {
const h = host('notify:send')
const r = await call(h, 'notify.send', { input: { title: 'Delay', body: 'AB123 late', scope: 'user', targetId: 5, link: '/trips/1' } }, 5)
expect(r.ok).toBe(true)
expect(notifySend).toHaveBeenCalledWith(expect.objectContaining({
event: 'plugin_notification', actorId: null, scope: 'user', targetId: 5,
params: expect.objectContaining({ title: 'Delay', body: 'AB123 late', link: '/trips/1' }),
}))
// trip scope for a trip the acting user (owner 5) can access
expect((await call(h, 'notify.send', { input: { title: 't', body: 'b', scope: 'trip', targetId: 1 } }, 5)).ok).toBe(true)
})
it('ai.complete/extract run under the resolved provider; unconfigured user → BAD_PARAMS', async () => {
const h = host('ai:invoke')
const c = await call(h, 'ai.complete', { prompt: 'Summarize' }, 5)
expect(c.ok).toBe(true)
expect(c.result).toMatchObject({ text: expect.stringContaining('answer:') })
expect(llmExtract).toHaveBeenCalled()
const e = await call(h, 'ai.extract', { text: 'AB123 JFK', jsonSchema: { type: 'object' } }, 5)
expect(e.ok).toBe(true)
expect(Array.isArray(e.result.results)).toBe(true)
// user 7 has no provider → the router's aiConfigured() check trips first
expect(((await call(h, 'ai.complete', { prompt: 'hi' }, 7)) as { error: { code: string } }).error.code).toBe('BAD_PARAMS')
})
it('scheduler.set upserts by name with caps; cancel removes; recurring floor enforced', async () => {
const h = createRealRpcHost('wsched', new Set(['jobs:run']));
const c = async (method: string, params: Record<string, unknown>): Promise<{ ok: boolean; result?: unknown; error?: { code: string; message: string } }> =>
h.dispatch({ k: 'req', id: 'x', method, params }, undefined) as never;
const due = Date.now() + 120_000;
expect((await c('scheduler.set', { name: 'poll', dueAt: due, payload: { a: 1 } })).ok).toBe(true);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dbAny = mockDb as any;
expect(dbAny.prepare("SELECT COUNT(*) AS n FROM plugin_scheduled_tasks WHERE plugin_id='wsched'").get().n).toBe(1);
// re-set same name = upsert (still 1 row, new due)
expect((await c('scheduler.set', { name: 'poll', dueAt: due + 1000 })).ok).toBe(true);
expect(dbAny.prepare("SELECT COUNT(*) AS n FROM plugin_scheduled_tasks WHERE plugin_id='wsched'").get().n).toBe(1);
// recurring below the 60s floor is refused
expect((await c('scheduler.set', { name: 'fast', dueAt: due, everyMs: 5000 })).error?.code).toBe('BAD_PARAMS');
// cancel removes it
expect((await c('scheduler.cancel', { name: 'poll' })).result).toMatchObject({ cancelled: true });
expect(dbAny.prepare("SELECT COUNT(*) AS n FROM plugin_scheduled_tasks WHERE plugin_id='wsched'").get().n).toBe(0);
closePluginDataDb('wsched');
})
it('enforces the daily notify + AI budgets, seeded from today\'s audit rows', async () => {
// Seed the audit with a plugin that has already spent its whole day (default caps
// are 100 notify / 200 ai) so the budget is exhausted on first use.
const today = new Date().toISOString().slice(0, 10) + 'T08:00:00.000Z';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dbAny = mockDb as any;
const ins = dbAny.prepare("INSERT INTO plugin_capability_audit (plugin_id, method, code, ts) VALUES (?, ?, 'ok', ?)");
for (let i = 0; i < 100; i++) ins.run('wbudget', 'notify.send', today);
for (let i = 0; i < 200; i++) ins.run('wbudget', 'ai.complete', today);
const h = createRealRpcHost('wbudget', new Set(['notify:send', 'ai:invoke']));
const c = async (method: string, params: Record<string, unknown>): Promise<{ ok: boolean; error?: { code: string; message: string } }> =>
h.dispatch({ k: 'req', id: 'x', method, params }, 5) as never;
const n = await c('notify.send', { input: { title: 't', body: 'b', scope: 'user', targetId: 5 } });
expect(n.ok).toBe(false);
expect(n.error?.code).toBe('BAD_PARAMS');
expect(n.error?.message).toMatch(/budget/i);
const a = await c('ai.complete', { prompt: 'hi' });
expect(a.ok).toBe(false);
expect(a.error?.message).toMatch(/budget/i);
closePluginDataDb('wbudget');
})
})
describe('host-deps factory — Wave 8 wiring (settings.get / oauth.getToken)', () => {
const host = (...perms: string[]) => createRealRpcHost('w8', new Set(perms))
// uid is explicit here (no default) — an undefined must stay undefined, not fall back.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const call = async (h: ReturnType<typeof host>, method: string, params: Record<string, unknown>, uid: number | undefined): Promise<any> =>
h.dispatch({ k: 'req', id: 'x', method, params }, uid)
afterAll(() => closePluginDataDb('w8'))
it('settings.get returns the acting user\'s decrypted value; userless → undefined', async () => {
const h = host() // no permission needed — the plugin's own settings
expect((await call(h, 'settings.get', { key: 'apiKey' }, 5)).result).toEqual({ value: 'k-5' })
expect((await call(h, 'settings.get', { key: 'apiKey' }, undefined)).result).toEqual({ value: undefined })
})
it('oauth.getToken returns only the acting user\'s access token, gated by oauth:client', async () => {
const h = host('oauth:client')
expect((await call(h, 'oauth.getToken', {}, 5)).result).toEqual({ accessToken: 'tok-5' })
expect((await call(h, 'oauth.getToken', {}, 7)).result).toEqual({ accessToken: null }) // not connected
expect((await call(h, 'oauth.getToken', {}, undefined)).result).toEqual({ accessToken: null }) // userless → null (SDK contract)
expect((await call(host(), 'oauth.getToken', {}, 5)).ok).toBe(false) // no grant
})
})
@@ -11,15 +11,18 @@ vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { PluginPhotosController } from '../../../src/nest/plugins/plugin-photos.controller';
import { PluginCalendarController } from '../../../src/nest/plugins/plugin-calendar.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function runtime(providers: string[], invoke: (id: string, fn: string, args: unknown[]) => unknown) {
return {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string, _hook: string, fn: string, args: unknown[]) => invoke(id, fn, args)),
} as unknown as PluginRuntimeService;
searchPhotos: vi.fn(async (id: string, query: string, page: number, limit: number) => invoke(id, 'search', [query, { page, limit }])),
getPhoto: vi.fn(async (id: string, photoId: string) => invoke(id, 'getById', [photoId])),
calendarName: vi.fn(async (id: string) => invoke(id, 'getName', [])),
calendarEvents: vi.fn(async (id: string, userId: number, start: string, end: string) => invoke(id, 'getEvents', [userId, start, end])),
} as unknown as PluginHooks;
}
describe('PluginPhotosController (photoProvider hook)', () => {
@@ -54,7 +57,7 @@ describe('PluginPhotosController (photoProvider hook)', () => {
const c = new PluginPhotosController(rt);
const out = (await c.search('beach', '3', req(7))).providers;
expect(out.map((p) => p.pluginId)).toEqual(['ok']);
expect(rt.invokeHook).toHaveBeenCalledWith('ok', 'photoProvider', 'search', ['beach', { page: 3, limit: 60 }], 7, 5000);
expect(rt.searchPhotos).toHaveBeenCalledWith('ok', 'beach', 3, 60, 7);
});
it('item: returns one normalized photo from a known provider, null for an unknown one', async () => {
@@ -81,7 +84,7 @@ describe('PluginCalendarController (calendarSource hook)', () => {
expect(out[0].events).toHaveLength(1);
expect(out[0].events[0]).toMatchObject({ id: 'e1', title: 'Flight', allDay: false });
// getEvents got the user + the window
expect(rt.invokeHook).toHaveBeenCalledWith('cal', 'calendarSource', 'getEvents', [9, '2026-07-01T00:00:00Z', '2026-08-01T00:00:00Z'], 9, 5000);
expect(rt.calendarEvents).toHaveBeenCalledWith('cal', 9, '2026-07-01T00:00:00Z', '2026-08-01T00:00:00Z');
});
it('gates on user + plugins-enabled, and skips a failing source', async () => {
@@ -21,15 +21,15 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { PluginRoutesController } from '../../../src/nest/plugins/plugin-routes.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(invoke: () => unknown, providers = ['ev-plug']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async () => invoke()),
} as unknown as PluginRuntimeService;
route: vi.fn(async () => invoke()),
} as unknown as PluginHooks;
return { c: new PluginRoutesController(runtime, new DatabaseService(dbConn)), runtime };
}
const wp = (n = 3) => Array.from({ length: n }, (_, i) => ({ lat: 48 + i * 0.1, lng: 2 + i * 0.1 }));
@@ -74,7 +74,7 @@ describe('PluginRoutesController', () => {
for (const b of cases) {
const { c, runtime } = controller(() => goodRoute());
expect((await c.route('ev-plug', 'ev', b as never, req(5))).route).toBeNull();
expect(runtime.invokeHook).not.toHaveBeenCalled();
expect(runtime.route).not.toHaveBeenCalled();
}
});
@@ -97,11 +97,7 @@ describe('PluginRoutesController', () => {
expect(route!.profile).toBe('ev');
expect(route!.legs[0].note).toBe('charge to 80%');
expect(route!.viaPoints[0]).toMatchObject({ label: 'Fastned', tone: 'success', dwellSeconds: 1501 });
expect(runtime.invokeHook).toHaveBeenCalledWith(
'ev-plug', 'routeProvider', 'getRoute',
[{ tripId: 1, dayId: 7, profile: 'ev', waypoints: wp() }],
5, 20_000,
);
expect(runtime.route).toHaveBeenCalledWith('ev-plug', { tripId: 1, dayId: 7, profile: 'ev', waypoints: wp() }, 5);
});
it('rejects a malformed route whole: wrong leg count, bad vertex, negative numbers', async () => {
+35 -116
View File
@@ -1,17 +1,18 @@
/**
* The coverage ledger: the anchor for the whole decorator rollout.
*
* Every wire method is owned exactly once, either by the legacy router blocks in
* rpc-host.ts or by a decorated *.rpc.ts class in the registry. Both sets are derived
* by construction, so no list is maintained by hand and the test cannot drift.
* Every wire method is owned by exactly one decorated *.rpc.ts class in the registry.
* Both sets are derived by construction, so no list is maintained by hand and the test
* cannot drift.
*
* It fails the moment a migration PR moves a method and forgets to delete the legacy
* registration, deletes one without adding it, or forgets to list a new *.rpc.ts class
* in allRpcControllers().
* The rollout is finished, so the legacy set is empty and the ledger's job flips from
* "how far along is the move" to "nothing fell out of it": a method deleted without a
* replacement, or a new *.rpc.ts class that no one listed in allRpcControllers().
*/
import { describe, it, expect } from 'vitest';
import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import { PluginRpcRegistryService } from '../../../src/nest/plugins/host/rpc-kit/registry.service';
import {
KNOWN_METHODS,
KNOWN_PERMISSIONS,
@@ -29,130 +30,48 @@ describe('plugin RPC coverage ledger', () => {
const host = new PluginRpcHost('probe', new Set<string>(KNOWN_PERMISSIONS), makeDeps(), registry);
const all = boundMethods(host);
const fromRegistry = registry.methodNames();
const legacy = new Set([...all].filter((m) => !fromRegistry.has(m)));
const vocabulary = new Set<string>([...KNOWN_METHODS, ...UNCONDITIONAL_METHODS]);
it('RPCLEDGER-001 no method is owned by both the registry and the legacy router', () => {
expect([...fromRegistry].filter((m) => legacy.has(m))).toEqual([]);
it('RPCLEDGER-001 every bound method comes from the registry, none from anywhere else', () => {
expect([...all].filter((m) => !fromRegistry.has(m))).toEqual([]);
});
it('RPCLEDGER-002 every registered method is one the wire protocol knows', () => {
const vocabulary = new Set<string>([...KNOWN_METHODS, ...UNCONDITIONAL_METHODS]);
expect([...all].filter((m) => !vocabulary.has(m))).toEqual([]);
});
it('RPCLEDGER-003 no method in the vocabulary is orphaned', () => {
const vocabulary = new Set<string>([...KNOWN_METHODS, ...UNCONDITIONAL_METHODS]);
expect([...vocabulary].filter((m) => !all.has(m))).toEqual([]);
});
it('RPCLEDGER-004 the two owner sets partition the vocabulary exactly', () => {
expect(all).toEqual(new Set<string>([...KNOWN_METHODS, ...UNCONDITIONAL_METHODS]));
expect(fromRegistry.size + legacy.size).toBe(all.size);
it('RPCLEDGER-004 the registry covers the vocabulary exactly', () => {
expect(all).toEqual(vocabulary);
expect(fromRegistry.size).toBe(KNOWN_METHODS.length + UNCONDITIONAL_METHODS.length);
});
it('RPCLEDGER-005 the migration ledger reads as expected for this PR', () => {
// Update these two numbers in every rollout PR. They make the diff state the size
// of the move out loud, which is the number a reviewer wants to see.
const total = KNOWN_METHODS.length + UNCONDITIONAL_METHODS.length;
expect(fromRegistry.size).toBe(93);
expect(legacy.size).toBe(total - 93);
it('RPCLEDGER-005 the surface is the 113 methods the protocol declares', () => {
// Pinned rather than derived: a method DELETED from KNOWN_METHODS together with
// its handler would keep every test above green, and this is the line that makes
// that show up in the diff.
expect(KNOWN_METHODS.length).toBe(110);
expect(UNCONDITIONAL_METHODS.length).toBe(3);
expect(fromRegistry.size).toBe(113);
});
it('RPCLEDGER-006 the migrated methods are exactly the ones this PR claims', () => {
expect([...fromRegistry].sort()).toEqual([
'accommodations.create',
'accommodations.delete',
'accommodations.update',
'atlas.bucketList',
'atlas.createBucketItem',
'atlas.deleteBucketItem',
'atlas.markCountry',
'atlas.markRegion',
'atlas.unmarkCountry',
'atlas.unmarkRegion',
'atlas.visited',
'categories.list',
'collab.createMessage',
'collab.createNote',
'collab.createPoll',
'collab.listMessages',
'collab.listNotes',
'collab.listPolls',
'collab.votePoll',
'collections.copyToTrip',
'collections.create',
'collections.deletePlace',
'collections.get',
'collections.listMine',
'collections.savePlace',
'collections.update',
'costs.create',
'costs.delete',
'costs.getByTrip',
'costs.listMine',
'costs.update',
'daynotes.create',
'daynotes.delete',
'daynotes.list',
'daynotes.update',
'days.create',
'days.delete',
'days.update',
'files.create',
'files.createLink',
'files.getContent',
'files.list',
'files.softDelete',
'files.update',
'itinerary.assign',
'itinerary.unassign',
'journal.createEntry',
'journal.createJourney',
'journal.deleteEntry',
'journal.deleteJourney',
'journal.getEntries',
'journal.listMine',
'journal.updateEntry',
'packing.create',
'packing.createBag',
'packing.delete',
'packing.deleteBag',
'packing.list',
'packing.listBags',
'packing.setBagMembers',
'packing.update',
'packing.updateBag',
'places.create',
'places.delete',
'places.update',
'rates.get',
'reservations.create',
'reservations.delete',
'reservations.listMine',
'reservations.update',
'tags.create',
'tags.delete',
'tags.list',
'tags.update',
'todos.create',
'todos.delete',
'todos.list',
'todos.update',
'trips.addMember',
'trips.create',
'trips.getAccommodations',
'trips.getById',
'trips.getDays',
'trips.getPlaces',
'trips.getReservations',
'trips.listMine',
'trips.members',
'trips.removeMember',
'trips.update',
'vacay.mine',
'vacay.toggleCompanyHoliday',
'vacay.toggleEntry',
'weather.get',
]);
it('RPCLEDGER-006 boot-time total coverage is armed in production', () => {
// The rollout's closing move: the registry service now FAILS APP BOOT when a
// KNOWN_METHOD has no decorated owner, instead of letting it surface as a runtime
// PERMISSION_DENIED nobody can explain.
const options = (new PluginRpcRegistryService({} as never, {} as never) as unknown as {
options: { requireTotalCoverage?: boolean };
}).options;
expect(options.requireTotalCoverage).toBe(true);
});
it('RPCLEDGER-007 a registry missing a method fails validate() rather than booting', () => {
// Drops TagsRpc, a method owner. Dropping the last entry would drop PluginHooks
// instead, and the failure would be about hooks rather than methods.
const short = allRpcControllers().slice(1);
expect(() => createTestPluginRegistry(short, { requireTotalCoverage: true })).toThrow(/has no handler/);
});
});
@@ -15,11 +15,15 @@ import { PackingRpc } from '../../../src/nest/packing/packing.rpc';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { TripsRpc } from '../../../src/nest/trips/trips.rpc';
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
const req = (method: string, params: Record<string, unknown>): RpcRequest => ({ k: 'req', id: 'x', method, params });
/** db.* is the cheapest handler to watch, and it needs no services of its own. */
const dbRegistry = () => createTestPluginRegistry([new DbRpc()]);
/** trips.getById lives on the decorators now, so the audit cases bind it through them. */
const tripsRegistry = () => {
const db = {
@@ -35,13 +39,13 @@ const tripsRegistry = () => {
describe('dispatch strips the supervisor _inv marker', () => {
it('RPCINV-001 the handler never sees _inv', async () => {
const deps = makeDeps();
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const host = new PluginRpcHost('p', new Set(['db:own']), deps, dbRegistry());
await host.dispatch(req('db.query', { sql: 'SELECT 1', args: [], _inv: 'req-7' }));
expect(deps.data.query).toHaveBeenCalledWith('SELECT 1', []);
});
it('RPCINV-002 the result is identical with and without the marker', async () => {
const host = new PluginRpcHost('p', new Set(['db:own']), makeDeps());
const host = new PluginRpcHost('p', new Set(['db:own']), makeDeps(), dbRegistry());
const withMarker = (await host.dispatch(req('db.query', { sql: 'SELECT 1', _inv: 'req-7' }))) as RpcResponse;
const without = (await host.dispatch(req('db.query', { sql: 'SELECT 1' }))) as RpcResponse;
expect(withMarker.ok).toBe(true);
@@ -73,7 +77,7 @@ describe('dispatch strips the supervisor _inv marker', () => {
it('RPCINV-005 params without the marker are passed through untouched', async () => {
const deps = makeDeps();
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const host = new PluginRpcHost('p', new Set(['db:own']), deps, dbRegistry());
await host.dispatch(req('db.exec', { sql: 'INSERT INTO t VALUES (1)', args: [1] }));
expect(deps.data.exec).toHaveBeenCalledWith('INSERT INTO t VALUES (1)', [1]);
});
+159 -253
View File
@@ -1,296 +1,202 @@
/**
* The capability router is the plugin permission boundary (#plugins, M1). These
* tests prove that an ungranted method is never reachable, a granted method
* works, a granted trip read is still membership-checked against the acting
* user, and bad params / unknown methods are rejected — without ever spawning a
* child (the router runs in the host).
* The capability router is the plugin permission boundary (#plugins, M1).
*
* Every handler now lives on a decorated *.rpc.ts class in its own domain, and each of
* those has its own suite. What is left here is the router itself: an ungranted method
* is never reachable, an unknown one is told apart from a denied one, a thrown error
* maps to the right wire code, and the audit sink sees the call — without ever
* spawning a child (the router runs in the host).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { PluginRpcHost, type HostDeps } from '../../../src/nest/plugins/host/rpc-host';
import { describe, it, expect, vi } from 'vitest';
import { PluginRpcHost, BadParams, ForbiddenResource, type HostDeps } from '../../../src/nest/plugins/host/rpc-host';
import { PluginController, PluginMethod, PluginOpenMethod } from '../../../src/nest/plugins/host/rpc-kit/decorators';
import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing';
import type { PluginRpcContext } from '../../../src/nest/plugins/host/rpc-kit/types';
import type { RpcRequest, RpcResponse, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import { makeDeps } from '../../helpers/rpc-host-deps';
const req = (method: string, params: Record<string, unknown> = {}): RpcRequest => ({ k: 'req', id: 'x', method, params });
const ok = (r: RpcResponse | RpcError): r is RpcResponse => r.ok === true;
const code = (r: RpcResponse | RpcError): string => (r as RpcError).error.code;
/**
* A throwaway controller over two real wire methods, so the router can be exercised
* without dragging a domain's services in. `tags.list` and `tags.create` are used
* because their permissions differ, which is what the split-grant cases need.
*/
@PluginController()
class ProbeRpc {
constructor(private readonly behaviour: (params: Record<string, unknown>, ctx: PluginRpcContext) => unknown) {}
@PluginMethod('tags.list', { permission: 'db:read:tags' })
read(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.behaviour(params, ctx);
}
@PluginMethod('tags.create', { permission: 'db:write:tags' })
write(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.behaviour(params, ctx);
}
@PluginOpenMethod('events.emit')
open(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.behaviour(params, ctx);
}
}
const makeHost = (
granted: string[],
behaviour: (params: Record<string, unknown>, ctx: PluginRpcContext) => unknown = () => ({ done: true }),
deps: HostDeps = makeDeps(),
): PluginRpcHost =>
new PluginRpcHost('p', new Set(granted), deps, createTestPluginRegistry([new ProbeRpc(behaviour)]));
describe('PluginRpcHost — capability enforcement', () => {
let deps: HostDeps;
beforeEach(() => { deps = makeDeps(); });
it('registers only granted methods; an ungranted method is PERMISSION_DENIED', async () => {
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const denied = await host.dispatch(req('trips.getById', { tripId: 1, asUserId: 42 }));
expect(denied.ok).toBe(false);
expect((denied as RpcError).error.code).toBe('PERMISSION_DENIED');
expect(deps.canAccessTrip).not.toHaveBeenCalled();
it('RPCHOST-001 registers only granted methods; an ungranted one is PERMISSION_DENIED', async () => {
const seen = vi.fn(() => ({ done: true }));
const host = makeHost(['db:read:tags'], seen);
expect(ok(await host.dispatch(req('tags.list'), 42))).toBe(true);
expect(code(await host.dispatch(req('tags.create'), 42))).toBe('PERMISSION_DENIED');
// The refusal happens before the handler, so the domain never runs at all.
expect(seen).toHaveBeenCalledTimes(1);
});
it('a granted db:own method runs against the plugin db', async () => {
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const res = await host.dispatch(req('db.query', { sql: 'SELECT 1', args: [] }));
expect(ok(res)).toBe(true);
expect((res as RpcResponse).result).toEqual([{ n: 1 }]);
expect(deps.data.query).toHaveBeenCalledWith('SELECT 1', []);
});
it('an unknown method is UNKNOWN_METHOD, not PERMISSION_DENIED', async () => {
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
it('RPCHOST-002 an unknown method is UNKNOWN_METHOD, not PERMISSION_DENIED', async () => {
const host = makeHost(['db:read:tags']);
const res = await host.dispatch(req('fs.readFile', { path: '/etc/passwd' }));
expect((res as RpcError).error.code).toBe('UNKNOWN_METHOD');
expect(code(res)).toBe('UNKNOWN_METHOD');
expect((res as RpcError).error.message).toBe('unknown method fs.readFile');
});
// The trips, roster and member cases moved to tests/unit/trips/trips.rpc.test.ts.
it('db:read:users returns only the public projection for a visible user', async () => {
const host = new PluginRpcHost('p', new Set(['db:read:users']), deps);
const res = await host.dispatch(req('users.getById', { id: 3 }), 42);
expect(ok(res)).toBe(true);
expect((res as RpcResponse).result).toEqual({ id: 3, username: 'ada', display_name: 'Ada', avatar: null });
// the SELECT column list is host-controlled — no password/token columns
expect(deps.db.prepare).toHaveBeenCalledWith(expect.stringContaining('id, username, display_name, avatar'));
it('RPCHOST-003 a denied known method names the plugin, so the log says who asked', async () => {
const res = await makeHost([]).dispatch(req('tags.list'), 42);
expect((res as RpcError).error.message).toBe('tags.list requires a permission "p" was not granted');
});
it('db:read:users is RESOURCE_FORBIDDEN for a user the acting user cannot see (no enumeration)', async () => {
const host = new PluginRpcHost('p', new Set(['db:read:users']), deps);
const forbidden = await host.dispatch(req('users.getById', { id: 999 }), 42);
expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
// and with no bound acting user (job / forged call), also denied
const noUser = await host.dispatch(req('users.getById', { id: 3 }), undefined);
expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('ws:broadcast:trip forwards to the (namespaced) broadcaster for a member', async () => {
const host = new PluginRpcHost('p', new Set(['ws:broadcast:trip']), deps);
const res = await host.dispatch(req('ws.broadcastToTrip', { tripId: 1, event: 'ping', data: { a: 1 } }), 42);
expect(ok(res)).toBe(true);
expect(deps.broadcastToTrip).toHaveBeenCalledWith(1, 'ping', { a: 1 });
});
it('ws:broadcast:trip is RESOURCE_FORBIDDEN for a non-member trip (no cross-tenant push)', async () => {
const host = new PluginRpcHost('p', new Set(['ws:broadcast:trip']), deps);
const forbidden = await host.dispatch(req('ws.broadcastToTrip', { tripId: 999, event: 'x', data: {} }), 42);
expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
expect(deps.broadcastToTrip).not.toHaveBeenCalled();
// and a broadcast with no bound acting user is denied too
const noUser = await host.dispatch(req('ws.broadcastToTrip', { tripId: 1, event: 'x', data: {} }), undefined);
expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
});
it('bad params are BAD_PARAMS', async () => {
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const res = await host.dispatch(req('db.query', { args: [] }));
expect((res as RpcError).error.code).toBe('BAD_PARAMS');
});
it('with no permissions, every real method is denied', async () => {
const host = new PluginRpcHost('p', new Set<string>(), deps);
for (const m of ['db.query', 'trips.getById', 'users.getById', 'ws.broadcastToTrip']) {
const res = await host.dispatch(req(m, { tripId: 1, asUserId: 42, id: 3, event: 'x', sql: 'SELECT 1' }));
expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
it('RPCHOST-004 with no permissions at all, every permissioned method is denied', async () => {
const host = makeHost([]);
for (const method of ['tags.list', 'tags.create']) {
expect(code(await host.dispatch(req(method), 42))).toBe('PERMISSION_DENIED');
}
});
it('ws:broadcast:user forwards only to the acting user (never an arbitrary one)', async () => {
const host = new PluginRpcHost('p', new Set(['ws:broadcast:user']), deps);
const res = await host.dispatch(req('ws.broadcastToUser', { userId: 42, event: 'poke', data: { x: 2 } }), 42);
expect(ok(res)).toBe(true);
expect(deps.broadcastToUser).toHaveBeenCalledWith(42, { event: 'poke', x: 2 });
// broadcasting to a DIFFERENT user is refused
const forbidden = await host.dispatch(req('ws.broadcastToUser', { userId: 9, event: 'poke', data: {} }), 42);
expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
it('RPCHOST-005 an unconditional method needs no grant', async () => {
expect(ok(await makeHost([]).dispatch(req('events.emit'), 42))).toBe(true);
});
it('non-array db args are BAD_PARAMS; a primitive ws payload is wrapped', async () => {
const host = new PluginRpcHost('p', new Set(['db:own', 'ws:broadcast:trip']), deps);
const bad = await host.dispatch(req('db.query', { sql: 'SELECT 1', args: 'nope' }));
expect((bad as RpcError).error.code).toBe('BAD_PARAMS');
await host.dispatch(req('ws.broadcastToTrip', { tripId: 1, event: 'ping', data: 'primitive' }), 42);
expect(deps.broadcastToTrip).toHaveBeenCalledWith(1, 'ping', { value: 'primitive' });
});
it('dispose() closes the plugin data db', () => {
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
host.dispose();
expect(deps.data.close).toHaveBeenCalled();
});
// The costs, reservation and accommodation cases moved to their domain suites.
// The addon-gated domains moved to their own suites; addon-gates.rpc.test.ts
// covers every gate in one table.
// The daynotes cases moved to tests/unit/days/day-notes.rpc.test.ts.
// weather.get, categories.list and rates.get moved to tests/unit/plugins/tenant-free.rpc.test.ts.
// The tags cases moved to tests/unit/tags/tags.rpc.test.ts with the handlers.
// The files cases moved to tests/unit/files/files.rpc.test.ts with the handlers.
it('notify.send forces the recipient to the acting user or a member trip; admin scope refused', async () => {
const host = new PluginRpcHost('p', new Set(['notify:send']), deps);
expect(ok(await host.dispatch(req('notify.send', { input: { title: 'Delay', body: 'AB123 is late', scope: 'user', targetId: 42 } }), 42))).toBe(true);
expect(deps.sendPluginNotification).toHaveBeenCalledWith('p', expect.objectContaining({ scope: 'user', targetId: 42 }));
expect(ok(await host.dispatch(req('notify.send', { input: { title: 'Trip', body: 'x', scope: 'trip', targetId: 1 } }), 42))).toBe(true);
// another user (scope user, foreign targetId) → forbidden
expect(((await host.dispatch(req('notify.send', { input: { title: 't', body: 'b', scope: 'user', targetId: 99 } }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
// a trip the acting user isn't in → forbidden
expect(((await host.dispatch(req('notify.send', { input: { title: 't', body: 'b', scope: 'trip', targetId: 2 } }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
// admin scope → bad params (not an allowed scope)
expect((await host.dispatch(req('notify.send', { input: { title: 't', body: 'b', scope: 'admin', targetId: 0 } }), 42)).ok).toBe(false);
// a protocol-relative / absolute link → rejected
expect((await host.dispatch(req('notify.send', { input: { title: 't', body: 'b', scope: 'user', targetId: 42, link: '//evil.com' } }), 42)).ok).toBe(false);
expect((await host.dispatch(req('notify.send', { input: { title: '', body: 'b', scope: 'user', targetId: 42 } }), 42)).ok).toBe(false);
});
it('ai.complete/extract require a configured provider + a bound user, with caps', async () => {
const host = new PluginRpcHost('p', new Set(['ai:invoke']), deps);
expect(ok(await host.dispatch(req('ai.complete', { prompt: 'Summarize my trip' }), 42))).toBe(true);
expect(ok(await host.dispatch(req('ai.extract', { text: 'AB123 JFK 10:00', jsonSchema: { type: 'object' } }), 42))).toBe(true);
expect((await host.dispatch(req('ai.complete', { prompt: '' }), 42)).ok).toBe(false);
expect((await host.dispatch(req('ai.extract', { text: 'x', jsonSchema: 'not-an-object' }), 42)).ok).toBe(false);
expect((await host.dispatch(req('ai.complete', { prompt: 'x'.repeat(20001) }), 42)).ok).toBe(false);
// user 7 has no provider configured → bad params (not a crash)
expect((await host.dispatch(req('ai.complete', { prompt: 'hi' }), 7)).ok).toBe(false);
// no user context at all → forbidden
expect((await host.dispatch(req('ai.complete', { prompt: 'hi' }), undefined)).ok).toBe(false);
});
it('settings.get returns the acting user\'s own value; a userless context yields undefined', async () => {
// No permission required — it only ever returns THIS plugin's config for the acting user.
const host = new PluginRpcHost('p', new Set(), deps);
const bound = await host.dispatch(req('settings.get', { key: 'apiKey' }), 42);
expect(ok(bound)).toBe(true);
expect((bound as RpcResponse).result).toEqual({ value: 'secret-of-p' });
expect(deps.getUserSetting).toHaveBeenCalledWith('p', 42, 'apiKey');
const userless = await host.dispatch(req('settings.get', { key: 'apiKey' }), undefined);
expect((userless as RpcResponse).result).toEqual({ value: undefined });
});
it('oauth.getToken needs the grant + a bound user; returns only the access token', async () => {
const host = new PluginRpcHost('p', new Set(['oauth:client']), deps);
const ok1 = await host.dispatch(req('oauth.getToken', {}), 42);
expect(ok(ok1)).toBe(true);
expect((ok1 as RpcResponse).result).toEqual({ accessToken: 'access-token-xyz' });
expect(deps.getOAuthToken).toHaveBeenCalledWith('p', 42);
// no bound user (a job/onLoad) → null, matching the SDK contract, not an error
const userless = await host.dispatch(req('oauth.getToken', {}), undefined);
expect(ok(userless)).toBe(true);
expect((userless as RpcResponse).result).toEqual({ accessToken: null });
// without the grant → not reachable
const noGrant = new PluginRpcHost('p', new Set(), deps);
expect((await noGrant.dispatch(req('oauth.getToken', {}), 42)).ok).toBe(false);
});
it('scheduler.set/cancel ride on jobs:run and are userless (no acting user needed)', async () => {
const host = new PluginRpcHost('p', new Set(['jobs:run']), deps);
// userless (no bound user) is fine — scheduled tasks are like jobs
const set = await host.dispatch(req('scheduler.set', { name: 'poll', dueAt: 123, everyMs: 60000, payload: { x: 1 } }), undefined);
expect(ok(set)).toBe(true);
expect(deps.schedulerSet).toHaveBeenCalledWith('poll', 123, 60000, { x: 1 });
const cancel = await host.dispatch(req('scheduler.cancel', { name: 'poll' }), undefined);
expect(ok(cancel)).toBe(true);
// without jobs:run → not reachable
const noGrant = new PluginRpcHost('p', new Set(), deps);
expect((await noGrant.dispatch(req('scheduler.set', { name: 'x', dueAt: 1 }), 42) as RpcError).error.code).toBe('PERMISSION_DENIED');
});
it('a read scope is denied without its own permission', async () => {
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
expect((await host.dispatch(req('journal.listMine'), 42)).ok).toBe(false);
expect((await host.dispatch(req('daynotes.list', { tripId: 1, dayId: 5 }), 42)).ok).toBe(false);
});
it('an error thrown by a handler becomes HOST_ERROR', async () => {
(deps.data.query as ReturnType<typeof vi.fn>).mockImplementation(() => {
throw new Error('disk gone');
it('RPCHOST-006 the host-bound acting user reaches the handler, never a params field', async () => {
let seen: PluginRpcContext | undefined;
const host = makeHost(['db:read:tags'], (_p, ctx) => {
seen = ctx;
return null;
});
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const res = await host.dispatch(req('db.query', { sql: 'SELECT 1', args: [] }));
expect((res as RpcError).error.code).toBe('HOST_ERROR');
await host.dispatch(req('tags.list', { asUserId: 999 }), 42);
expect(seen?.actingUserId).toBe(42);
expect(seen?.pluginId).toBe('p');
await host.dispatch(req('tags.list'), undefined);
expect(seen?.actingUserId).toBeUndefined();
});
it('RPCHOST-007 the context exposes the plugin db handle and the inter-plugin peers', async () => {
const deps = makeDeps();
let seen: PluginRpcContext | undefined;
const host = makeHost(['db:read:tags'], (_p, ctx) => {
seen = ctx;
return null;
}, deps);
await host.dispatch(req('tags.list'), 42);
expect(seen?.data).toBe(deps.data);
await seen?.plugins.call('other', 'sum', [1], 42);
expect(deps.callPlugin).toHaveBeenCalledWith('other', 'sum', [1], 42);
seen?.plugins.emit('ping', { a: 1 });
expect(deps.emitPluginEvent).toHaveBeenCalledWith('ping', { a: 1 });
});
it('RPCHOST-008 BadParams and ForbiddenResource map to their own wire codes', async () => {
expect(code(await makeHost(['db:read:tags'], () => {
throw new BadParams('sql must be a string');
}).dispatch(req('tags.list'), 42))).toBe('BAD_PARAMS');
expect(code(await makeHost(['db:read:tags'], () => {
throw new ForbiddenResource('no access to trip 9');
}).dispatch(req('tags.list'), 42))).toBe('RESOURCE_FORBIDDEN');
});
it('RPCHOST-009 any other error becomes HOST_ERROR with its message', async () => {
const res = await makeHost(['db:read:tags'], () => {
throw new Error('disk gone');
}).dispatch(req('tags.list'), 42);
expect(code(res)).toBe('HOST_ERROR');
expect((res as RpcError).error.message).toBe('disk gone');
});
it('a non-Error thrown by a handler still maps to HOST_ERROR', async () => {
(deps.data.query as ReturnType<typeof vi.fn>).mockImplementation(() => {
it('RPCHOST-010 a non-Error throw still maps to HOST_ERROR, with a generic message', async () => {
const res = await makeHost(['db:read:tags'], () => {
throw 'raw string';
});
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
const res = await host.dispatch(req('db.query', { sql: 'SELECT 1' }));
expect((res as RpcError).error.code).toBe('HOST_ERROR');
}).dispatch(req('tags.list'), 42);
expect(code(res)).toBe('HOST_ERROR');
expect((res as RpcError).error.message).toBe('internal error');
});
// ── Costs (budget items): db:read:costs / db:write:costs ────────────────────
// --- Planner writes (#1429) ---
// The places, days and itinerary cases moved to their own domain suites.
it('places.create is PERMISSION_DENIED without db:write:places', async () => {
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
const res = await host.dispatch(req('places.create', { tripId: 1, input: { name: 'X' } }), 42);
expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
it('RPCHOST-011 an async handler is awaited before the response is built', async () => {
const host = makeHost(['db:read:tags'], async () => {
await Promise.resolve();
return { late: true };
});
expect(((await host.dispatch(req('tags.list'), 42)) as RpcResponse).result).toEqual({ late: true });
});
// --- Plugin metadata (db:meta) ---
it('db:meta stores and reads namespaced metadata on an accessible entity', async () => {
const host = new PluginRpcHost('p', new Set(['db:meta']), deps);
const set = await host.dispatch(req('meta.set', { entityType: 'trip', entityId: 1, key: 'rating', value: 5 }), 42);
expect(ok(set)).toBe(true);
expect(deps.metaSet).toHaveBeenCalledWith('trip', 1, 'rating', 5);
const placeOk = await host.dispatch(req('meta.get', { entityType: 'place', entityId: 7, key: 'x' }), 42);
expect(ok(placeOk)).toBe(true); // place 7 resolves to accessible trip 1
it('RPCHOST-012 a rejected promise is mapped like a throw', async () => {
const host = makeHost(['db:read:tags'], async () => {
throw new BadParams('async refusal');
});
expect(code(await host.dispatch(req('tags.list'), 42))).toBe('BAD_PARAMS');
});
it('meta.set is PERMISSION_DENIED without db:meta', async () => {
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
const res = await host.dispatch(req('meta.set', { entityType: 'trip', entityId: 1, key: 'x', value: 1 }), 42);
expect((res as RpcError).error.code).toBe('PERMISSION_DENIED');
it('RPCHOST-013 missing params are treated as an empty object, not a crash', async () => {
let seen: Record<string, unknown> | undefined;
const host = makeHost(['db:read:tags'], (params) => {
seen = params;
return null;
});
expect(ok(await host.dispatch({ k: 'req', id: 'x', method: 'tags.list' }, 42))).toBe(true);
expect(seen).toEqual({});
});
it('meta is RESOURCE_FORBIDDEN on an entity the acting user cannot access', async () => {
const host = new PluginRpcHost('p', new Set(['db:meta']), deps);
const res = await host.dispatch(req('meta.set', { entityType: 'trip', entityId: 2, key: 'x', value: 1 }), 42);
expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
expect(deps.metaSet).not.toHaveBeenCalled();
it('RPCHOST-014 the audit sink sees the outcome of an auditable call, denials included', async () => {
const audit = vi.fn();
const deps = { ...makeDeps(), audit };
expect(ok(await makeHost(['db:read:tags'], () => null, deps).dispatch(req('tags.list'), 42))).toBe(true);
expect(audit).toHaveBeenCalledWith(expect.objectContaining({ pluginId: 'p', actingUserId: 42, method: 'tags.list', code: 'ok' }));
audit.mockClear();
await makeHost([], () => null, deps).dispatch(req('tags.list'), 42);
expect(audit).toHaveBeenCalledWith(expect.objectContaining({ method: 'tags.list', code: 'PERMISSION_DENIED' }));
});
it('meta with an unknown entityType is BAD_PARAMS', async () => {
const host = new PluginRpcHost('p', new Set(['db:meta']), deps);
const res = await host.dispatch(req('meta.set', { entityType: 'user', entityId: 1, key: 'x', value: 1 }), 42);
expect((res as RpcError).error.code).toBe('BAD_PARAMS');
it('RPCHOST-015 a throwing audit sink never breaks the call it was auditing', async () => {
const audit = vi.fn(() => {
throw new Error('audit table is gone');
});
const host = makeHost(['db:read:tags'], () => ({ done: true }), { ...makeDeps(), audit });
expect(ok(await host.dispatch(req('tags.list'), 42))).toBe(true);
});
it('meta writes resolve the entity edit permission per type (place→place_edit, day→day_edit) and refuse no-user', async () => {
const host = new PluginRpcHost('p', new Set(['db:meta']), deps);
expect(ok(await host.dispatch(req('meta.set', { entityType: 'place', entityId: 7, key: 'k', value: 1 }), 42))).toBe(true);
expect(deps.canEditPlaces).toHaveBeenCalled();
expect(ok(await host.dispatch(req('meta.set', { entityType: 'day', entityId: 3, key: 'k', value: 1 }), 42))).toBe(true);
expect(deps.canEditDays).toHaveBeenCalled();
// reservation metadata uses reservation_edit; accommodation uses day_edit
expect(ok(await host.dispatch(req('meta.set', { entityType: 'reservation', entityId: 40, key: 'ext_id', value: 'AB1' }), 42))).toBe(true);
expect(deps.canEditReservations).toHaveBeenCalled();
expect(ok(await host.dispatch(req('meta.set', { entityType: 'accommodation', entityId: 11, key: 'k', value: 1 }), 42))).toBe(true);
// an entity of another trip is refused
expect((await host.dispatch(req('meta.get', { entityType: 'reservation', entityId: 999, key: 'k' }), 42) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
// no host-bound acting user (a job / forged call) → refused
const noUser = await host.dispatch(req('meta.get', { entityType: 'trip', entityId: 1, key: 'k' }), undefined);
expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
it('RPCHOST-016 dispose() closes the plugin data db, and a second close is harmless', () => {
const deps = makeDeps();
const host = makeHost(['db:read:tags'], () => null, deps);
host.dispose();
expect(deps.data.close).toHaveBeenCalled();
(deps.data.close as ReturnType<typeof vi.fn>).mockImplementation(() => {
throw new Error('already closed');
});
expect(() => host.dispose()).not.toThrow();
});
// Regression (#getPlaces): the mocked `db.prepare` above never parses the SQL, so an
// invalid column sails through. Drive the trip reads against a REAL schema-loaded
// SQLite instead — `places` has no day_id/position (those live on day_assignments),
// so the old `ORDER BY day_id, position` threw `no such column` on every call.
it('meta WRITES need the entity edit permission — a read-only member is RESOURCE_FORBIDDEN', async () => {
// Member can access the trip but not edit it (viewer role).
(deps.canEditTrip as ReturnType<typeof vi.fn>).mockReturnValue(false);
const host = new PluginRpcHost('p', new Set(['db:meta']), deps);
const write = await host.dispatch(req('meta.set', { entityType: 'trip', entityId: 1, key: 'x', value: 1 }), 42);
expect((write as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
expect(deps.metaSet).not.toHaveBeenCalled();
// …but a READ is only access-gated, so it still works.
const read = await host.dispatch(req('meta.get', { entityType: 'trip', entityId: 1, key: 'x' }), 42);
expect(ok(read)).toBe(true);
expect(deps.metaGet).toHaveBeenCalled();
it('RPCHOST-017 a method the registry does not own is rejected, not silently answered', async () => {
// The registry is the ONLY source of handlers now, so a class that was never
// listed in its module makes every one of its methods PERMISSION_DENIED. This is
// the failure mode that has no other symptom, which is why each domain suite also
// asserts its class is in the module providers.
const bare = new PluginRpcHost('p', new Set(['db:read:tags']), makeDeps(), createTestPluginRegistry([]));
expect(code(await bare.dispatch(req('tags.list'), 42))).toBe('PERMISSION_DENIED');
});
});
@@ -45,14 +45,14 @@ function serviceFor(instances: object[]): PluginRpcRegistryService {
describe('PluginRpcRegistryService', () => {
it('RPCKIT-SVC-001 registers the marked providers at boot', () => {
const service = serviceFor([new TagsRpc(), new PlainProvider()]);
service.onModuleInit();
service.scanProviders();
expect(service.methodNames()).toEqual(new Set(['tags.list']));
});
it('RPCKIT-SVC-002 the same instance wrapped twice is registered once', () => {
const instance = new TagsRpc();
const service = serviceFor([instance, instance]);
service.onModuleInit();
service.scanProviders();
// Without the dedupe this would be two entries and validate() would report
// tags.list as double-owned.
expect(service.list()).toHaveLength(1);
@@ -60,7 +60,7 @@ describe('PluginRpcRegistryService', () => {
it('RPCKIT-SVC-003 unmarked providers are skipped rather than rejected', () => {
const service = serviceFor([new PlainProvider()]);
expect(() => service.onModuleInit()).not.toThrow();
expect(() => service.scanProviders()).not.toThrow();
expect(service.list()).toEqual([]);
});
@@ -70,7 +70,7 @@ describe('PluginRpcRegistryService', () => {
} as unknown as DiscoveryService;
const scanner = { getAllMethodNames: () => [] } as unknown as MetadataScanner;
const service = new PluginRpcRegistryService(discovery, scanner);
expect(() => service.onModuleInit()).not.toThrow();
expect(() => service.scanProviders()).not.toThrow();
expect(service.list()).toEqual([]);
});
@@ -81,9 +81,19 @@ describe('PluginRpcRegistryService', () => {
);
});
it('RPCKIT-SVC-006 total coverage is NOT required while the legacy router still owns methods', () => {
it('RPCKIT-SVC-006 boot fails when the surface is incomplete', () => {
// The rollout is finished, so a decorated class that no module registers is no
// longer a silent PERMISSION_DENIED at runtime: the app refuses to start, and the
// message names the method that lost its owner.
const service = serviceFor([new TagsRpc()]);
expect(() => service.onModuleInit()).not.toThrow();
expect(() => service.onModuleInit()).toThrow(/has no handler/);
});
it('RPCKIT-SVC-008 a hook nobody consumes fails boot too, so no grant is dead', () => {
// A hook:* permission on the consent screen with nothing behind it looks exactly
// like a live one to the user granting it.
const service = serviceFor([new TagsRpc()]);
expect(() => service.onModuleInit()).toThrow(/has no host-side consumer/);
});
it('RPCKIT-SVC-007 only providers are scanned, never controllers', () => {
@@ -93,7 +103,7 @@ describe('PluginRpcRegistryService', () => {
getControllers,
} as unknown as DiscoveryService;
const scanner = { getAllMethodNames: () => [] } as unknown as MetadataScanner;
new PluginRpcRegistryService(discovery, scanner).onModuleInit();
new PluginRpcRegistryService(discovery, scanner).scanProviders();
expect(getControllers).not.toHaveBeenCalled();
});
});
@@ -16,7 +16,7 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () =>
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { TripCardContributionsController } from '../../../src/nest/plugins/trip-card-contributions.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -24,8 +24,8 @@ const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) a
function controller(invoke: (id: string, args: unknown[]) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string, _h: string, _fn: string, args: unknown[]) => invoke(id, args)),
} as unknown as PluginRuntimeService;
tripCards: vi.fn(async (id: string, _h: string, _fn: string, args: unknown[]) => invoke(id, args)),
} as unknown as PluginHooks;
return { c: new TripCardContributionsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
}
const badge = (over: Record<string, unknown> = {}) => ({ tripId: 1, id: 'b1', label: 'Visa', ...over });
@@ -52,7 +52,7 @@ describe('TripCardContributionsController', () => {
it('passes only the accessible, deduped tripIds to the hook once', async () => {
const { c, runtime } = controller(() => [badge()]);
await c.get('1,2,2,99,abc', req(5)); // 99 inaccessible, abc invalid, 2 duplicated
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'tripCardProvider', 'getCards', [[1, 2]], 5, 5000);
expect(runtime.tripCards).toHaveBeenCalledWith('p1', [1, 2], 5);
});
it('drops a badge whose tripId was not requested / is inaccessible', async () => {
@@ -8,18 +8,18 @@ vi.mock('../../../src/db/database', () => ({ db: {}, canAccessTrip }));
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { TripWarningsController } from '../../../src/nest/plugins/trip-warnings.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) as any;
function controller(over: Partial<PluginRuntimeService> = {}) {
function controller(over: Partial<PluginHooks> = {}) {
const runtime = {
providersOf: vi.fn(() => ['p1', 'p2']),
invokeHook: vi.fn(async (id: string) =>
tripWarnings: vi.fn(async (id: string) =>
id === 'p2' ? [{ level: 'error', message: 'Day 3 is overpacked', dayId: 3 }] : [{ level: 'warning', message: 'Museum closed Mon', placeId: 7 }]),
...over,
} as unknown as PluginRuntimeService;
} as unknown as PluginHooks;
return { c: new TripWarningsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
}
@@ -37,8 +37,8 @@ describe('TripWarningsController', () => {
it('merges provider warnings, tags each with the plugin id, defaults an odd level to warning', async () => {
const { c } = controller({
invokeHook: vi.fn(async (id: string) =>
id === 'p1' ? [{ level: 'bogus', message: 'Check timings' }, { message: '' }] : [{ level: 'info', message: 'Rainy week' }]) as unknown as PluginRuntimeService['invokeHook'],
tripWarnings: vi.fn(async (id: string) =>
id === 'p1' ? [{ level: 'bogus', message: 'Check timings' }, { message: '' }] : [{ level: 'info', message: 'Rainy week' }]) as unknown as PluginHooks['tripWarnings'],
});
const res = await c.get('1', req(5));
expect(res.warnings).toEqual([
@@ -49,17 +49,17 @@ describe('TripWarningsController', () => {
it('skips a provider that throws (graceful) and calls the hook with the trip + acting user', async () => {
const { c, runtime } = controller({
invokeHook: vi.fn(async (id: string) => { if (id === 'p2') throw new Error('slow'); return [{ level: 'warning', message: 'ok' }]; }) as unknown as PluginRuntimeService['invokeHook'],
tripWarnings: vi.fn(async (id: string) => { if (id === 'p2') throw new Error('slow'); return [{ level: 'warning', message: 'ok' }]; }) as unknown as PluginHooks['tripWarnings'],
});
const res = await c.get('1', req(5));
expect(res.warnings).toEqual([{ pluginId: 'p1', level: 'warning', message: 'ok', dayId: undefined, placeId: undefined }]);
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'warningProvider', 'getWarnings', [1], 5, 5000);
expect(runtime.tripWarnings).toHaveBeenCalledWith('p1', 1, 5);
});
it('strips emojis from the warning message (rendered natively in TREK chrome)', async () => {
const { c } = controller({
providersOf: vi.fn(() => ['p1']),
invokeHook: vi.fn(async () => [{ level: 'error', message: '🔥 Overbooked!' }]) as unknown as PluginRuntimeService['invokeHook'],
tripWarnings: vi.fn(async () => [{ level: 'error', message: '🔥 Overbooked!' }]) as unknown as PluginHooks['tripWarnings'],
});
const res = await c.get('1', req(5));
expect(res.warnings[0].message).toBe('Overbooked!');
@@ -68,10 +68,10 @@ describe('TripWarningsController', () => {
it('caps a flooding provider at 20 warnings and truncates an oversized message', async () => {
const { c } = controller({
providersOf: vi.fn(() => ['flood']),
invokeHook: vi.fn(async () => [
tripWarnings: vi.fn(async () => [
{ level: 'warning', message: 'z'.repeat(1000) },
...Array.from({ length: 50 }, (_v, i) => ({ level: 'info', message: `w${i}` })),
]) as unknown as PluginRuntimeService['invokeHook'],
]) as unknown as PluginHooks['tripWarnings'],
});
const res = await c.get('1', req(5));
expect(res.warnings).toHaveLength(20); // per-provider count cap
@@ -15,7 +15,7 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: () => ({ get: () =>
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
import { ViewContributionsController } from '../../../src/nest/plugins/view-contributions.controller';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
import type { DatabaseService } from '../../../src/nest/database/database.service';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -23,8 +23,8 @@ const req = (id?: number) => ({ user: id === undefined ? undefined : { id } }) a
function controller(invoke: (id: string) => unknown, providers = ['p1']) {
const runtime = {
providersOf: vi.fn(() => providers),
invokeHook: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginRuntimeService;
tableContributions: vi.fn(async (id: string) => invoke(id)),
} as unknown as PluginHooks;
return { c: new ViewContributionsController(runtime, { canAccessTrip } as unknown as DatabaseService), runtime };
}
const col = (over: Record<string, unknown> = {}) => ({ kind: 'column', entityId: 1, id: 'c1', label: 'X', ...over });
@@ -115,6 +115,6 @@ describe('ViewContributionsController', () => {
const { c, runtime } = controller((id) => { if (id === 'p2') throw new Error('slow'); return [col({ id: 'from-p1' })]; }, ['p1', 'p2']);
const out = (await c.get('reservations', '1', req(5))).contributions;
expect(out.map((o) => o.id)).toEqual(['from-p1']);
expect(runtime.invokeHook).toHaveBeenCalledWith('p1', 'tableContributor', 'getContributions', ['reservations', 1], 5, 5000);
expect(runtime.tableContributions).toHaveBeenCalledWith('p1', 'reservations', 1, 5);
});
});