Files
OmniRoute/src/lib/plugins/hooks.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

266 lines
7.2 KiB
TypeScript

/**
* Custom hook registry — event-driven plugin hook system.
*
* Plugins can register handlers for any OmniRoute event. Built-in events
* cover the full request lifecycle plus routing, rate limiting, and errors.
*
* @module plugins/hooks
*/
import { logger } from "../../../open-sse/utils/logger.ts";
const log = logger("PLUGIN_HOOKS");
// ── Types ──
export type BlockingHookResult = {
blocked?: boolean;
response?: unknown;
body?: unknown;
metadata?: Record<string, unknown>;
};
export type HookHandler = (
payload: unknown
) => void | Promise<void> | BlockingHookResult | Promise<BlockingHookResult>;
export interface HookRegistration {
pluginName: string;
handler: HookHandler;
priority: number;
}
// ── Built-in events ──
export const BUILTIN_EVENTS = [
"onRequest",
"onResponse",
"onError",
"onModelSelect",
"onComboResolve",
"onRateLimit",
"onQuotaExhaust",
"onProviderError",
"onStreamStart",
"onStreamEnd",
] as const;
export type BuiltinEvent = (typeof BUILTIN_EVENTS)[number];
// ── Registry ──
const hooks: Map<string, HookRegistration[]> = new Map();
/**
* Register a handler for an event.
*/
export function registerHook(
event: string,
pluginName: string,
handler: HookHandler,
priority: number = 100
): void {
if (!hooks.has(event)) {
hooks.set(event, []);
}
const list = hooks.get(event)!;
// Prevent duplicate registration
if (list.some((r) => r.pluginName === pluginName && r.handler === handler)) {
return;
}
list.push({ pluginName, handler, priority });
list.sort((a, b) => a.priority - b.priority);
log.info("hook.registered", { event, pluginName, priority });
}
/**
* Unregister all handlers for a plugin.
*/
export function unregisterHooks(pluginName: string): void {
for (const [event, list] of hooks.entries()) {
const before = list.length;
const filtered = list.filter((r) => r.pluginName !== pluginName);
if (filtered.length !== before) {
hooks.set(event, filtered);
log.info("hook.unregistered", { event, pluginName, removed: before - filtered.length });
}
}
}
/**
* Unregister a specific handler.
*/
export function unregisterHook(event: string, pluginName: string): void {
const list = hooks.get(event);
if (!list) return;
const before = list.length;
const filtered = list.filter((r) => r.pluginName !== pluginName);
hooks.set(event, filtered);
if (before !== filtered.length) {
log.info("hook.unregistered", { event, pluginName });
}
}
/**
* Emit an event — fire all registered handlers.
* Handler errors are logged but don't block other handlers.
*/
export async function emitHook(event: string, payload: unknown): Promise<void> {
const list = hooks.get(event);
if (!list || list.length === 0) return;
for (const reg of list) {
try {
await reg.handler(payload);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
log.error("hook.handler_error", {
event,
pluginName: reg.pluginName,
error: message,
});
}
}
}
/**
* Emit a blocking event — fire handlers with body/metadata chaining.
* Returns blocking result from the first handler that blocks, or merged body/metadata.
* Used for onRequest and onResponse where plugins can modify or block the request.
*/
export async function emitHookBlocking(
event: string,
payload: unknown
): Promise<{
blocked?: boolean;
response?: unknown;
body?: unknown;
metadata?: Record<string, unknown>;
}> {
const list = hooks.get(event) || [];
const ctx = (payload || {}) as Record<string, unknown>;
let mergedBody: unknown = ctx.body;
let mergedMetadata: Record<string, unknown> = (ctx.metadata as Record<string, unknown>) || {};
for (const reg of list) {
try {
const result = await reg.handler(payload);
if (result && typeof result === "object") {
if ("body" in result) mergedBody = (result as Record<string, unknown>).body;
if ("metadata" in result)
mergedMetadata = {
...mergedMetadata,
...(((result as Record<string, unknown>).metadata as Record<string, unknown>) || {}),
};
if ("blocked" in result && (result as BlockingHookResult).blocked) {
return {
...result,
body: (result as BlockingHookResult).body ?? mergedBody,
metadata: { ...mergedMetadata, ...((result as BlockingHookResult).metadata || {}) },
};
}
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
log.error("hook.blocking_handler_error", {
event,
pluginName: reg.pluginName,
error: message,
});
}
}
return { body: mergedBody, metadata: mergedMetadata };
}
// ── Lifecycle wrappers (for chatCore.ts convenience) ──
export interface PluginContext {
requestId: string;
body: unknown;
model: string;
provider: string;
apiKeyInfo?: unknown;
metadata: Record<string, unknown>;
}
export interface PluginResult {
blocked?: boolean;
response?: unknown;
body?: unknown;
metadata?: Record<string, unknown>;
}
// ── Plugin interface (for loader/manager compatibility) ──
export interface Plugin {
name: string;
priority?: number;
enabled?: boolean;
onRequest?: (ctx: PluginContext) => Promise<PluginResult | void> | PluginResult | void;
onResponse?: (ctx: PluginContext, response: unknown) => Promise<unknown | void> | unknown | void;
onError?: (ctx: PluginContext, error: Error) => Promise<unknown | void> | unknown | void;
}
/**
* Run onRequest hooks — blocking. Plugins can modify body/metadata or block with 403.
*/
export async function runOnRequest(ctx: PluginContext): Promise<PluginResult> {
return emitHookBlocking("onRequest", ctx);
}
/**
* Run onResponse hooks — chains response through plugins. Each plugin can modify the response.
*/
export async function runOnResponse(ctx: PluginContext, response: unknown): Promise<unknown> {
let currentResponse = response;
const list = hooks.get("onResponse") || [];
for (const reg of list) {
try {
const result = await reg.handler({ ...ctx, response: currentResponse });
if (
result !== undefined &&
result !== null &&
typeof result === "object" &&
"response" in result
) {
currentResponse = (result as { response: unknown }).response;
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
log.error("hook.response_handler_error", { pluginName: reg.pluginName, error: message });
}
}
return currentResponse;
}
/**
* Run onError hooks — fire-and-forget notification.
*/
export async function runOnError(ctx: PluginContext, error: Error): Promise<void> {
await emitHook("onError", { ...ctx, error });
}
/**
* Get all registered hooks for an event.
*/
export function getHooks(event: string): HookRegistration[] {
return hooks.get(event) ?? [];
}
/**
* Get all events that have registered handlers.
*/
export function getActiveEvents(): string[] {
return [...hooks.entries()].filter(([, list]) => list.length > 0).map(([event]) => event);
}
/**
* Reset all hooks (for testing).
*/
export function resetHooks(): void {
hooks.clear();
}