mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-21 22:46:32 +00:00
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:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user