feat(plugins): lifecycle polish — uninstall, error log, egress guard, widget slot (M8)

- Uninstall with data disposition: POST /api/admin/plugins/:id/uninstall kills the
  plugin, removes its code + DB metadata, and (deleteData) drops its data dir,
  error log and per-user settings.
- Error log: GET/DELETE /api/admin/plugins/:id/errors — the plugin's own crash /
  request-failure log, surfaced in the admin panel.
- Egress guard: the isolated child wraps global fetch and refuses any outbound
  host not in the plugin's declared egress[]; with none declared, all outbound is
  blocked. Process-level defense in depth (the container runtime enforces it at
  the network layer in v2).
- Admin → Plugins is now actionable: activate / deactivate / uninstall, a
  registry browser (install), and per-plugin error log. i18n across all locales.
- Dashboard widget slot: active widget plugins render as sandboxed cards.

The trek:request core-data bridge + photo/calendar hook consumers remain follow-ups.
This commit is contained in:
mauriceboe
2026-07-03 18:08:11 +02:00
committed by Maurice
parent 660e4b9dfc
commit 1cee4e93b1
34 changed files with 719 additions and 29 deletions
@@ -3,9 +3,12 @@ import { db } from '../../db/database';
import { pluginsEnabled } from './kill-switch';
import { decrypt_api_key } from '../../services/apiKeyCrypto';
import { PluginSupervisor, type PluginRouteInfo } from './supervisor/plugin-supervisor';
import fs from 'node:fs';
import { createRealRpcHost, closePluginDataDb } from './host/create-rpc-host';
import { removePluginData } from './host/plugin-data.service';
import { isKnownPermission } from './protocol/envelope';
import { discoverPlugins } from './install/discovery';
import { pluginCodeDir } from './paths';
/**
* Owns the isolated-plugin runtime lifecycle inside NestJS (#plugins, M2).
@@ -78,7 +81,8 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
const declared = parseArray(row.permissions).filter(isKnownPermission);
db.prepare('UPDATE plugins SET granted_permissions = ? WHERE id = ?').run(JSON.stringify(declared), id);
const config = decryptConfig(parseObject(row.config));
await this.supervisor.activate(id, new Set(declared), config);
const egress = declared.filter((p) => p.startsWith('http:outbound:')).map((p) => p.slice('http:outbound:'.length));
await this.supervisor.activate(id, new Set(declared), config, egress);
}
async deactivate(id: string): Promise<void> {
@@ -87,6 +91,21 @@ export class PluginRuntimeService implements OnModuleInit, OnModuleDestroy {
db.prepare("UPDATE plugins SET status = 'inactive', updated_at = CURRENT_TIMESTAMP WHERE id = ?").run(id);
}
/** Stop the plugin, remove its code, and optionally delete all its data. */
async uninstall(id: string, deleteData: boolean): Promise<void> {
await this.supervisor.disable(id);
closePluginDataDb(id);
// Code always goes; the DB metadata + fields go so it disappears from the UI.
fs.rmSync(pluginCodeDir(id), { recursive: true, force: true });
db.prepare('DELETE FROM plugins WHERE id = ?').run(id);
db.prepare('DELETE FROM plugin_settings_fields WHERE plugin_id = ?').run(id);
if (deleteData) {
removePluginData(id);
db.prepare('DELETE FROM plugin_error_log WHERE plugin_id = ?').run(id);
db.prepare("DELETE FROM settings WHERE key LIKE ?").run(`plugin:${id}:%`);
}
}
isActive(id: string): boolean {
return this.supervisor.isActive(id);
}
+19 -1
View File
@@ -1,4 +1,4 @@
import { Body, Controller, Get, HttpCode, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common';
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common';
import { PluginsService } from './plugins.service';
import { PluginRuntimeService } from './plugin-runtime.service';
import { PluginRegistryService } from './registry/registry.service';
@@ -74,6 +74,24 @@ export class PluginsController {
return { status: 'inactive' };
}
@Post(':id/uninstall')
@HttpCode(200)
async uninstall(@Param('id') id: string, @Body() body: { deleteData?: boolean }) {
await this.runtime.uninstall(id, !!body?.deleteData);
return { status: 'uninstalled' };
}
@Get(':id/errors')
errors(@Param('id') id: string) {
return { errors: this.plugins.errors(id) };
}
@Delete(':id/errors')
clearErrors(@Param('id') id: string) {
this.plugins.clearErrors(id);
return { ok: true };
}
@Post('rescan')
@HttpCode(200)
rescan() {
@@ -67,6 +67,17 @@ export class PluginsService {
return maskSecrets(config, secretKeys);
}
/** A plugin's error log, newest first. */
errors(id: string): Array<{ ts: string; level: string; message: string }> {
return db
.prepare('SELECT ts, level, message FROM plugin_error_log WHERE plugin_id = ? ORDER BY ts DESC, id DESC LIMIT 200')
.all(id) as Array<{ ts: string; level: string; message: string }>;
}
clearErrors(id: string): void {
db.prepare('DELETE FROM plugin_error_log WHERE plugin_id = ?').run(id);
}
/** Read the instance config with secret fields masked. */
getInstanceConfig(id: string): Record<string, unknown> {
const row = db.prepare('SELECT config FROM plugins WHERE id = ?').get(id) as { config: string } | undefined;
@@ -125,11 +125,41 @@ process.on('message', (raw: unknown) => {
return;
}
if (msg.k === 'evt') {
if (msg.topic === 'init') void boot(((msg.data as { config?: Record<string, unknown> })?.config) ?? {});
else if (msg.topic === 'shutdown') void shutdown();
if (msg.topic === 'init') {
const d = msg.data as { config?: Record<string, unknown>; egress?: string[] };
installEgressGuard(d.egress ?? []);
void boot(d.config ?? {});
} else if (msg.topic === 'shutdown') void shutdown();
}
});
/**
* Restrict the plugin's outbound network to its declared egress hosts. With no
* declared egress, ALL outbound fetch is blocked. Wildcards like `*.host` match
* any subdomain. This is process-level defense in depth; the container runtime
* (v2) enforces it at the network layer.
*/
function installEgressGuard(egress: string[]): void {
const patterns = egress.map((h) => h.trim().toLowerCase()).filter(Boolean);
const allowed = (hostname: string): boolean => {
const h = hostname.toLowerCase();
return patterns.some((p) => (p.startsWith('*.') ? h === p.slice(2) || h.endsWith(p.slice(1)) : h === p));
};
const realFetch = globalThis.fetch;
if (typeof realFetch !== 'function') return;
globalThis.fetch = ((input: unknown, init?: unknown) => {
const url = typeof input === 'string' ? input : (input as { url?: string })?.url ?? String(input);
let host: string;
try {
host = new URL(url).hostname;
} catch {
return Promise.reject(new Error('egress: invalid url'));
}
if (!allowed(host)) return Promise.reject(new Error(`egress: ${host} is not in the plugin's declared hosts`));
return (realFetch as (i: unknown, n: unknown) => Promise<unknown>)(input, init);
}) as typeof fetch;
}
// Ask the host for the init payload (instance config), then wait for it.
send({ k: 'evt', topic: 'hello', data: {} });
@@ -39,6 +39,7 @@ interface Supervised {
id: string;
granted: ReadonlySet<string>;
config: Record<string, unknown>;
egress: string[];
rpcHost: PluginRpcHost;
child: ChildProcess | null;
status: PluginStatus;
@@ -80,12 +81,13 @@ export class PluginSupervisor {
}
/** Spawn a plugin and resolve once it reports `loaded` (or reject on load error). */
activate(id: string, granted: ReadonlySet<string>, config: Record<string, unknown> = {}): Promise<void> {
activate(id: string, granted: ReadonlySet<string>, config: Record<string, unknown> = {}, egress: string[] = []): Promise<void> {
if (this.running.has(id)) return Promise.resolve();
const sup: Supervised = {
id,
granted,
config,
egress,
rpcHost: this.createRpcHost(id, granted),
child: null,
status: 'starting',
@@ -201,7 +203,7 @@ export class PluginSupervisor {
if (msg.k === 'evt') {
switch (msg.topic) {
case 'hello':
sup.child?.send({ k: 'evt', topic: 'init', data: { config: sup.config } } satisfies Envelope);
sup.child?.send({ k: 'evt', topic: 'init', data: { config: sup.config, egress: sup.egress } } satisfies Envelope);
break;
case 'heartbeat':
sup.lastBeat = Date.now();
@@ -15,7 +15,8 @@ const { testDb } = vi.hoisted(() => {
id TEXT PRIMARY KEY, status TEXT, permissions TEXT DEFAULT '[]', granted_permissions TEXT DEFAULT '[]',
config TEXT DEFAULT '{}', last_error TEXT, updated_at TEXT);
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);`);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);`);
return { testDb: db };
});
vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined }));
@@ -150,6 +151,31 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
expect(rt.outboundHostsOf('missing')).toEqual([]);
});
it('uninstall removes the code, DB rows, settings and (with deleteData) data', async () => {
fs.mkdirSync(path.join(codeRoot, 'gone', 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, 'gone', 'server', 'index.js'), 'module.exports={}');
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('gone','inactive','[]','{}')").run();
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('gone','k','instance',0)").run();
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (1, 'plugin:gone:units', 'metric')").run();
await new PluginRuntimeService().uninstall('gone', true);
expect(fs.existsSync(path.join(codeRoot, 'gone'))).toBe(false);
expect(testDb.prepare("SELECT COUNT(*) c FROM plugins WHERE id='gone'").get()).toMatchObject({ c: 0 });
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_settings_fields WHERE plugin_id='gone'").get()).toMatchObject({ c: 0 });
expect(testDb.prepare("SELECT COUNT(*) c FROM settings WHERE key LIKE 'plugin:gone:%'").get()).toMatchObject({ c: 0 });
});
it('the egress guard blocks a fetch to an undeclared host', async () => {
fs.mkdirSync(path.join(codeRoot, 'nettry', 'server'), { recursive: true });
fs.writeFileSync(path.join(codeRoot, 'nettry', 'server', 'index.js'),
"module.exports = { async onLoad() { await fetch('https://blocked.example/x'); } };");
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('nettry','inactive','[]','{}')").run();
// no http:outbound granted -> egress guard blocks all outbound -> onLoad throws
await expect(new PluginRuntimeService().activate('nettry')).rejects.toThrow(/egress/);
await new PluginRuntimeService().deactivate('nettry').catch(() => {});
});
it('onModuleDestroy tears down cleanly', async () => {
await expect(new PluginRuntimeService().onModuleDestroy()).resolves.toBeUndefined();
});
@@ -11,7 +11,8 @@ const { testDb } = vi.hoisted(() => {
id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
status TEXT, reviewed_at TEXT, source_repo TEXT, config TEXT DEFAULT '{}', updated_at TEXT,
sort_order INTEGER DEFAULT 0);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);`);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);
CREATE TABLE plugin_error_log (id INTEGER PRIMARY KEY AUTOINCREMENT, plugin_id TEXT, level TEXT, message TEXT, ts TEXT DEFAULT '2026-01-01');`);
return { testDb: db };
});
vi.mock('../../../src/db/database', () => ({ db: testDb }));
@@ -144,3 +145,14 @@ describe('PluginsService instance config', () => {
expect(() => new PluginsService().getInstanceConfig('nope')).toThrow(/not found/);
});
});
describe('PluginsService error log', () => {
beforeEach(() => testDb.exec('DELETE FROM plugin_error_log'));
it('lists and clears a plugin error log', () => {
testDb.prepare("INSERT INTO plugin_error_log (plugin_id, level, message) VALUES ('p','error','boom')").run();
const svc = new PluginsService();
expect(svc.errors('p')).toEqual([{ ts: '2026-01-01', level: 'error', message: 'boom' }]);
svc.clearErrors('p');
expect(svc.errors('p')).toEqual([]);
});
});