Spaces:
Runtime error
Runtime error
File size: 20,509 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | /**
* Plugin manager β lifecycle management for plugins.
*
* Singleton that coordinates scanner, loader, DB, and hook registry.
* Handles install, activate, deactivate, uninstall, scan, and startup loading.
*
* @module plugins/manager
*/
import { mkdir, cp, rm, rename, realpath, readFile } from "fs/promises";
import { join, dirname, resolve, sep } from "path";
import { randomUUID } from "crypto";
import { logger } from "../../../open-sse/utils/logger.ts";
import { getDefaultPluginDir, scanPluginDir } from "./scanner";
import { loadPlugin, type LoadedPlugin } from "./loader";
import { registerHook, unregisterHooks, emitHook, type HookHandler, type Plugin } from "./hooks";
import {
insertPlugin,
getPluginByName,
listPlugins as dbListPlugins,
updatePluginStatus,
updatePluginConfig,
deletePlugin as dbDeletePlugin,
pluginExists,
type PluginRow,
} from "../db/plugins";
import type { PluginManifestWithDefaults } from "./manifest";
const log = logger("PLUGIN_MANAGER");
type LifecycleHookName = Extract<
keyof Plugin,
| "onRequest"
| "onResponse"
| "onError"
| "onInstall"
| "onActivate"
| "onDeactivate"
| "onUninstall"
>;
/**
* Compare two semver strings. Returns positive if a > b, negative if a < b, 0 if equal.
* Only handles simple MAJOR.MINOR.PATCH β no pre-release tags.
*
* NaN-safe: strips a `-prerelease` suffix before parsing so a legacy DB value like
* `1.0.0-beta` doesn't produce NaN comparisons and silently compare equal to `1.0.0`.
* Non-numeric segments (after stripping) are coerced to 0.
*
* Exported for unit testing only β prefer pluginManager methods for production use.
*/
export function compareSemver(a: string, b: string): number {
// Strip optional pre-release suffix (e.g. "-beta", "-rc.1") before parsing
const stripPreRelease = (v: string) => v.replace(/-.*$/, "");
const parse = (v: string) =>
stripPreRelease(v)
.split(".")
.map((s) => {
const n = Number(s);
return Number.isNaN(n) ? 0 : n;
});
const [aMaj, aMin, aPat] = parse(a);
const [bMaj, bMin, bPat] = parse(b);
if (aMaj !== bMaj) return aMaj - bMaj;
if (aMin !== bMin) return aMin - bMin;
return aPat - bPat;
}
// ββ SECURITY: CRITICAL-2 ββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Assert that `target` is strictly contained within `pluginRoot`.
* Prevents a tampered/legacy DB `pluginDir` from causing deletion of an
* arbitrary filesystem path when passed to `rm({ recursive: true })`.
*
* Throws immediately if `target` resolves outside `pluginRoot`.
*/
function assertWithinPluginDir(pluginRoot: string, target: string): void {
const root = resolve(pluginRoot);
const t = resolve(target);
if (t !== root && !t.startsWith(root + sep)) {
throw new Error(
`Refusing to delete a path outside the plugin directory: "${t}" is not under "${root}"`
);
}
}
// ββ SECURITY: CRITICAL-3 (shared) ββββββββββββββββββββββββββββββββββββββββββ
/**
* Assert that `entryPoint` is strictly within `destDir`.
* Called at install/upgrade time to reject `manifest.main` values like
* `"../../evil.js"` before the plugin is ever persisted to DB.
*
* Throws if the resolved entryPoint escapes `destDir`.
*/
function assertEntryPointWithinDest(destDir: string, entryPoint: string): void {
const root = resolve(destDir);
const ep = resolve(entryPoint);
if (!ep.startsWith(root + sep)) {
throw new Error(
`Plugin manifest.main resolves outside plugin directory: "${ep}" escapes "${root}"`
);
}
}
class PluginManager {
private static instance: PluginManager;
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
private pluginDir: string;
private constructor() {
this.pluginDir = getDefaultPluginDir();
}
static getInstance(): PluginManager {
if (!PluginManager.instance) {
PluginManager.instance = new PluginManager();
}
return PluginManager.instance;
}
/**
* Install a plugin from a source directory.
* Copies to a staging dir first, validates manifest.main containment, then
* atomically renames into place. Cleans up staging dir on any failure.
*/
async install(sourceDir: string): Promise<PluginRow> {
// Check if sourceDir itself contains plugin.json (direct plugin dir)
const { safeValidateManifest } = await import("./manifest");
const { readFile: readFileFs } = await import("fs/promises");
let directPlugin: {
name: string;
manifest: any;
pluginDir: string;
entryPoint: string;
} | null = null;
try {
const manifestPath = join(sourceDir, "plugin.json");
const raw = await readFileFs(manifestPath, "utf-8");
const parsed = JSON.parse(raw);
const result = safeValidateManifest(parsed);
if (result.success) {
const entryPoint = join(sourceDir, result.data.main);
directPlugin = {
name: result.data.name,
manifest: result.data,
pluginDir: sourceDir,
entryPoint,
};
}
} catch {}
const { plugins, errors } = directPlugin
? { plugins: [directPlugin], errors: [] }
: await scanPluginDir(sourceDir);
if (plugins.length === 0) {
throw new Error(
`No valid plugin found in ${sourceDir}: ${errors.map((e) => e.error).join(", ")}`
);
}
const discovered = plugins[0];
const { name, manifest, pluginDir: srcDir } = discovered;
// If already installed, auto-upgrade when source is strictly newer; reject otherwise.
if (pluginExists(name)) {
const existing = getPluginByName(name)!;
if (compareSemver(manifest.version, existing.version) > 0) {
// Source is newer β delegate to upgrade()
return this.upgrade(sourceDir);
}
throw new Error(
`Plugin '${name}' is already installed (${existing.version}) and source version ${manifest.version} is not newer`
);
}
// CRITICAL-3: Copy to staging dir first, validate, then rename atomically.
const destDir = join(this.pluginDir, name);
const stagingDir = `${destDir}.staging-${randomUUID()}`;
await mkdir(dirname(destDir), { recursive: true });
// Reaching here means the plugin is not DB-registered (the pluginExists()
// guard above returns/throws otherwise). A destDir still present on disk is
// therefore orphaned (e.g. a crash mid-uninstall left files behind) and would
// make the atomic rename below fail with ENOTEMPTY β remove it first, guarded
// by path containment so we never rm outside the plugin directory.
assertWithinPluginDir(this.pluginDir, destDir);
await rm(destDir, { recursive: true, force: true }).catch(() => {});
await cp(srcDir, stagingDir, { recursive: true });
try {
// CRITICAL-3: Validate manifest.main is within the staging dir before persisting.
const entryPoint = join(stagingDir, manifest.main || "index.js");
assertEntryPointWithinDest(stagingDir, entryPoint);
// Atomic: rename staging β final dest
await rename(stagingDir, destDir);
} catch (err) {
// Cleanup staging dir so no half-installed directory is left behind.
await rm(stagingDir, { recursive: true, force: true }).catch(() => {});
throw err;
}
// Register in DB (destDir is now in place)
const row = insertPlugin({
id: randomUUID(),
name,
version: manifest.version,
description: manifest.description,
author: manifest.author,
license: manifest.license,
main: manifest.main,
source: manifest.source,
tags: manifest.tags,
manifest: manifest as unknown as Record<string, unknown>,
configSchema: manifest.configSchema as unknown as Record<string, unknown>,
hooks: [
manifest.hooks.onRequest && "onRequest",
manifest.hooks.onResponse && "onResponse",
manifest.hooks.onError && "onError",
manifest.hooks.onInstall && "onInstall",
manifest.hooks.onActivate && "onActivate",
manifest.hooks.onDeactivate && "onDeactivate",
manifest.hooks.onUninstall && "onUninstall",
].filter(Boolean) as string[],
permissions: manifest.requires.permissions,
pluginDir: destDir,
enabled: manifest.enabledByDefault,
});
log.info("manager.installed", { name, version: manifest.version });
// Fire onInstall lifecycle hook
if (manifest.hooks.onInstall) {
await emitHook("onInstall", { name, version: manifest.version, manifest });
}
// Auto-activate if enabledByDefault
if (manifest.enabledByDefault) {
await this.activate(name);
}
return row;
}
/**
* Upgrade an installed plugin to a newer version from sourceDir.
* Preserves nothing (clean reinstall); config is reset to defaults.
* Throws if the plugin is not installed or the source version is not strictly newer.
*
* Atomically: copy to staging β validate β rm old (containment-checked) β rename staging.
* On any failure after staging copy, staging is cleaned up and old install is left intact.
*/
async upgrade(sourceDir: string): Promise<PluginRow> {
// Scan source to get new manifest
const { safeValidateManifest } = await import("./manifest");
const { readFile: readFileFs } = await import("fs/promises");
let discovered: { name: string; manifest: any; pluginDir: string } | null = null;
// Try direct plugin dir first
try {
const manifestPath = join(sourceDir, "plugin.json");
const raw = await readFileFs(manifestPath, "utf-8");
const parsed = JSON.parse(raw);
const result = safeValidateManifest(parsed);
if (result.success) {
discovered = { name: result.data.name, manifest: result.data, pluginDir: sourceDir };
}
} catch {}
if (!discovered) {
const { plugins, errors } = await scanPluginDir(sourceDir);
if (plugins.length === 0) {
throw new Error(
`No valid plugin found in ${sourceDir}: ${errors.map((e) => e.error).join(", ")}`
);
}
discovered = plugins[0];
}
const { name, manifest } = discovered;
// Must be already installed
if (!pluginExists(name)) {
throw new Error(`Plugin '${name}' is not installed β use install() instead`);
}
const existing = getPluginByName(name)!;
// Source must be strictly newer
if (compareSemver(manifest.version, existing.version) <= 0) {
throw new Error(
`Plugin '${name}' upgrade rejected: source version ${manifest.version} is not newer than installed ${existing.version}`
);
}
log.info("manager.upgrading", { name, from: existing.version, to: manifest.version });
// Deactivate if active before touching files
if (existing.status === "active") {
await this.deactivate(name);
}
// CRITICAL-3: Copy to staging dir first, validate manifest.main, then swap atomically.
const destDir = join(this.pluginDir, name);
const stagingDir = `${destDir}.staging-${randomUUID()}`;
await mkdir(dirname(destDir), { recursive: true });
await cp(discovered.pluginDir, stagingDir, { recursive: true });
try {
// CRITICAL-3: Validate manifest.main is within staging before we destroy old version.
const entryPoint = join(stagingDir, manifest.main || "index.js");
assertEntryPointWithinDest(stagingDir, entryPoint);
// CRITICAL-2: Assert old install dir is within pluginDir before deleting it.
assertWithinPluginDir(this.pluginDir, existing.pluginDir);
// Only now remove old dir (after staging succeeded and was validated).
try {
await rm(existing.pluginDir, { recursive: true, force: true });
} catch (err: any) {
log.warn("manager.upgrade_dir_error", { name, error: err.message });
}
dbDeletePlugin(name);
// Atomic rename staging β final dest
await rename(stagingDir, destDir);
} catch (err) {
// Cleanup staging, leave old install intact.
await rm(stagingDir, { recursive: true, force: true }).catch(() => {});
throw err;
}
const row = insertPlugin({
id: randomUUID(),
name,
version: manifest.version,
description: manifest.description,
author: manifest.author,
license: manifest.license,
main: manifest.main,
source: manifest.source,
tags: manifest.tags,
manifest: manifest as unknown as Record<string, unknown>,
configSchema: manifest.configSchema as unknown as Record<string, unknown>,
hooks: [
manifest.hooks.onRequest && "onRequest",
manifest.hooks.onResponse && "onResponse",
manifest.hooks.onError && "onError",
manifest.hooks.onInstall && "onInstall",
manifest.hooks.onActivate && "onActivate",
manifest.hooks.onDeactivate && "onDeactivate",
manifest.hooks.onUninstall && "onUninstall",
].filter(Boolean) as string[],
permissions: manifest.requires.permissions,
pluginDir: destDir,
enabled: manifest.enabledByDefault,
});
log.info("manager.upgraded", { name, version: manifest.version });
if (manifest.enabledByDefault) {
await this.activate(name);
}
return row;
}
/**
* Activate a plugin β load into VM, register hooks, update DB.
*/
async activate(name: string): Promise<void> {
const row = getPluginByName(name);
if (!row) throw new Error(`Plugin '${name}' not found`);
if (row.status === "active") return;
const manifest = JSON.parse(row.manifest) as PluginManifestWithDefaults;
// Path traversal guard: use realpath to resolve symlinks
const entryPoint = join(row.pluginDir, manifest.main);
let resolvedPluginDir: string;
try {
resolvedPluginDir = await realpath(row.pluginDir);
} catch {
throw new Error(`Plugin directory '${row.pluginDir}' does not exist`);
}
const resolvedEntry = await realpath(entryPoint).catch(() => null);
if (
!resolvedEntry ||
(!resolvedEntry.startsWith(resolvedPluginDir + "/") && resolvedEntry !== resolvedPluginDir)
) {
throw new Error(`Plugin '${name}' entry point escapes plugin directory`);
}
try {
const loaded = await loadPlugin(entryPoint, manifest);
const hookNames: LifecycleHookName[] = [
"onRequest",
"onResponse",
"onError",
"onInstall",
"onActivate",
"onDeactivate",
"onUninstall",
];
for (const hookName of hookNames) {
const handler = loaded.plugin[hookName];
if (typeof handler === "function") {
registerHook(hookName, name, handler as HookHandler);
}
}
this.loadedPlugins.set(name, loaded);
updatePluginStatus(name, "active");
// Fire onActivate lifecycle hook
if (manifest.hooks.onActivate) {
await emitHook("onActivate", { name, version: manifest.version, manifest });
}
log.info("manager.activated", { name });
} catch (err: any) {
updatePluginStatus(name, "error", err.message);
log.error("manager.activate_failed", { name, error: err.message });
throw err;
}
}
/**
* Deactivate a plugin β fire onDeactivate, unregister hooks, update DB.
*
* IMPORTANT: onDeactivate MUST fire BEFORE unregisterHooks(name) so the
* plugin's own onDeactivate handler is still registered and can execute
* cleanup logic. See PR #3473 review finding.
*/
async deactivate(name: string): Promise<void> {
const row = getPluginByName(name);
const manifest = row ? (JSON.parse(row.manifest) as PluginManifestWithDefaults) : null;
// Fire onDeactivate lifecycle hook BEFORE unregistering β plugin's handlers
// are still registered at this point so its own onDeactivate can run.
if (manifest?.hooks.onDeactivate) {
await emitHook("onDeactivate", { name, version: manifest.version, manifest });
}
const loaded = this.loadedPlugins.get(name);
if (loaded) {
unregisterHooks(name);
loaded.cleanup();
this.loadedPlugins.delete(name);
}
updatePluginStatus(name, "inactive");
log.info("manager.deactivated", { name });
}
/**
* Uninstall a plugin β deactivate, delete directory (containment-checked), remove from DB.
*/
async uninstall(name: string): Promise<void> {
const row = getPluginByName(name);
if (!row) throw new Error(`Plugin '${name}' not found`);
const manifest = JSON.parse(row.manifest) as PluginManifestWithDefaults;
// Deactivate first if active
if (row.status === "active") {
await this.deactivate(name);
}
// Fire onUninstall lifecycle hook (before deleting files)
if (manifest.hooks.onUninstall) {
await emitHook("onUninstall", { name, version: manifest.version, manifest });
}
// CRITICAL-2: Assert the pluginDir from DB is within our managed pluginDir root
// before issuing a recursive delete. Prevents a tampered/legacy DB value from
// causing deletion of an arbitrary path on the filesystem.
assertWithinPluginDir(this.pluginDir, row.pluginDir);
// Delete plugin directory
try {
await rm(row.pluginDir, { recursive: true, force: true });
} catch (err: any) {
log.warn("manager.uninstall_dir_error", { name, error: err.message });
}
// Remove from DB
dbDeletePlugin(name);
log.info("manager.uninstalled", { name });
}
/**
* Scan plugin directory and sync with DB.
* Discovers new plugins and marks missing ones.
*/
async scan(): Promise<{ discovered: number; errors: Array<{ name: string; error: string }> }> {
const { plugins, errors } = await scanPluginDir(this.pluginDir);
// Register newly discovered plugins that aren't in DB
for (const discovered of plugins) {
if (!pluginExists(discovered.name)) {
try {
insertPlugin({
id: randomUUID(),
name: discovered.name,
version: discovered.manifest.version,
description: discovered.manifest.description,
author: discovered.manifest.author,
license: discovered.manifest.license,
main: discovered.manifest.main,
source: discovered.manifest.source,
tags: discovered.manifest.tags,
manifest: discovered.manifest as unknown as Record<string, unknown>,
configSchema: discovered.manifest.configSchema as unknown as Record<string, unknown>,
hooks: [
discovered.manifest.hooks.onRequest && "onRequest",
discovered.manifest.hooks.onResponse && "onResponse",
discovered.manifest.hooks.onError && "onError",
discovered.manifest.hooks.onInstall && "onInstall",
discovered.manifest.hooks.onActivate && "onActivate",
discovered.manifest.hooks.onDeactivate && "onDeactivate",
discovered.manifest.hooks.onUninstall && "onUninstall",
].filter(Boolean) as string[],
permissions: discovered.manifest.requires.permissions,
pluginDir: discovered.pluginDir,
enabled: discovered.manifest.enabledByDefault,
});
} catch (err: any) {
errors.push({ name: discovered.name, error: `DB insert failed: ${err.message}` });
}
}
}
return { discovered: plugins.length, errors };
}
/**
* Load all active plugins on startup.
*/
async loadAll(): Promise<void> {
const rows = dbListPlugins("active");
log.info("manager.loadAll", { count: rows.length });
for (const row of rows) {
try {
await this.activate(row.name);
} catch (err: any) {
log.error("manager.loadAll_failed", { name: row.name, error: err.message });
}
}
}
/**
* Get a loaded plugin by name.
*/
getLoaded(name: string): LoadedPlugin | undefined {
return this.loadedPlugins.get(name);
}
/**
* List all plugins from DB.
*/
listAll(): PluginRow[] {
return dbListPlugins();
}
/**
* Get plugin by name from DB.
*/
getPlugin(name: string): PluginRow | null {
return getPluginByName(name);
}
}
export const pluginManager = PluginManager.getInstance();
|