Files
OmniRoute/src/lib/plugins/index.ts
Diego Rodrigues de Sa e Souza 191009dd23 Release v3.8.7 (#2919)
* feat(plugins): WordPress-style plugin system backend

* fix(plugins): address code review feedback

- Path traversal guard: validate entryPoint stays within plugin dir
- install() now handles direct plugin directories (not just parent dirs)
- Non-null assertion replaced with explicit null check
- require efficiency: allowedModules map moved outside function
- Source wrapper: add newlines to prevent trailing comment issues
- Config validation: validate values against configSchema on save
- Dynamic import comment: clarify Node.js caching behavior

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): replace vm with child_process, add auth to all routes

Addresses all remaining code review feedback:

1. **Loader rewrite**: Replaced Node.js vm module with child_process.fork()
   for proper process-level isolation. Complies with Rule 3 (no eval).
   Each plugin runs in a separate Node.js process with IPC communication.

2. **Auth on all routes**: Added requireManagementAuth to all 6 plugin
   API route files (list, install, scan, details, activate, deactivate, config).

3. **Env filtering**: Only safe env vars passed to plugin processes unless
   "env" permission is granted.

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): security + ESM fixes for loader and manager

loader.ts:
- Fix IPC: use process.send()/process.on("message") instead of worker_threads.parentPort
- Fix ESM: write host script as .mjs (not .js) to force ESM execution
- Add timeout: 10s default on callHook() with Promise.race
- Add SIGKILL escalation: SIGTERM first, then SIGKILL after 3s grace
- Fix env filtering: use allowlist (safeKeys) instead of passing all env vars
- Clear timeout on successful IPC response (no timer leak)

manager.ts:
- Fix path traversal: use fs.realpath() instead of startsWith()
- Fix imports: use registerHook/unregisterHooks from hooks.ts
- Register hooks individually via registerHook(event, name, handler)

hooks.ts:
- Copied from feat/plugin-custom-hooks (canonical registry)

* feat(discovery): add discovery tool stub service

Phase 1 scaffold for automated provider discovery:
- DiscoveryConfig, DiscoveryResult types
- probeEndpoint() for URL availability checking
- scanProvider() stub (Phase 2 will implement real scanning)
- getDiscoveryResults() stub
- Default config: disabled (opt-in)

* chore(plugins): slop cleanup — pino logger, remove redundant sorts

- index.ts: replace console.log/error with pino structured logging
- hooks.ts: remove redundant .sort() in emitHookBlocking/runOnResponse (already sorted on registration)
- manager.ts: add readFile import

* test(plugins): add scanner, loader, manager unit tests

- scanner: 9 tests (discovery, hidden dirs, validation, entry point, multiple)
- loader: 5 tests (type contracts, Plugin/PluginContext/PluginResult interfaces)
- manager: 6 tests (singleton, lifecycle methods, error on unknown)
- Total: 20 tests, all passing

* fix(settings): add missing home page pin keys to updateSettingsSchema

* feat(plugins): add i18n keys to all 42 locales

* fix(settings): add missing security keys to updateSettingsSchema and add tests

* fix(usage): analytics route reads combo_name/requested_model from call_logs only

The 3.8.6 variant of #2904 added SELECTs of combo_name/requested_model
against usage_history, but those columns only exist in call_logs (no
migration adds them to usage_history). This returned HTTP 500 on
/api/usage/analytics. Restore the working query shape from the 3.8.7
variant. Fixes 18 failing usage-analytics-route tests.

* fix(types,test): resolve noImplicitAny in progressiveAging + align semaphore test to #2903 gate pruning

- progressiveAging: type compression results so messages[0].content is
  indexable (was TS7053 against {}); restores typecheck:noimplicit:core gate.
- services-branch-hardening: #2903 (perf-ram) prunes idle rate-limit gates
  on zero; assert no-running/empty-queue without assuming the entry persists.

* fix(analytics): address merged review regressions

* fix(executor): normalize max effort for openai shape providers

* Make zero-latency combo optimizations opt-in

* Address zero-latency combo review feedback

* chore(release): sync v3.8.7 touchpoints + credit contributors

- llm.txt → 3.8.7 (Current version + Key Features header)
- CHANGELOG: add Dmitry Kuznetsov & Nikolay Alafuzov to 3.8.6 Hall of Contributors
- version already 3.8.7 across package.json/open-sse/electron/openapi (from #2909)

* fix(cleanup): restore usage history cutoff boundary

* docs(changelog): rank 3.8.6 contributors in a commits table with their PRs

* fix(dashboard): theme ReactFlow Controls +/- buttons for dark mode

* fix(settings): add missing home page pin keys to updateSettingsSchema

* fix(settings): add missing security keys to updateSettingsSchema and add tests

* fix(executor): normalize max effort for openai shape providers

* Make zero-latency combo optimizations opt-in

* Address zero-latency combo review feedback

* fix(analytics): address merged review regressions

* fix(cleanup): restore usage history cutoff boundary

* feat(plugins): WordPress-style plugin system backend

* fix(plugins): address code review feedback

- Path traversal guard: validate entryPoint stays within plugin dir
- install() now handles direct plugin directories (not just parent dirs)
- Non-null assertion replaced with explicit null check
- require efficiency: allowedModules map moved outside function
- Source wrapper: add newlines to prevent trailing comment issues
- Config validation: validate values against configSchema on save
- Dynamic import comment: clarify Node.js caching behavior

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): replace vm with child_process, add auth to all routes

Addresses all remaining code review feedback:

1. **Loader rewrite**: Replaced Node.js vm module with child_process.fork()
   for proper process-level isolation. Complies with Rule 3 (no eval).
   Each plugin runs in a separate Node.js process with IPC communication.

2. **Auth on all routes**: Added requireManagementAuth to all 6 plugin
   API route files (list, install, scan, details, activate, deactivate, config).

3. **Env filtering**: Only safe env vars passed to plugin processes unless
   "env" permission is granted.

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): security + ESM fixes for loader and manager

loader.ts:
- Fix IPC: use process.send()/process.on("message") instead of worker_threads.parentPort
- Fix ESM: write host script as .mjs (not .js) to force ESM execution
- Add timeout: 10s default on callHook() with Promise.race
- Add SIGKILL escalation: SIGTERM first, then SIGKILL after 3s grace
- Fix env filtering: use allowlist (safeKeys) instead of passing all env vars
- Clear timeout on successful IPC response (no timer leak)

manager.ts:
- Fix path traversal: use fs.realpath() instead of startsWith()
- Fix imports: use registerHook/unregisterHooks from hooks.ts
- Register hooks individually via registerHook(event, name, handler)

hooks.ts:
- Copied from feat/plugin-custom-hooks (canonical registry)

* feat(discovery): add discovery tool stub service

Phase 1 scaffold for automated provider discovery:
- DiscoveryConfig, DiscoveryResult types
- probeEndpoint() for URL availability checking
- scanProvider() stub (Phase 2 will implement real scanning)
- getDiscoveryResults() stub
- Default config: disabled (opt-in)

* chore(plugins): slop cleanup — pino logger, remove redundant sorts

- index.ts: replace console.log/error with pino structured logging
- hooks.ts: remove redundant .sort() in emitHookBlocking/runOnResponse (already sorted on registration)
- manager.ts: add readFile import

* test(plugins): add scanner, loader, manager unit tests

- scanner: 9 tests (discovery, hidden dirs, validation, entry point, multiple)
- loader: 5 tests (type contracts, Plugin/PluginContext/PluginResult interfaces)
- manager: 6 tests (singleton, lifecycle methods, error on unknown)
- Total: 20 tests, all passing

* feat(plugins): add i18n keys to all 42 locales

* chore(plugins): remove duplicate migration 059_create_plugins.sql

* chore(plugins): remove duplicate migration 059_create_plugins.sql (post-merge)

* fix(sse): guard non-string error.code in proxyFetch + harden model parsing (#2463) (#2923)

Integrated into release/v3.8.7

* fix(docker): add runner-web stage with Playwright Chromium (#2832) (#2846)

Integrated into release/v3.8.7

* docs(changelog): document NVIDIA NIM and error code type-crash fix (#2463)

* test: ignore NVIDIA_BASE_URL and NVIDIA_MODEL in env contract check

---------

Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>
Co-authored-by: Apostol Apostolov <theapoapostolov@gmail.com>
Co-authored-by: Halil Tezcan KARABULUT <info@hlltzcnkb.com>
Co-authored-by: R.D. <rogerproself@gmail.com>
2026-05-29 19:54:00 -03:00

224 lines
6.1 KiB
TypeScript

/**
* Plugin/Middleware Architecture — L-8
*
* Pre/post hooks on the request pipeline. Plugins are registered
* with a priority (lower = runs first) and can intercept requests
* before they reach the chat handler or modify responses after.
*
* Lifecycle:
* onRequest → runs BEFORE chat handler (can block/modify request)
* onResponse → runs AFTER chat handler (can modify/log response)
* onError → runs on handler errors (can recover or re-throw)
*
* @module lib/plugins
*/
// ── Types ──
import { logger } from "../../../open-sse/utils/logger.ts";
const log = logger("PLUGINS");
export interface PluginContext {
/** Unique request ID */
requestId: string;
/** Request body (parsed JSON) */
body: any;
/** Model string */
model: string;
/** Provider (if resolved) */
provider?: string;
/** API key info */
apiKeyInfo?: any;
/** Arbitrary metadata plugins can share */
metadata: Record<string, any>;
}
export interface PluginResult {
/** If true, stop processing further plugins and return immediately */
blocked?: boolean;
/** Optional response to return if blocked */
response?: any;
/** Modified body (if any) */
body?: any;
/** Modified metadata */
metadata?: Record<string, any>;
}
export interface Plugin {
/** Unique plugin name */
name: string;
/** Priority (lower = runs first, default 100) */
priority?: number;
/** Whether the plugin is enabled */
enabled?: boolean;
/** Called before the chat handler */
onRequest?: (ctx: PluginContext) => Promise<PluginResult | void> | PluginResult | void;
/** Called after the chat handler */
onResponse?: (ctx: PluginContext, response: any) => Promise<any | void> | any | void;
/** Called on handler error */
onError?: (ctx: PluginContext, error: Error) => Promise<any | void> | any | void;
}
// ── Registry ──
const _plugins: Plugin[] = [];
/**
* Register a plugin. Plugins are sorted by priority on each registration.
*/
export function registerPlugin(plugin: Plugin): void {
// Set defaults
plugin.priority = plugin.priority ?? 100;
plugin.enabled = plugin.enabled ?? true;
// Remove existing plugin with same name (re-registration)
const idx = _plugins.findIndex((p) => p.name === plugin.name);
if (idx !== -1) _plugins.splice(idx, 1);
_plugins.push(plugin);
_plugins.sort((a, b) => (a.priority || 100) - (b.priority || 100));
log.info("plugin.registered", {
name: plugin.name,
priority: plugin.priority,
enabled: plugin.enabled,
});
}
/**
* Unregister a plugin by name.
*/
export function unregisterPlugin(name: string): boolean {
const idx = _plugins.findIndex((p) => p.name === name);
if (idx === -1) return false;
_plugins.splice(idx, 1);
return true;
}
/**
* Enable/disable a plugin at runtime.
*/
export function setPluginEnabled(name: string, enabled: boolean): boolean {
const plugin = _plugins.find((p) => p.name === name);
if (!plugin) return false;
plugin.enabled = enabled;
return true;
}
/**
* List all registered plugins.
*/
export function listPlugins(): Array<{
name: string;
priority: number;
enabled: boolean;
hooks: string[];
}> {
return _plugins.map((p) => ({
name: p.name,
priority: p.priority || 100,
enabled: p.enabled !== false,
hooks: [
p.onRequest ? "onRequest" : "",
p.onResponse ? "onResponse" : "",
p.onError ? "onError" : "",
].filter(Boolean),
}));
}
// ── Execution ──
/**
* Run all onRequest hooks. Returns the (possibly modified) context,
* or a blocked response if any plugin blocked the request.
*/
export async function runOnRequest(
ctx: PluginContext
): Promise<{ blocked: boolean; response?: any; ctx: PluginContext }> {
let currentCtx = { ...ctx };
for (const plugin of _plugins) {
if (!plugin.enabled || !plugin.onRequest) continue;
try {
const result = await plugin.onRequest(currentCtx);
if (result) {
if (result.blocked) {
log.info("plugin.request_blocked", { name: plugin.name });
return { blocked: true, response: result.response, ctx: currentCtx };
}
if (result.body) currentCtx.body = result.body;
if (result.metadata) {
currentCtx.metadata = { ...currentCtx.metadata, ...result.metadata };
}
}
} catch (err: any) {
log.error("plugin.onRequest_error", {
name: plugin.name,
error: err instanceof Error ? err.message : String(err),
});
// Plugin errors don't block the pipeline by default
}
}
return { blocked: false, ctx: currentCtx };
}
/**
* Run all onResponse hooks. Returns the (possibly modified) response.
*/
export async function runOnResponse(ctx: PluginContext, response: any): Promise<any> {
let currentResponse = response;
for (const plugin of _plugins) {
if (!plugin.enabled || !plugin.onResponse) continue;
try {
const modified = await plugin.onResponse(ctx, currentResponse);
if (modified !== undefined && modified !== null) {
currentResponse = modified;
}
} catch (err: any) {
log.error("plugin.onResponse_error", {
name: plugin.name,
error: err instanceof Error ? err.message : String(err),
});
}
}
return currentResponse;
}
/**
* Run all onError hooks. Returns a recovery response if any plugin handles it,
* or null to let the error propagate.
*/
export async function runOnError(ctx: PluginContext, error: Error): Promise<any | null> {
for (const plugin of _plugins) {
if (!plugin.enabled || !plugin.onError) continue;
try {
const recovery = await plugin.onError(ctx, error);
if (recovery !== undefined && recovery !== null) {
log.info("plugin.error_recovered", { name: plugin.name });
return recovery;
}
} catch (err: any) {
log.error("plugin.onError_error", {
name: plugin.name,
error: err instanceof Error ? err.message : String(err),
});
}
}
return null; // No recovery — let error propagate
}
/**
* Reset all plugins (for testing).
*/
export function resetPlugins(): void {
_plugins.length = 0;
}