Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): harden lifecycle, boot validation, and install integrity (#942)
Yudhi Armyndharis95210c20ed1c
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 60587358b..2b7bd9bc9 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4324,7 +4324,9 @@ Install a plugin from an uploaded `.zip` package.#### POST /api/plugins/install-url-Install a plugin by downloading its `.zip` from an HTTP(S) URL (SSRF-guarded fetch: host validated, redirects refused, size-capped at `plugins.downloadMaxBytes`, default 5 MB).+Install a plugin by downloading its `.zip` from an HTTPS URL (SSRF-guarded fetch: host validated, redirects refused, size-capped at `plugins.downloadMaxBytes`, default 5 MB). Plain `http://` is rejected — the package is executable code and must be integrity-protected in transit; private-network targets remain subject to the SSRF guard.++Optional content pinning: append `#sha256=<64 hex>` (URL fragment — never sent to the server) or `?sha256=<64 hex>` (`checksum=` also accepted) to require the downloaded bytes to match that digest. A mismatch, a malformed marker, or conflicting markers fail the install closed; no marker means no verification (HTTPS + the SSRF guard are the baseline).**Auth:** API key (ADMIN)@@ -4332,7 +4334,7 @@ Install a plugin by downloading its `.zip` from an HTTP(S) URL (SSRF-guarded fet| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- |-| `url` | string | Yes | `@IsUrl({ protocols:['http','https'], require_protocol:true })` | Absolute http(s) URL of the package |+| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the package; optional `#sha256=` / `?sha256=` digest pin |```json{ "url": "https://github.com/openwa-plugins/chat-flow/releases/download/v1.0.0/chat-flow.zip" }@@ -4340,7 +4342,7 @@ Install a plugin by downloading its `.zip` from an HTTP(S) URL (SSRF-guarded fet**Response** `201` — the newly installed `PluginDto`.-**Errors:** `400` invalid URL / download or package invalid · `401` · `403` · `409` already installed+**Errors:** `400` invalid URL / download, integrity check, or package invalid · `401` · `403` · `409` already installed---@@ -4489,7 +4491,7 @@ A session-restricted key requesting `"*"` or out-of-scope sessions gets `403 API#### POST /api/plugins/:id/update-Update an installed plugin in place from a URL, preserving config + enabled state (old directory backed up and restored on failure).+Update an installed plugin in place from a URL, preserving config + enabled state. The new package is written to a staging sibling and validated BEFORE the running plugin is stopped, then swapped in with two renames (live → backup, staging → live); a failure before or during the swap restores the previous version, and a process crash mid-swap is reconciled at boot (the backup is restored when the live directory is missing), so an interrupted update can never make the plugin silently vanish. Accepts the same optional `#sha256=` / `?sha256=` digest pin as `install-url` (fail-closed on mismatch).**Auth:** API key (ADMIN)@@ -4503,7 +4505,7 @@ Update an installed plugin in place from a URL, preserving config + enabled stat| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- |-| `url` | string | Yes | `@IsUrl({ protocols:['http','https'], require_protocol:true })` | Absolute http(s) URL of the new `.zip` (SSRF-guarded download) |+| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the new `.zip` (SSRF-guarded download); optional `#sha256=` / `?sha256=` digest pin |```json{ "url": "https://example.com/plugins/chat-flow-1.1.0.zip" }@@ -4517,7 +4519,7 @@ Update an installed plugin in place from a URL, preserving config + enabled stat#### DELETE /api/plugins/:id-Uninstall a plugin and delete its files. Built-in plugins are protected.+Uninstall a plugin: dispatch its `onUnload` lifecycle hook, delete its files, drop its registry entry, and remove its `ctx.storage` data directory (`<dataDir>/plugins/<id>` — a separate tree when `PLUGINS_DIR` points outside the data dir). Built-in plugins are protected.**Auth:** API key (ADMIN)diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex f19e509ba..e18e0b207 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -486,8 +486,10 @@ double-enable, and engines must match the configured active engine):**Disable / unload / uninstall.** `disablePlugin` runs `onDisable` (force-terminating the worker for asandboxed plugin, even if `onDisable` hangs or throws) and unregisters the plugin's hooks. `onModuleDestroy`disables every enabled plugin on graceful shutdown so stateful plugins can flush. `uninstallPlugin`-disables + unloads, drops the registry entry, and deletes the plugin's directory (built-ins are-protected and cannot be uninstalled).+disables + unloads, drops the registry entry, and deletes the plugin's directory and its `ctx.storage`+data dir (built-ins are protected and cannot be uninstalled). The unload path dispatches `onUnload`:+for a sandboxed plugin it runs in the worker between `onDisable` and terminate (a plain disable does+NOT fire `onUnload` — disable is reversible and its cleanup hook is `onDisable`).**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger, plugin-scopedstorage, `registerHook` (wrapped with the per-session activation gate), the live `config` getter, and@@ -569,8 +571,8 @@ URL / catalog), not an npm/github source descriptor.| `GET /plugins/catalog` | List the remote plugin catalog, annotated with install state || `GET /plugins/:id` | Get a single plugin || `POST /plugins/install` | Install from an uploaded `.zip` (`multipart/form-data`, field `file`, ≤ 5 MB) |-| `POST /plugins/install-url` | Install by downloading a `.zip` from a URL (SSRF-guarded) |-| `POST /plugins/:id/update` | Update an installed plugin in place from a URL (preserves config + enabled state) |+| `POST /plugins/install-url` | Install by downloading a `.zip` from an https URL (SSRF-guarded; optional `#sha256=` digest pin) |+| `POST /plugins/:id/update` | Update an installed plugin in place from a URL (staged swap, crash-safe; preserves config + enabled state) || `POST /plugins/:id/enable` | Enable a plugin || `POST /plugins/:id/disable` | Disable a plugin || `PUT /plugins/:id/config` | Update the plugin's base config |diff --git a/openapi.json b/openapi.jsonindex e8956a471..079140c6b 100644--- a/openapi.json+++ b/openapi.json@@ -7718,7 +7718,7 @@"properties": {"url": {"type": "string",- "description": "HTTP(S) URL of the plugin .zip to download and install"+ "description": "HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is executable code, so it must be integrity-protected in transit (hosts on private networks remain subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never sent to the server) or `?sha256=<64 hex>` to require the downloaded archive to match that digest; a mismatch fails the install."}},"required": [diff --git a/src/core/plugins/index.ts b/src/core/plugins/index.tsindex cd17c7a1b..182b0765a 100644--- a/src/core/plugins/index.ts+++ b/src/core/plugins/index.ts@@ -1,4 +1,5 @@export * from './plugin.interfaces';+export * from './plugin-manifest';export * from './plugin-loader.service';export * from './plugin-storage.service';export * from './plugins.module';diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex 33bbf7e24..0eadd7a1a 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -827,7 +827,7 @@ describe('PluginLoaderService — search-provider enable-failure cleanup', () =>fs.mkdirSync(path.join(tmpDir, 'rt'), { recursive: true });fs.writeFileSync(path.join(tmpDir, 'rt', 'manifest.json'),- JSON.stringify({ id: 'rt', name: 'RT', version: '1.0.0', type: 'EXTENSION', main: 'index.cjs' }),+ JSON.stringify({ id: 'rt', name: 'RT', version: '1.0.0', type: 'extension', main: 'index.cjs' }),);// Fixture: register a search provider, THEN throw in onEnable — so the host has received// search-provider-register (and activated the provider in auto mode) before enable fails.@@ -909,7 +909,7 @@ describe('PluginLoaderService — search-provider worker-crash fallback', () =>fs.mkdirSync(path.join(tmpDir, 'ok'), { recursive: true });fs.writeFileSync(path.join(tmpDir, 'ok', 'manifest.json'),- JSON.stringify({ id: 'ok', name: 'OK', version: '1.0.0', type: 'EXTENSION', main: 'index.cjs' }),+ JSON.stringify({ id: 'ok', name: 'OK', version: '1.0.0', type: 'extension', main: 'index.cjs' }),);fs.writeFileSync(path.join(tmpDir, 'ok', 'index.cjs'),@@ -943,3 +943,309 @@ describe('PluginLoaderService — search-provider worker-crash fallback', () =>expect(registry.active()?.id).toBe('builtin-fts'); // fell back, not pinned to the dead plugin});});++describe('PluginLoaderService — boot-time manifest validation parity with install', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-bootval-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ const config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService;+ loader = new PluginLoaderService(+ config,+ new HookManager(),+ new PluginStorageService(config),+ {} as unknown as ModuleRef,+ );+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ const writePlugin = (id: string, manifest: unknown, withMain = true): string => {+ const dir = path.join(pluginsDir, id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'manifest.json'),+ typeof manifest === 'string' ? manifest : JSON.stringify(manifest),+ );+ if (withMain) fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');+ return dir;+ };+ const baseManifest = (id: string): Record<string, unknown> => ({+ id,+ name: id,+ version: '1.0.0',+ type: 'extension',+ main: 'index.js',+ });++ it('rejects the same invalid manifests install rejects (fields, id, reserved, type)', () => {+ // Missing a required field.+ const noName = baseManifest('no-name');+ delete noName.name;+ expect(() => loader.loadPlugin(writePlugin('no-name', noName))).toThrow(/required field: name/i);+ // A non-string required field (truthy — passed the old bare falsy check).+ expect(() => loader.loadPlugin(writePlugin('num-main', { ...baseManifest('num-main'), main: 123 }))).toThrow(+ /invalid required field/i,+ );+ // Unsafe id.+ expect(() => loader.loadPlugin(writePlugin('bad id', { ...baseManifest('bad id'), id: 'bad id' }))).toThrow(+ /invalid plugin id/i,+ );+ // Reserved built-in id (would shadow the baileys engine).+ expect(() => loader.loadPlugin(writePlugin('baileys', baseManifest('baileys')))).toThrow(/reserved/i);+ // A non-extension tier (engines are built-in, never directory-loadable).+ expect(() => loader.loadPlugin(writePlugin('my-eng', { ...baseManifest('my-eng'), type: 'engine' }))).toThrow(+ /not installable/i,+ );+ // A non-object manifest document.+ expect(() => loader.loadPlugin(writePlugin('arr-plg', '[]'))).toThrow(/must be a JSON object/i);+ });++ it('rejects a manifest whose main escapes the plugin directory', () => {+ const dir = writePlugin('trav-plg', { ...baseManifest('trav-plg'), main: '../other/evil.js' });+ expect(() => loader.loadPlugin(dir)).toThrow(/escapes the plugin directory/i);+ });++ it('rejects a manifest whose main file is missing from the directory', () => {+ const dir = writePlugin('gone-main', { ...baseManifest('gone-main'), main: 'gone.js' });+ expect(() => loader.loadPlugin(dir)).toThrow(/main file not found/i);+ });+});++describe('PluginLoaderService — interrupted-update recovery at boot', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-uprec-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ const config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService;+ loader = new PluginLoaderService(+ config,+ new HookManager(),+ new PluginStorageService(config),+ {} as unknown as ModuleRef,+ );+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ const writePluginTree = (dirName: string, id: string, version = '1.0.0'): void => {+ const dir = path.join(pluginsDir, dirName);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'manifest.json'),+ JSON.stringify({ id, name: id, version, type: 'extension', main: 'index.js' }),+ );+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');+ };++ it('restores the backup as the live dir when a crash mid-swap lost the live dir', () => {+ // Crash between `rename(live → backup)` and `rename(staging → live)`: the live dir is gone, the+ // backup holds the previous version, and staging never landed.+ writePluginTree('.svc-plg.bak', 'svc-plg');+ writePluginTree('.svc-plg.new', 'svc-plg', '2.0.0');++ loader.onModuleInit();++ // The previous version is back as the live dir and loads normally — the plugin no longer+ // silently vanishes while its registry entry still claims it is installed.+ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'))).toBe(true);+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);+ });++ it('drops a stale backup when the live dir exists (crash after the swap completed)', () => {+ writePluginTree('svc-plg', 'svc-plg', '2.0.0'); // the swapped-in new version+ writePluginTree('.svc-plg.bak', 'svc-plg'); // leftover backup of the old one++ loader.onModuleInit();++ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('2.0.0');+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);+ });++ it('drops a stale staging tree (crash before the swap ever started)', () => {+ writePluginTree('svc-plg', 'svc-plg');+ writePluginTree('.svc-plg.new', 'svc-plg', '2.0.0');++ loader.onModuleInit();++ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);+ });++ it('leaves an unrelated dot-prefixed directory alone', () => {+ writePluginTree('svc-plg', 'svc-plg');+ fs.mkdirSync(path.join(pluginsDir, '.gitkeep.d'), { recursive: true });++ loader.onModuleInit();++ expect(fs.existsSync(path.join(pluginsDir, '.gitkeep.d'))).toBe(true);+ expect(loader.getPlugin('svc-plg')).toBeDefined();+ });+});++describe('PluginLoaderService — onUnload dispatch', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;+ let storage: PluginStorageService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-onunload-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ const config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService;+ storage = new PluginStorageService(config);+ loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ const extManifest = (id: string): PluginManifest => ({+ id,+ name: id,+ version: '1.0.0',+ type: PluginType.EXTENSION,+ main: 'index.js',+ });++ it('runs an in-process plugin’s onUnload on the uninstall path (after onDisable)', async () => {+ const calls: string[] = [];+ const instance = {+ onDisable: () => {+ calls.push('onDisable');+ return Promise.resolve();+ },+ onUnload: () => {+ calls.push('onUnload');+ return Promise.resolve();+ },+ } as unknown as IPlugin;+ loader.registerBuiltInPlugin(extManifest('un-plg'), instance);+ // Built-ins can't be uninstalled, so drive the same unload path an uninstall takes.+ await loader.enablePlugin('un-plg');+ await loader.unloadPlugin('un-plg');++ expect(calls).toEqual(['onDisable', 'onUnload']);+ expect(loader.getPlugin('un-plg')).toBeUndefined();+ });++ it('does NOT fire onUnload on a plain disable (disable is reversible; its hook is onDisable)', async () => {+ const onUnload = jest.fn(() => Promise.resolve());+ loader.registerBuiltInPlugin(extManifest('no-unload-plg'), { onUnload });+ await loader.enablePlugin('no-unload-plg');++ await loader.disablePlugin('no-unload-plg');++ expect(onUnload).not.toHaveBeenCalled();+ expect(loader.getPlugin('no-unload-plg')?.status).toBe(PluginStatus.DISABLED);+ });++ it('dispatches onUnload to a sandboxed plugin’s worker before terminating it', async () => {+ loader.registerBuiltInPlugin(extManifest('sand-plg'), {});+ const plugin = loader.getPlugin('sand-plg')!;+ // Simulate a sandboxed runtime: non-built-in instance with a live worker host.+ plugin.builtIn = false;+ plugin.status = PluginStatus.ENABLED;+ const host = {+ runLifecycle: jest.fn().mockResolvedValue(undefined),+ terminate: jest.fn().mockResolvedValue(undefined),+ };+ (loader as unknown as { sandboxHosts: Map<string, typeof host> }).sandboxHosts.set('sand-plg', host);++ await loader.unloadPlugin('sand-plg');++ expect(host.runLifecycle.mock.calls.map((c: unknown[]) => c[0])).toEqual(['onDisable', 'onUnload']);+ expect(host.terminate).toHaveBeenCalledTimes(1);+ // onUnload must run BEFORE the worker is terminated — after terminate the hook is unreachable.+ const unloadOrder = host.runLifecycle.mock.invocationCallOrder[1];+ const terminateOrder = host.terminate.mock.invocationCallOrder[0];+ expect(unloadOrder).toBeLessThan(terminateOrder);+ });++ it('still terminates the worker when the sandboxed onUnload throws (best-effort teardown)', async () => {+ loader.registerBuiltInPlugin(extManifest('sand-bad'), {});+ const plugin = loader.getPlugin('sand-bad')!;+ plugin.builtIn = false;+ plugin.status = PluginStatus.ENABLED;+ const host = {+ runLifecycle: jest+ .fn()+ .mockImplementation((method: string) =>+ method === 'onUnload' ? Promise.reject(new Error('unload wedged')) : Promise.resolve(),+ ),+ terminate: jest.fn().mockResolvedValue(undefined),+ };+ (loader as unknown as { sandboxHosts: Map<string, typeof host> }).sandboxHosts.set('sand-bad', host);++ await expect(loader.unloadPlugin('sand-bad')).resolves.toBeUndefined();++ expect(host.terminate).toHaveBeenCalledTimes(1);+ expect(loader.getPlugin('sand-bad')).toBeUndefined();+ });+});++describe('PluginLoaderService — uninstall cleans up split-dir plugin storage', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let dataDir: string;+ let loader: PluginLoaderService;+ let storage: PluginStorageService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-splitstore-'));+ // Split-dir deployment: the package dir and the ctx.storage data dir are NOT the same tree.+ pluginsDir = path.join(tmpDir, 'plugins');+ dataDir = path.join(tmpDir, 'data');+ fs.mkdirSync(pluginsDir, { recursive: true });+ const config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? dataDir : undefined),+ } as unknown as ConfigService;+ storage = new PluginStorageService(config);+ loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ const writeUserPlugin = (id: string): string => {+ const dir = path.join(pluginsDir, id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'manifest.json'),+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),+ );+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');+ return dir;+ };++ it('removes the plugin’s storage dir on uninstall, and only that plugin’s', async () => {+ const dir = writeUserPlugin('user-plg');+ writeUserPlugin('other-plg');+ loader.loadPlugin(dir);+ loader.loadPlugin(path.join(pluginsDir, 'other-plg'));+ // Persist real ctx.storage state for both plugins (split-dir: under <dataDir>/plugins/<id>).+ await storage.createPluginStorage('user-plg').set('token', { secret: 'abc' });+ await storage.createPluginStorage('other-plg').set('token', { secret: 'xyz' });+ const userStorageDir = path.join(dataDir, 'plugins', 'user-plg');+ const otherStorageDir = path.join(dataDir, 'plugins', 'other-plg');+ expect(fs.existsSync(userStorageDir)).toBe(true);++ await loader.uninstallPlugin('user-plg');++ expect(fs.existsSync(dir)).toBe(false); // package dir (unchanged behavior)+ expect(fs.existsSync(userStorageDir)).toBe(false); // split-dir storage is now cleaned too+ expect(fs.existsSync(otherStorageDir)).toBe(true); // another plugin's storage is untouched+ expect(await storage.createPluginStorage('other-plg').get('token')).toEqual({ secret: 'xyz' });+ });+});diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex cc4757ee1..663dcb441 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -28,6 +28,7 @@ import {validateIngressManifest,warnUnauthenticatedIngressRoutes,} from './plugin.interfaces';+import { validatePluginManifest } from './plugin-manifest';import { effectiveNetAllow, isNetHostAllowed, performPluginFetch } from './plugin-net';import { PluginStorageService } from './plugin-storage.service';import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';@@ -91,6 +92,19 @@ export function resolvePluginMainPath(pluginsDir: string, pluginId: string, mainreturn mainPath;}+/**+ * Sibling directory names an in-place plugin update stages into / backs up to (see+ * PluginsService.updatePackageInner). Dot-prefixed so the boot directory scan skips them, and placed+ * inside the plugins dir so the swap renames stay on one filesystem (EXDEV-safe). The loader's+ * boot-time reconciler (recoverInterruptedUpdates) keys off these exact names.+ */+export function pluginUpdateStagingDirName(pluginId: string): string {+ return `.${pluginId}.new`;+}+export function pluginUpdateBackupDirName(pluginId: string): string {+ return `.${pluginId}.bak`;+}+/*** Build the minimal, allowlisted env for an untrusted plugin worker so it never inherits host secrets.* Only {@link SANDBOX_ENV_ALLOWLIST} keys are forwarded (unset keys are omitted, not emitted as@@ -271,11 +285,16 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap}private loadPluginsFromDirectory(dir: string): void {+ // Reconcile any interrupted-update leftovers BEFORE scanning, so a crash mid-swap can't make a+ // plugin silently vanish while its registry entry still claims it is installed.+ this.recoverInterruptedUpdates(dir);+const entries = fs.readdirSync(dir, { withFileTypes: true });for (const entry of entries) {- // Skip non-directories and dot-prefixed dirs (e.g. a crash-leftover `.<id>.bak` update backup),- // so a half-finished update can't be re-loaded as a duplicate-id plugin on the next boot.+ // Skip non-directories and dot-prefixed dirs (e.g. a crash-leftover `.<id>.bak` update backup or+ // `.<id>.new` staging tree), so a half-finished update can't be re-loaded as a duplicate-id+ // plugin on the next boot. recoverInterruptedUpdates has already reconciled them by this point.if (!entry.isDirectory() || entry.name.startsWith('.')) continue;const pluginPath = path.join(dir, entry.name);@@ -307,15 +326,81 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap}}+ /**+ * Crash recovery for in-place updates (see PluginsService.updatePackageInner). An update stages the+ * new tree at `.<id>.new`, then swaps with two renames (live → `.<id>.bak`, staging → live). Both+ * siblings are dot-prefixed, so the scan above skips them — but without reconciliation a crash+ * BETWEEN the renames loses the live dir and the plugin silently vanishes from the runtime while+ * its registry entry still claims it is installed. Reconcile before scanning:+ * - live dir missing + `.<id>.bak` present → the swap was interrupted: restore the backup as the+ * live dir (the previous version comes back; the update never touched the registry entry or the+ * operator's config, so nothing else needs repairing).+ * - live dir present + `.<id>.bak` present → the swap completed but the process died before the+ * backup cleanup: drop the backup.+ * - `.<id>.new` present → staging from an interrupted/failed update; the live install (if any)+ * was never swapped: drop it.+ * Best-effort: a reconciliation failure is logged and left for the next boot rather than aborting+ * plugin loading entirely.+ */+ private recoverInterruptedUpdates(dir: string): void {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const match = /^\.(.+)\.(?:bak|new)$/.exec(entry.name);+ if (!match) continue;+ const pluginId = match[1];+ const leftover = path.join(dir, entry.name);+ const liveDir = path.join(dir, pluginId);+ try {+ if (entry.name === pluginUpdateStagingDirName(pluginId)) {+ fs.rmSync(leftover, { recursive: true, force: true });+ this.logger.warn(`Dropped stale update staging for plugin ${pluginId}`, {+ pluginId,+ action: 'plugin_update_staging_pruned',+ });+ } else if (!fs.existsSync(liveDir)) {+ fs.renameSync(leftover, liveDir);+ this.logger.warn(+ `Restored plugin ${pluginId} from its update backup — a previous update was interrupted mid-swap`,+ { pluginId, action: 'plugin_update_backup_restored' },+ );+ } else {+ fs.rmSync(leftover, { recursive: true, force: true });+ this.logger.warn(`Dropped stale update backup for plugin ${pluginId}`, {+ pluginId,+ action: 'plugin_update_backup_pruned',+ });+ }+ } catch (error) {+ this.logger.error(+ `Failed to reconcile the interrupted-update leftover ${entry.name}`,+ error instanceof Error ? error.message : String(error),+ { pluginId, action: 'plugin_update_recovery_failed' },+ );+ }+ }+ }+loadPlugin(pluginPath: string): PluginInstance {const manifestPath = path.join(pluginPath, 'manifest.json');const manifestContent = fs.readFileSync(manifestPath, 'utf-8');- const manifest = JSON.parse(manifestContent) as PluginManifest;-- // Validate manifest- if (!manifest.id || !manifest.name || !manifest.version || !manifest.type || !manifest.main) {- throw new Error(`Invalid manifest: missing required fields`);+ const manifest = JSON.parse(manifestContent) as unknown;++ // Boot-time validation is the SAME validation install runs (parsePluginPackage): a hand-placed+ // or crash-leftover directory must satisfy the install contract too — plain-object shape,+ // required string fields, id format + reserved ids, extension-only type, and a `main` that+ // cannot escape the plugin dir. Otherwise a manifest the installer would have rejected loads+ // anyway and only fails (or worse, runs unexpected code) at enable time.+ validatePluginManifest(manifest);++ // Anchor `main` inside THIS on-disk directory: the lexical check above is forward-slash only,+ // so a platform-separator escape (e.g. Windows-style `..\x`) would slip past it — resolve and+ // re-check containment here. Parity with install's in-archive check: the entry must exist as a+ // file, or the plugin loads "successfully" and only blows up when someone enables it.+ const mainPath = resolvePluginMainPath(path.dirname(pluginPath), path.basename(pluginPath), manifest.main);+ if (!fs.existsSync(mainPath) || !fs.statSync(mainPath).isFile()) {+ throw new Error(`Plugin ${manifest.id}: main file not found in the plugin directory: ${manifest.main}`);}+// Reject a malformed ingress declaration (SDK-major mismatch, missing webhook:ingress permission,// duplicate/empty routes, non-positive toleranceSec) at load time instead of letting it silently// load and become provisionable. No-op for plugins that declare no ingress. A route declaring@@ -486,7 +571,15 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap}}- async disablePlugin(pluginId: string): Promise<void> {+ /**+ * Disable an enabled plugin (best-effort force-teardown for sandboxed ones). `opts.unload` is set+ * ONLY by the unload path (uninstall / in-place update): it additionally dispatches the plugin's+ * onUnload hook. A plain disable (REST / shutdown teardown) deliberately does NOT fire onUnload —+ * disable is reversible and its cleanup hook is onDisable, while onUnload means "removed from the+ * runtime". (For a sandboxed plugin the worker thread does die on disable, but terminate() itself+ * releases its timers/sockets; the hook contract stays: onUnload only on unload.)+ */+ async disablePlugin(pluginId: string, opts?: { unload?: boolean }): Promise<void> {const plugin = this.plugins.get(pluginId);if (!plugin) {throw new Error(`Plugin ${pluginId} not found`);@@ -511,6 +604,21 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstraperror: error instanceof Error ? error.message : String(error),});}+ if (opts?.unload) {+ // The worker is about to be terminated, so this is the ONLY chance onUnload ever gets for+ // a sandboxed plugin — after terminate the hook is unreachable, and unloadPlugin's+ // in-process call can't help (plugin.instance is null). Same bounded, best-effort policy+ // as onDisable above: a wedged/throwing onUnload must never block the teardown.+ try {+ await host.runLifecycle('onUnload', SANDBOX_LIFECYCLE_TIMEOUT_MS);+ } catch (error) {+ this.logger.warn(`Sandboxed plugin ${pluginId} onUnload failed during unload; terminating anyway`, {+ pluginId,+ action: 'sandbox_unload_lifecycle_failed',+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }await host.terminate().catch(() => undefined);this.sandboxHosts.delete(pluginId);} else {@@ -546,12 +654,16 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapthrow new Error(`Plugin ${pluginId} not found`);}- // Disable first if enabled+ // Disable first if enabled. `unload: true` so a SANDBOXED plugin also gets its onUnload hook:+ // disable terminates the worker thread, which would otherwise make onUnload unreachable. An+ // in-process plugin's onUnload runs below instead (its instance survives disable). A sandboxed+ // plugin that is already disabled has no live worker left to notify — its resources were+ // released when the worker terminated, so there is nothing to clean up.if (plugin.status === PluginStatus.ENABLED) {- await this.disablePlugin(pluginId);+ await this.disablePlugin(pluginId, { unload: true });}- // Call onUnload+ // Call onUnload (in-process plugins; a sandboxed one received it above, before terminate)if (plugin.instance?.onUnload) {const context = this.createPluginContext(plugin);await plugin.instance.onUnload(context);@@ -597,6 +709,12 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapfs.rmSync(dir, { recursive: true, force: true });}+ // Drop the plugin's ctx.storage data dir. Under shipped defaults it lives INSIDE the package+ // dir (already gone above), but a split-dir deployment (PLUGINS_DIR outside the data dir) would+ // otherwise leak <dataDir>/plugins/<id> — persisted secrets included — on every uninstall.+ // Best-effort, and strictly that one plugin's directory.+ this.pluginStorage.deletePluginData(pluginId);+this.logger.log(`Plugin uninstalled: ${pluginId}`, { pluginId, action: 'plugin_uninstalled' });}diff --git a/src/core/plugins/plugin-manifest.spec.ts b/src/core/plugins/plugin-manifest.spec.tsnew file mode 100644index 000000000..e42499207--- /dev/null+++ b/src/core/plugins/plugin-manifest.spec.ts@@ -0,0 +1,60 @@+import { validatePluginManifest, RESERVED_PLUGIN_IDS, INSTALLABLE_TYPES } from './plugin-manifest';++/**+ * The shared manifest contract enforced identically at install time (parsePluginPackage) and at+ * boot time (PluginLoaderService.loadPlugin): a plugin that could never be installed must never be+ * boot-loaded from a hand-placed directory either.+ */+describe('validatePluginManifest', () => {+ const valid = { id: 'my-plg', name: 'My Plugin', version: '1.0.0', type: 'extension', main: 'index.js' };++ it('accepts a valid manifest', () => {+ expect(() => validatePluginManifest({ ...valid })).not.toThrow();+ });++ it('rejects a non-object manifest (null / array / scalar)', () => {+ for (const body of [null, [], 'x', 5, true]) {+ expect(() => validatePluginManifest(body)).toThrow(/must be a JSON object/i);+ }+ });++ it('rejects a missing required field', () => {+ const bad = { ...valid, main: undefined } as unknown;+ expect(() => validatePluginManifest(bad)).toThrow(/required field: main/i);+ });++ it('rejects a non-string required field (numeric main)', () => {+ expect(() => validatePluginManifest({ ...valid, main: 123 })).toThrow(/invalid required field/i);+ });++ it('rejects an unsafe plugin id', () => {+ expect(() => validatePluginManifest({ ...valid, id: '../evil' })).toThrow(/invalid plugin id/i);+ expect(() => validatePluginManifest({ ...valid, id: 'has space' })).toThrow(/invalid plugin id/i);+ });++ it('rejects a reserved id, case-insensitively', () => {+ for (const id of RESERVED_PLUGIN_IDS) {+ expect(() => validatePluginManifest({ ...valid, id })).toThrow(/reserved/i);+ }+ expect(() => validatePluginManifest({ ...valid, id: 'Auto-Reply' })).toThrow(/reserved/i);+ });++ it('rejects a non-installable type (engines and unknown tiers alike)', () => {+ for (const type of ['engine', 'storage', 'wormhole']) {+ expect(() => validatePluginManifest({ ...valid, id: `plg-${type}`, type })).toThrow(/not installable/i);+ }+ expect(INSTALLABLE_TYPES.has('extension')).toBe(true);+ });++ it('rejects a main that escapes the plugin directory', () => {+ for (const main of ['../evil.js', '../../etc/passwd', '..', '/etc/passwd', 'a/../../b.js', '..\\evil.js']) {+ expect(() => validatePluginManifest({ ...valid, main })).toThrow(/escapes the plugin directory/i);+ }+ });++ it('accepts nested and dot-relative mains inside the plugin directory', () => {+ expect(() => validatePluginManifest({ ...valid, main: 'dist/main.js' })).not.toThrow();+ expect(() => validatePluginManifest({ ...valid, main: './index.js' })).not.toThrow();+ expect(() => validatePluginManifest({ ...valid, main: 'dist/../index.js' })).not.toThrow();+ });+});diff --git a/src/core/plugins/plugin-manifest.ts b/src/core/plugins/plugin-manifest.tsnew file mode 100644index 000000000..4c0ced519--- /dev/null+++ b/src/core/plugins/plugin-manifest.ts@@ -0,0 +1,72 @@+import * as path from 'path';+import { PluginManifest, PluginType } from './plugin.interfaces';++/**+ * Plugin ids a plugin package / directory must never use. `whatsapp-web.js` / `baileys` are built-in+ * engines; `auto-reply` / `translation` are the legacy bundled-extension ids (removed in v0.7 —+ * superseded by the marketplace `chat-flow` / `group-translate`) kept reserved so a re-upload or a+ * hand-placed directory can't shadow them.+ */+export const RESERVED_PLUGIN_IDS = new Set(['whatsapp-web.js', 'baileys', 'auto-reply', 'translation']);++/** Only extensions are user-installable / directory-loadable; engines (and other tiers) are built-in by design. */+export const INSTALLABLE_TYPES = new Set<string>([PluginType.EXTENSION]);++const SAFE_ID = /^[a-z0-9][a-z0-9._-]*$/i;+const REQUIRED_FIELDS = ['id', 'name', 'version', 'type', 'main'] as const;++/**+ * The manifest validation BOTH install-time (parsePluginPackage) and boot-time+ * (PluginLoaderService.loadPlugin) enforce, so a plugin that could never be installed can never be+ * boot-loaded from a hand-placed or crash-leftover directory either. Throws a plain Error with the+ * shared message; each caller maps it to its own surface (install → HTTP 400, boot → load failure+ * logged + the directory skipped).+ *+ * Checks: plain-object shape; required fields present as non-empty strings; id format + reserved+ * ids; installable (extension) type; and that `main` is a relative path that cannot escape the+ * plugin directory. The `main` check here is lexical (forward-slash semantics); the loader+ * additionally anchors it against the real on-disk directory, which also catches platform-separator+ * tricks, and requires the entry file to exist (parity with install's in-archive check).+ */+export function validatePluginManifest(manifest: unknown): asserts manifest is PluginManifest {+ // JSON.parse("null") / "[]" / "5" don't throw — but indexing a field on a non-object then throws a+ // TypeError downstream. Require a plain object up front.+ if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {+ throw new Error('manifest.json must be a JSON object');+ }+ const m = manifest as PluginManifest;+ for (const field of REQUIRED_FIELDS) {+ // Require a non-empty STRING: a non-string value (e.g. `main: 123`) is truthy and would pass a+ // bare falsy check, then crash a string-only API like path.posix.normalize with a TypeError.+ if (typeof m[field] !== 'string' || m[field].length === 0) {+ throw new Error(`manifest.json is missing or has an invalid required field: ${field}`);+ }+ }+ if (!SAFE_ID.test(m.id) || m.id.includes('..')) {+ throw new Error(`Invalid plugin id: "${m.id}"`);+ }+ // SAFE_ID accepts mixed case, so the reservation check is case-insensitive — else `Auto-Reply`+ // loads as a distinct plugin that shadows the reserved `auto-reply`.+ if (RESERVED_PLUGIN_IDS.has(m.id.toLowerCase())) {+ throw new Error(`Plugin id "${m.id}" is reserved by a built-in plugin`);+ }+ if (!INSTALLABLE_TYPES.has(m.type)) {+ throw new Error(+ `Plugin type "${m.type}" is not installable — only extension plugins can be installed (engines and other tiers are built-in).`,+ );+ }+ assertMainContained(m.main);+}++/**+ * Lexical containment for a manifest `main`: a relative, forward-slash path that stays inside the+ * plugin directory. Rejects absolute paths, `..` escapes, and backslashes (the install pipeline+ * rejects backslash archive paths outright, so a loadable main never contains one — a Windows-style+ * `..\x` would otherwise sail through the forward-slash checks and escape on a Windows host).+ */+function assertMainContained(main: string): void {+ const normalized = path.posix.normalize(main);+ if (path.posix.isAbsolute(main) || normalized === '..' || normalized.startsWith('../') || main.includes('\\')) {+ throw new Error(`manifest.json main escapes the plugin directory: "${main}"`);+ }+}diff --git a/src/core/plugins/plugin-restore-on-boot.spec.ts b/src/core/plugins/plugin-restore-on-boot.spec.tsindex 29c2c3826..147a1ad43 100644--- a/src/core/plugins/plugin-restore-on-boot.spec.ts+++ b/src/core/plugins/plugin-restore-on-boot.spec.ts@@ -41,11 +41,12 @@ describe('PluginLoaderService — restoring the operator enable decision acrossconfig = { get: (k: string) => (k === 'dataDir' ? tmpDir : undefined) } as unknown as ConfigService;storage = new PluginStorageService(config);loader = makeLoader(storage);- // A plugin on disk is only a manifest as far as loadPlugin is concerned — the code itself runs in- // the sandbox worker, so no module is required here.+ // A plugin on disk needs its manifest AND its declared main file to load (boot validates both,+ // like install); the code itself runs in the sandbox worker, so a stub main file suffices here.pluginDir = path.join(tmpDir, 'plugins', manifest.id);fs.mkdirSync(pluginDir, { recursive: true });fs.writeFileSync(path.join(pluginDir, 'manifest.json'), JSON.stringify(manifest));+ fs.writeFileSync(path.join(pluginDir, 'index.js'), 'module.exports = class {};');});afterEach(() => {@@ -123,6 +124,7 @@ describe('PluginLoaderService — restoring the operator enable decision acrossconst secondDir = path.join(tmpDir, 'plugins', second.id);fs.mkdirSync(secondDir, { recursive: true });fs.writeFileSync(path.join(secondDir, 'manifest.json'), JSON.stringify(second));+ fs.writeFileSync(path.join(secondDir, 'index.js'), 'module.exports = class {};');const storage2 = new PluginStorageService(config);const loader2 = makeLoader(storage2);diff --git a/src/core/plugins/plugin-storage.service.spec.ts b/src/core/plugins/plugin-storage.service.spec.tsindex c0788a1b2..88abac963 100644--- a/src/core/plugins/plugin-storage.service.spec.ts+++ b/src/core/plugins/plugin-storage.service.spec.ts@@ -159,3 +159,46 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>await expect(storage.delete('../../escape')).rejects.toThrow();});});++describe('PluginStorageService.deletePluginData (uninstall storage cleanup)', () => {+ let dataDir: string;+ let service: PluginStorageService;++ beforeEach(() => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-plugindata-rm-'));+ const configService = {+ get: (k: string) => (k === 'dataDir' ? dataDir : undefined),+ } as unknown as ConfigService;+ service = new PluginStorageService(configService);+ });++ afterEach(() => {+ fs.rmSync(dataDir, { recursive: true, force: true });+ });++ it('removes the named plugin’s storage dir, leaving other plugins untouched', async () => {+ await service.createPluginStorage('gone-plg').set('token', { secret: 'abc' });+ await service.createPluginStorage('keep-plg').set('token', { secret: 'xyz' });++ service.deletePluginData('gone-plg');++ expect(fs.existsSync(path.join(dataDir, 'plugins', 'gone-plg'))).toBe(false);+ expect(fs.existsSync(path.join(dataDir, 'plugins', 'keep-plg'))).toBe(true);+ expect(await service.createPluginStorage('keep-plg').get('token')).toEqual({ secret: 'xyz' });+ });++ it('is a no-op for a plugin with no storage dir', () => {+ expect(() => service.deletePluginData('never-stored')).not.toThrow();+ });++ it('refuses a traversal id that resolves outside the storage root', () => {+ // A real directory the escaping id would resolve to — it must survive the call.+ const outside = path.join(dataDir, 'not-plugin-storage');+ fs.mkdirSync(outside, { recursive: true });+ fs.writeFileSync(path.join(outside, 'keep.txt'), 'keep');++ service.deletePluginData('../not-plugin-storage');++ expect(fs.existsSync(path.join(outside, 'keep.txt'))).toBe(true);+ });+});diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.tsindex 7b63d5e07..24b8805b7 100644--- a/src/core/plugins/plugin-storage.service.ts+++ b/src/core/plugins/plugin-storage.service.ts@@ -212,6 +212,34 @@ export class PluginStorageService {// Plugin Data Storage (sandboxed per-plugin storage)// ============================================================================+ /**+ * Remove a plugin's entire data-storage directory (<dataDir>/plugins/<id>). Called on uninstall.+ * Containment-guarded exactly like the package-dir delete in the loader: an id that resolves+ * outside the storage root is refused, so only the named plugin's directory can ever be touched.+ * Best-effort — a removal failure is logged, never thrown, so the uninstall still completes.+ */+ deletePluginData(pluginId: string): void {+ const root = path.resolve(this.dataDir, 'plugins');+ const dir = path.resolve(root, pluginId);+ if (dir === root || !dir.startsWith(root + path.sep)) {+ this.logger.warn(`Refusing to delete plugin storage outside the storage root: ${pluginId}`, {+ pluginId,+ action: 'plugin_storage_delete_refused',+ });+ return;+ }+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ this.logger.debug(`Deleted plugin storage: ${pluginId}`, { pluginId, action: 'plugin_storage_deleted' });+ } catch (error) {+ this.logger.warn(`Failed to delete plugin storage for ${pluginId}`, {+ pluginId,+ action: 'plugin_storage_delete_failed',+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+createPluginStorage(pluginId: string): PluginStorage {const pluginDataDir = path.join(this.dataDir, 'plugins', pluginId);diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.tsindex 2ec225921..6d1d97563 100644--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts@@ -14,6 +14,7 @@ const CTX_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-aware-plugin.cconst HOOK_CONFIG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-config-plugin.cjs');const CTX_LIFECYCLE_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-lifecycle-plugin.cjs');const SEARCH_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/search-plugin.cjs');+const UNLOAD_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/unload-plugin.cjs');const flushAsync = (): Promise<void> => new Promise(resolve => setImmediate(resolve));// Run the TS bootstrap inside the worker via ts-node. The base tsconfig is nodenext; we pin the@@ -49,6 +50,20 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {await host.terminate();});+ it('dispatches onUnload to the plugin inside the worker (the hook the loader fires on uninstall)', async () => {+ const host = makeHost();+ await host.load(UNLOAD_FIXTURE);+ await host.runLifecycle('onEnable');+ await expect(host.healthCheck(3000)).resolves.toMatchObject({ message: 'loaded' });++ await host.runLifecycle('onUnload');++ // The worker-side instance observed its onUnload — before this hook was dispatched on the+ // unload path, a sandboxed plugin's cleanup (timers, connections) never ran.+ await expect(host.healthCheck(3000)).resolves.toMatchObject({ message: 'unloaded' });+ await host.terminate();+ });+it('rejects load() when the plugin module cannot be required', async () => {const host = makeHost();await expect(host.load(path.resolve(ROOT, 'test/fixtures/sandbox/missing.cjs'))).rejects.toThrow();diff --git a/src/modules/plugins/dto/plugin.dto.spec.ts b/src/modules/plugins/dto/plugin.dto.spec.tsnew file mode 100644index 000000000..f7461c46c--- /dev/null+++ b/src/modules/plugins/dto/plugin.dto.spec.ts@@ -0,0 +1,48 @@+import 'reflect-metadata';+import { validate } from 'class-validator';+import { InstallFromUrlDto } from './plugin.dto';++/**+ * The install/update-from-URL boundary: plugin packages are executable code, so the download must+ * be integrity-protected in transit. Plain http:// is rejected with a clear message; https:// —+ * including an optional `#sha256=` integrity fragment — passes DTO validation (private-network+ * targets remain subject to the SSRF guard downstream).+ */+describe('InstallFromUrlDto', () => {+ const dtoWith = (url: string): InstallFromUrlDto => {+ const dto = new InstallFromUrlDto();+ dto.url = url;+ return dto;+ };++ it('rejects a plain http:// URL with a clear message', async () => {+ const errors = await validate(dtoWith('http://plugins.example/pkg.zip'));++ expect(errors).toHaveLength(1);+ expect(errors[0].property).toBe('url');+ expect(JSON.stringify(errors[0].constraints)).toMatch(/https:\/\/ URL.*plain http is not accepted/i);+ });++ it('rejects http:// even for a localhost/private host (no scheme carve-out)', async () => {+ const errors = await validate(dtoWith('http://localhost:3000/pkg.zip'));++ expect(errors).toHaveLength(1);+ expect(errors[0].property).toBe('url');+ });++ it('accepts an https:// URL', async () => {+ await expect(validate(dtoWith('https://plugins.example/pkg.zip'))).resolves.toHaveLength(0);+ });++ it('accepts an https:// URL carrying a #sha256 integrity fragment', async () => {+ const digest = 'a'.repeat(64);+ await expect(validate(dtoWith(`https://plugins.example/pkg.zip#sha256=${digest}`))).resolves.toHaveLength(0);+ });++ it('rejects a non-URL value', async () => {+ const errors = await validate(dtoWith('not-a-url'));++ expect(errors).toHaveLength(1);+ expect(errors[0].property).toBe('url');+ });+});diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.tsindex 1261e06ac..107f67e74 100644--- a/src/modules/plugins/dto/plugin.dto.ts+++ b/src/modules/plugins/dto/plugin.dto.ts@@ -83,8 +83,18 @@ export class PluginSessionsDto {}export class InstallFromUrlDto {- @ApiProperty({ description: 'HTTP(S) URL of the plugin .zip to download and install' })+ @ApiProperty({+ description:+ 'HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is ' ++ 'executable code, so it must be integrity-protected in transit (hosts on private networks remain ' ++ 'subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never ' ++ 'sent to the server) or `?sha256=<64 hex>` to require the downloaded archive to match that digest; ' ++ 'a mismatch fails the install.',+ })@IsString()- @IsUrl({ protocols: ['http', 'https'], require_protocol: true })+ @IsUrl(+ { protocols: ['https'], require_protocol: true },+ { message: 'url must be an https:// URL — plain http is not accepted for plugin downloads' },+ )url!: string;}diff --git a/src/modules/plugins/plugin-download.spec.ts b/src/modules/plugins/plugin-download.spec.tsnew file mode 100644index 000000000..3a78ef40e--- /dev/null+++ b/src/modules/plugins/plugin-download.spec.ts@@ -0,0 +1,55 @@+import { expectedSha256FromUrl, assertDownloadSha256 } from './plugin-download';+import { createHash } from 'crypto';++/**+ * Optional content integrity for plugin downloads: the expected sha256 travels IN the URL+ * (`#sha256=` fragment — never sent to the server — or a `?sha256=`/`?checksum=` query param), and+ * verification is fail-closed whenever a marker is present.+ */+describe('expectedSha256FromUrl', () => {+ const digest = 'a'.repeat(64);++ it('extracts the digest from a #sha256= fragment (case-insensitive hex)', () => {+ expect(expectedSha256FromUrl(`https://h/pkg.zip#sha256=${digest}`)).toBe(digest);+ expect(expectedSha256FromUrl(`https://h/pkg.zip#sha256=${digest.toUpperCase()}`)).toBe(digest);+ });++ it('extracts the digest from ?sha256= / ?checksum= query params', () => {+ expect(expectedSha256FromUrl(`https://h/pkg.zip?sha256=${digest}`)).toBe(digest);+ expect(expectedSha256FromUrl(`https://h/pkg.zip?checksum=${digest}`)).toBe(digest);+ });++ it('returns null when the URL carries no integrity marker', () => {+ expect(expectedSha256FromUrl('https://h/pkg.zip')).toBeNull();+ expect(expectedSha256FromUrl('https://h/pkg.zip#download')).toBeNull();+ expect(expectedSha256FromUrl('not a url')).toBeNull(); // downstream URL validation rejects it+ });++ it('fails closed on a malformed marker', () => {+ expect(() => expectedSha256FromUrl('https://h/pkg.zip#sha256=xyz')).toThrow(/64-character hex/i);+ expect(() => expectedSha256FromUrl(`https://h/pkg.zip?sha256=${'a'.repeat(63)}`)).toThrow(/64-character hex/i);+ });++ it('fails closed when fragment and query disagree', () => {+ expect(() => expectedSha256FromUrl(`https://h/pkg.zip?sha256=${digest}#sha256=${'b'.repeat(64)}`)).toThrow(+ /conflicting/i,+ );+ });+});++describe('assertDownloadSha256', () => {+ const body = Buffer.from('plugin zip bytes');+ const digest = createHash('sha256').update(body).digest('hex');++ it('is a no-op when the URL carries no integrity marker', () => {+ expect(() => assertDownloadSha256('https://h/pkg.zip', body)).not.toThrow();+ });++ it('passes when the digest matches the downloaded bytes', () => {+ expect(() => assertDownloadSha256(`https://h/pkg.zip#sha256=${digest}`, body)).not.toThrow();+ });++ it('throws when the digest does not match (substituted package)', () => {+ expect(() => assertDownloadSha256(`https://h/pkg.zip#sha256=${'0'.repeat(64)}`, body)).toThrow(/sha256 mismatch/i);+ });+});diff --git a/src/modules/plugins/plugin-download.ts b/src/modules/plugins/plugin-download.tsindex 152a14d06..0c46e6481 100644--- a/src/modules/plugins/plugin-download.ts+++ b/src/modules/plugins/plugin-download.ts@@ -1,3 +1,4 @@+import { createHash } from 'crypto';import { withSafeFetch } from '../../common/security/ssrf-guard';/** Default cap on a server-side plugin download: 5 MiB (matches the upload limit). */@@ -5,6 +6,60 @@ const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;/** Default timeout for a server-side plugin download: 30s. */const DEFAULT_TIMEOUT_MS = 30_000;+const SHA256_HEX = /^[0-9a-f]{64}$/i;++/**+ * Optional content integrity for a plugin download, carried IN the URL so it works over any+ * transport (a catalog `download` link, a dashboard paste, a raw API call):+ * - URL fragment: https://host/pkg.zip#sha256=<64 hex> — never sent to the server+ * - query param: https://host/pkg.zip?sha256=<64 hex> — `checksum=` is accepted too+ * Returns the lowercase expected digest, or null when the URL carries no integrity marker.+ *+ * Throws when a marker is present but malformed (not 64 hex chars) or when fragment and query+ * disagree: the caller explicitly asked for integrity, so an unusable marker fails closed rather+ * than silently degrading to no verification.+ */+export function expectedSha256FromUrl(url: string): string | null {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return null; // not a parseable URL — the SSRF guard / fetch rejects it downstream+ }+ const markers: string[] = [];+ if (parsed.hash.startsWith('#sha256=')) {+ markers.push(parsed.hash.slice('#sha256='.length));+ }+ for (const key of ['sha256', 'checksum']) {+ const value = parsed.searchParams.get(key);+ if (value !== null) markers.push(value);+ }+ if (markers.length === 0) return null;+ const digests = markers.map(marker => marker.trim().toLowerCase());+ if (digests.some(digest => !SHA256_HEX.test(digest))) {+ throw new Error('the URL carries a sha256 integrity marker that is not a 64-character hex digest');+ }+ if (new Set(digests).size > 1) {+ throw new Error('the URL carries conflicting sha256 integrity markers');+ }+ return digests[0];+}++/**+ * Fail-closed sha256 verification of a downloaded plugin package. No-op when the URL carries no+ * integrity marker (HTTPS + the SSRF guard remain the baseline); otherwise the digest of the+ * downloaded bytes MUST equal the expected one — a mismatch means the bytes were substituted in+ * transit (or the marker is stale), and the caller must not install them.+ */+export function assertDownloadSha256(url: string, body: Buffer): void {+ const expected = expectedSha256FromUrl(url);+ if (expected === null) return;+ const actual = createHash('sha256').update(body).digest('hex');+ if (actual !== expected) {+ throw new Error(`sha256 mismatch for the downloaded package (expected ${expected}, got ${actual})`);+ }+}+/*** Fetch a remote resource (plugin .zip or catalog JSON) as a Buffer, always behind the SSRF guard:* every host (the original URL and every redirect hop) is validated before its socket opens and a hopdiff --git a/src/modules/plugins/plugin-installer.spec.ts b/src/modules/plugins/plugin-installer.spec.tsindex 72569f0ed..95a2261ce 100644--- a/src/modules/plugins/plugin-installer.spec.ts+++ b/src/modules/plugins/plugin-installer.spec.ts@@ -171,6 +171,18 @@ describe('parsePluginPackage', () => {expect(() => parsePluginPackage(buf)).toThrow(/missing its main file/i);});+ it('rejects a manifest whose main escapes the plugin directory', () => {+ // Previously only caught indirectly ("missing its main file", since an escaping main can never+ // match an in-archive entry). The shared manifest validator now rejects it explicitly — the same+ // message the boot-time loader enforces on a hand-placed directory.+ for (const main of ['../evil.js', '../../etc/passwd', '/etc/passwd', '..\\evil.js']) {+ const bad = { ...validManifest, main };+ expect(() => parsePluginPackage(zipOf({ 'manifest.json': JSON.stringify(bad), 'index.js': 'x' }))).toThrow(+ /escapes the plugin directory/i,+ );+ }+ });+it('rejects too many files', () => {const files: Record<string, string> = { 'manifest.json': JSON.stringify(validManifest), 'index.js': 'x' };for (let i = 0; i < 5; i++) files[`f${i}.txt`] = 'x';diff --git a/src/modules/plugins/plugin-installer.ts b/src/modules/plugins/plugin-installer.tsindex 7716a8a85..96115aa13 100644--- a/src/modules/plugins/plugin-installer.ts+++ b/src/modules/plugins/plugin-installer.ts@@ -2,7 +2,11 @@ import AdmZip from 'adm-zip';import * as path from 'path';import * as zlib from 'zlib';import { BadRequestException } from '@nestjs/common';-import { PluginManifest, PluginType } from '../../core/plugins';+import { PluginManifest, RESERVED_PLUGIN_IDS, INSTALLABLE_TYPES, validatePluginManifest } from '../../core/plugins';++// Re-exported so existing importers of this module keep working; the definitions live in+// core/plugins/plugin-manifest.ts, shared with the boot-time loader validation.+export { RESERVED_PLUGIN_IDS, INSTALLABLE_TYPES };export interface PackageLimits {/** Max number of files in the archive (cheap zip-bomb / fork-bomb guard). */@@ -13,19 +17,6 @@ export interface PackageLimits {export const DEFAULT_PACKAGE_LIMITS: PackageLimits = { maxEntries: 200, maxTotalBytes: 20 * 1024 * 1024 };-/**- * Plugin ids an uploaded package must never use. `whatsapp-web.js` / `baileys` are built-in engines;- * `auto-reply` / `translation` are the legacy bundled-extension ids (removed in v0.7 — superseded by- * the marketplace `chat-flow` / `group-translate`) kept reserved so a re-upload can't shadow them.- */-export const RESERVED_PLUGIN_IDS = new Set(['whatsapp-web.js', 'baileys', 'auto-reply', 'translation']);--/** Only extensions are user-installable; engines (and other tiers) are built-in by design. */-export const INSTALLABLE_TYPES = new Set<string>([PluginType.EXTENSION]);--const SAFE_ID = /^[a-z0-9][a-z0-9._-]*$/i;-const REQUIRED_FIELDS = ['id', 'name', 'version', 'type', 'main'] as const;-/*** Decompress one zip entry with a hard cap on actual output bytes. adm-zip only forwards zlib* `maxOutputLength` when the entry's declared uncompressed size is positive, so an entry that lies@@ -91,31 +82,16 @@ export function parsePluginPackage(buffer: Buffer, limits: PackageLimits = DEFAU} catch {throw new BadRequestException('manifest.json is not valid JSON');}- // JSON.parse("null") / "[]" / "5" don't throw — but indexing a field on a non-object then throws an- // uncaught TypeError (HTTP 500) on the attacker-controlled install path. Require a plain object.- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {- throw new BadRequestException('manifest.json must be a JSON object');- }- const manifest = parsed as PluginManifest;- for (const field of REQUIRED_FIELDS) {- // Require a non-empty STRING: a non-string value (e.g. `main: 123`) is truthy and would pass a- // bare falsy check, then crash a string-only API like path.posix.normalize with an uncaught- // TypeError (HTTP 500). Reject it cleanly as a 400 here.- if (typeof manifest[field] !== 'string' || manifest[field].length === 0) {- throw new BadRequestException(`manifest.json is missing or has an invalid required field: ${field}`);- }- }- if (!SAFE_ID.test(manifest.id) || manifest.id.includes('..')) {- throw new BadRequestException(`Invalid plugin id: "${manifest.id}"`);- }- if (RESERVED_PLUGIN_IDS.has(manifest.id.toLowerCase())) {- throw new BadRequestException(`Plugin id "${manifest.id}" is reserved by a built-in plugin`);- }- if (!INSTALLABLE_TYPES.has(manifest.type)) {- throw new BadRequestException(- `Plugin type "${manifest.type}" is not installable — only extension plugins can be installed (engines and other tiers are built-in).`,- );+ // The SAME manifest validation the boot-time loader enforces (shape, required string fields, id+ // format + reserved ids, extension-only type, contained `main`) — shared so the two entry points+ // can never drift apart. Mapped to a clean 400 here, never an uncaught TypeError (HTTP 500) on+ // the attacker-controlled install path.+ try {+ validatePluginManifest(parsed);+ } catch (error) {+ throw new BadRequestException(error instanceof Error ? error.message : String(error));}+ const manifest = parsed;// Size guard FIRST, off the declared header sizes, so a zip bomb is rejected before we decompress.const packaged = files.filter(e => !prefix || e.entryName.startsWith(prefix));diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex f5379bec8..a94042566 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -1,11 +1,24 @@+// Spread the real fs so every method passes through, but as configurable props the test can spy on+// (the bare `import * as fs` namespace is non-configurable, so jest.spyOn can't redefine its methods).+jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('fs')>('fs') }));++// fetchSafeBuffer stays REAL by default (the SSRF redaction test below depends on it); individual+// integrity tests queue a one-shot resolved download instead of hitting the network.+jest.mock('./plugin-download', () => {+ const actual = jest.requireActual<typeof import('./plugin-download')>('./plugin-download');+ return { ...actual, fetchSafeBuffer: jest.fn(actual.fetchSafeBuffer) };+});+import * as fs from 'fs';import * as os from 'os';import * as path from 'path';+import { createHash } from 'crypto';import AdmZip from 'adm-zip';import { BadRequestException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { PluginsService, isIngressCapable } from './plugins.service';+import { fetchSafeBuffer } from './plugin-download';import { SECRET_SENTINEL } from './redact-config';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { PluginStorageService } from '../../core/plugins/plugin-storage.service';@@ -137,6 +150,63 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {enableSpy.mockRestore();});+ it('cleans up the staging + backup dirs after a successful update (swap happened)', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });++ const dto = await service.updatePackage('svc-plg', pkg({ version: '2.0.0' }));++ expect(dto.version).toBe('2.0.0');+ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('2.0.0');+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);+ });++ it('keeps the old install fully intact when the update fails BEFORE the swap (staging)', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });+ // A package whose entries collide as file-then-directory makes the staging WRITE fail:+ // 'index.js' lands as a file, then 'index.js/extra.js' needs it to be a directory.+ const z = new AdmZip();+ z.addFile('manifest.json', Buffer.from(JSON.stringify({ ...manifest, version: '2.0.0' })));+ z.addFile('index.js', Buffer.from('module.exports = class {};'));+ z.addFile('index.js/extra.js', Buffer.from('module.exports = class {};'));++ await expect(service.updatePackage('svc-plg', z.toBuffer())).rejects.toThrow(/Failed to stage/i);++ // The old version never stopped being the install: still loaded, still on disk, no leftovers.+ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');+ const onDisk = JSON.parse(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'), 'utf8')) as {+ version: string;+ };+ expect(onDisk.version).toBe('1.0.0');+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);+ });++ it('restores the previous version when the swap itself fails mid-way', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });++ // Let the first swap rename (live → backup) through, then fail the second (staging → live).+ const realRename = fs.renameSync;+ const spy = jest.spyOn(fs, 'renameSync').mockImplementation((a: fs.PathLike, b: fs.PathLike) => {+ if (String(a).endsWith('.new')) throw new Error('simulated swap failure');+ return realRename(a, b);+ });++ await expect(service.updatePackage('svc-plg', pkg({ version: '2.0.0' }))).rejects.toThrow(+ /Failed to update plugin/i,+ );+ spy.mockRestore();++ // The failed swap must leave the OLD version loadable: backup restored on disk and reloaded.+ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');+ const onDisk = JSON.parse(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'), 'utf8')) as {+ version: string;+ };+ expect(onDisk.version).toBe('1.0.0');+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);+ });+it('serializes concurrent lifecycle operations on the same plugin id', async () => {service.install({ buffer: pkg() });let resolveFirst: () => void = () => undefined;@@ -172,6 +242,108 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {});});+describe('PluginsService — download integrity (optional #sha256 pinning)', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;+ let service: PluginsService;+ const fetchMock = fetchSafeBuffer as unknown as jest.Mock;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-dl-integrity-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ const config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService;+ loader = new PluginLoaderService(+ config,+ new HookManager(),+ new PluginStorageService(config),+ {} as unknown as ModuleRef,+ );+ service = new PluginsService(loader, config);+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ /** Queue a one-shot offline download; the mock then falls back to the real (SSRF-guarded) implementation. */+ const serveOnce = (buffer: Buffer): void => {+ fetchMock.mockImplementationOnce(() => Promise.resolve(buffer));+ };+ const sha256 = (buffer: Buffer): string => createHash('sha256').update(buffer).digest('hex');++ it('installs when the #sha256 fragment matches the downloaded bytes', async () => {+ const buf = pkg();+ serveOnce(buf);++ const dto = await service.installFromUrl(`https://plugins.example/svc-plg.zip#sha256=${sha256(buf)}`);++ expect(dto.id).toBe('svc-plg');+ expect(loader.getPlugin('svc-plg')).toBeDefined();+ });++ it('also accepts the digest as a ?sha256= query parameter', async () => {+ const buf = pkg();+ serveOnce(buf);++ const dto = await service.installFromUrl(`https://plugins.example/svc-plg.zip?sha256=${sha256(buf)}`);++ expect(dto.id).toBe('svc-plg');+ });++ it('fails closed when the pinned digest does not match (package substituted in transit)', async () => {+ serveOnce(pkg());+ const wrong = '0'.repeat(64);++ await expect(service.installFromUrl(`https://plugins.example/svc-plg.zip#sha256=${wrong}`)).rejects.toThrow(+ /integrity check failed/i,+ );++ // Nothing was installed from the substituted bytes.+ expect(loader.getPlugin('svc-plg')).toBeUndefined();+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg'))).toBe(false);+ });++ it('rejects a malformed integrity marker instead of silently skipping verification', async () => {+ serveOnce(pkg());++ await expect(service.installFromUrl('https://plugins.example/svc-plg.zip#sha256=not-hex')).rejects.toThrow(+ /integrity check failed/i,+ );+ expect(loader.getPlugin('svc-plg')).toBeUndefined();+ });++ it('rejects conflicting markers (fragment vs query disagree)', async () => {+ const buf = pkg();+ serveOnce(buf);+ const other = '1'.repeat(64);++ await expect(+ service.installFromUrl(`https://plugins.example/svc-plg.zip?sha256=${sha256(buf)}#sha256=${other}`),+ ).rejects.toThrow(/integrity check failed/i);+ });++ it('installs without a marker (HTTPS + the SSRF guard remain the baseline)', async () => {+ serveOnce(pkg());++ const dto = await service.installFromUrl('https://plugins.example/svc-plg.zip');++ expect(dto.id).toBe('svc-plg');+ });++ it('updateFromUrl fails closed on a mismatch and leaves the old version intact', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });+ serveOnce(pkg({ version: '2.0.0' }));+ const wrong = '0'.repeat(64);++ await expect(+ service.updateFromUrl('svc-plg', `https://plugins.example/svc-plg.zip#sha256=${wrong}`),+ ).rejects.toThrow(/integrity check failed/i);++ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');+ });+});+describe('PluginsService — getConfigUiHtml (sandboxed config editor)', () => {let tmpDir: string;let pluginsDir: string;diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 84ccb4a67..3006aac44 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -10,11 +10,12 @@ import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';import { PluginLoaderService, PluginStatus, resolvePluginMainPath } from '../../core/plugins';+import { pluginUpdateBackupDirName, pluginUpdateStagingDirName } from '../../core/plugins';import type { PluginConfigSchema } from '../../core/plugins';import { PluginDto } from './dto/plugin.dto';import { redactSecretConfig, restoreSecretConfig } from './redact-config';import { parsePluginPackage } from './plugin-installer';-import { fetchSafeBuffer } from './plugin-download';+import { assertDownloadSha256, fetchSafeBuffer } from './plugin-download';import { annotateCatalog, CatalogEntry, CatalogPlugin } from './catalog';import { redactSsrfError } from '../../common/security/ssrf-guard';import { createLogger } from '../../common/services/logger.service';@@ -340,9 +341,12 @@ export class PluginsService {}/**- * Install a plugin from an HTTP(S) URL: download the .zip through the SSRF guard (host validated,+ * Install a plugin from an HTTPS URL: download the .zip through the SSRF guard (host validated,* connection pinned, redirects refused, size-capped), then run the exact same validate-write-load- * pipeline as an uploaded package. The downloaded buffer is treated as untrusted, identical to an upload.+ * pipeline as an uploaded package. The downloaded buffer is treated as untrusted, identical to an+ * upload. When the URL pins a digest (`#sha256=<hex>` fragment or `?sha256=` query — see+ * plugin-download.ts), the bytes MUST match it: a mismatch means the package was substituted in+ * transit and the install fails closed.*/async installFromUrl(url: string): Promise<PluginDto> {const maxBytes = this.configService.get<number>('plugins.downloadMaxBytes') ?? 5 * 1024 * 1024;@@ -354,6 +358,13 @@ export class PluginsService {`Failed to download plugin from URL: ${redactSsrfError(error, logger, 'plugin download')}`,);}+ try {+ assertDownloadSha256(url, buffer);+ } catch (error) {+ throw new BadRequestException(+ `Plugin download integrity check failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }// Peek the id (the SSRF download stays outside the lock) so the install — which writes the plugin// directory — is serialized against any concurrent uninstall/update of the same id.const { manifest } = parsePluginPackage(buffer);@@ -395,8 +406,14 @@ export class PluginsService {/*** Update an installed plugin in place from a validated package buffer, preserving operator config and* the enabled state. The package id must match the installed id. Config survives because `unloadPlugin`- * drops the plugin from memory but keeps its registry entry (config); `loadPlugin` re-reads it. The old- * directory is backed up and restored if the swap or reload of the new version fails, so a bad update+ * drops the plugin from memory but keeps its registry entry (config); `loadPlugin` re-reads it.+ *+ * Crash-safety: the new tree is written to a staging sibling and validated BEFORE the running+ * plugin is stopped, so a staging failure leaves the current install completely untouched. The+ * swap itself is two renames (live → backup, staging → live); a process crash between them is+ * reconciled at boot by the loader's interrupted-update recovery, which restores the backup when+ * the live dir is missing — an interrupted update can no longer make the plugin silently vanish.+ * If loading/enabling the new version fails, the backup is restored and reloaded, so a bad update* never leaves the plugin broken.*/updatePackage(id: string, buffer: Buffer): Promise<PluginDto> {@@ -419,23 +436,74 @@ export class PluginsService {}const wasEnabled = plugin.status === PluginStatus.ENABLED;- const dir = path.join(this.pluginLoader.getPluginsDir(), id);- // Dot-prefixed sibling inside pluginsDir: same filesystem (so the rename stays EXDEV-safe) but- // skipped by the loader's directory scan, so a crash mid-update can't leave it loaded as a duplicate.- const backup = path.join(this.pluginLoader.getPluginsDir(), `.${id}.bak`);-- // Stop the running plugin (terminates its sandbox worker) but keep its registry entry so config survives.- await this.pluginLoader.unloadPlugin(id);-- fs.rmSync(backup, { recursive: true, force: true });- fs.renameSync(dir, backup);-+ const pluginsDir = this.pluginLoader.getPluginsDir();+ const dir = path.join(pluginsDir, id);+ // Dot-prefixed siblings inside pluginsDir: same filesystem (so the renames stay EXDEV-safe) but+ // skipped by the loader's directory scan, so a crash mid-update can't leave them loaded as a+ // duplicate. The loader's boot-time recovery keys off these exact names.+ const backup = path.join(pluginsDir, pluginUpdateBackupDirName(id));+ const staging = path.join(pluginsDir, pluginUpdateStagingDirName(id));++ // Stage the new tree BEFORE stopping the running plugin: any failure here (validation above,+ // disk error below) leaves the current install completely untouched.+ fs.rmSync(staging, { recursive: true, force: true });try {for (const entry of entries) {- const dest = path.join(dir, entry.relPath);+ const dest = path.join(staging, entry.relPath);fs.mkdirSync(path.dirname(dest), { recursive: true });fs.writeFileSync(dest, entry.data);}+ } catch (error) {+ fs.rmSync(staging, { recursive: true, force: true });+ throw new BadRequestException(+ `Failed to stage plugin update: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ logger.log(`Plugin update staged: ${id} → v${manifest.version}`, {+ pluginId: id,+ version: manifest.version,+ action: 'plugin_update_staged',+ });++ // Stop the running plugin (terminates its sandbox worker) but keep its registry entry so config+ // survives, then swap the directories. Self-heal first: a previously interrupted swap may have+ // left the live dir missing with only the backup remaining (normally reconciled at boot — do it+ // here too so this update proceeds from the restored previous version).+ await this.pluginLoader.unloadPlugin(id);+ try {+ if (!fs.existsSync(dir) && fs.existsSync(backup)) {+ fs.renameSync(backup, dir);+ logger.warn(`Restored plugin ${id} from its update backup before applying a new update`, {+ pluginId: id,+ action: 'plugin_update_backup_restored',+ });+ }+ fs.rmSync(backup, { recursive: true, force: true });+ fs.renameSync(dir, backup);+ fs.renameSync(staging, dir);+ } catch (error) {+ // A swap-step failure must leave a loadable install behind: put the backup back when the live+ // dir is missing, drop the staging tree, and bring the previous version back up (best-effort).+ if (!fs.existsSync(dir) && fs.existsSync(backup)) {+ fs.renameSync(backup, dir);+ }+ fs.rmSync(staging, { recursive: true, force: true });+ try {+ this.pluginLoader.loadPlugin(dir);+ if (wasEnabled) await this.pluginLoader.enablePlugin(id);+ } catch {+ /* best-effort restore; surface the original failure below */+ }+ throw new BadRequestException(+ `Failed to update plugin: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ logger.log(`Plugin update swapped in: ${id} → v${manifest.version}`, {+ pluginId: id,+ action: 'plugin_update_swapped',+ });++ try {// ctx.storage files share the package directory under shipped defaults. Restore service-owned// state from the backup unless the new package explicitly supplied that exact path. Copy (rather// than move) so the rollback below still has a complete original directory.@@ -453,6 +521,11 @@ export class PluginsService {await this.pluginLoader.enablePlugin(id);}fs.rmSync(backup, { recursive: true, force: true });+ logger.log(`Plugin updated: ${id} → v${manifest.version}`, {+ pluginId: id,+ version: manifest.version,+ action: 'plugin_update_applied',+ });} catch (error) {// Roll back to the previous version: restore the backed-up directory and reload it.// The failed forward path may have left the NEW version in the loader map (loadPlugin@@ -460,6 +533,11 @@ export class PluginsService {// otherwise the restore's loadPlugin() hits the "already loaded" guard and the runtime stays// desynced from disk (new manifest in memory, old files on disk). unloadPlugin throws when// nothing is loaded (the loadPlugin-itself-failed case), hence the catch.+ logger.warn(`Plugin update failed for ${id}; rolling back to the previous version`, {+ pluginId: id,+ action: 'plugin_update_rollback',+ error: error instanceof Error ? error.message : String(error),+ });await this.pluginLoader.unloadPlugin(id).catch(() => undefined);fs.rmSync(dir, { recursive: true, force: true });fs.renameSync(backup, dir);@@ -489,6 +567,13 @@ export class PluginsService {`Failed to download plugin from URL: ${redactSsrfError(error, logger, 'plugin download')}`,);}+ try {+ assertDownloadSha256(url, buffer);+ } catch (error) {+ throw new BadRequestException(+ `Plugin download integrity check failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }return this.updatePackage(id, buffer);}diff --git a/test/fixtures/sandbox/unload-plugin.cjs b/test/fixtures/sandbox/unload-plugin.cjsnew file mode 100644index 000000000..870e52b1c--- /dev/null+++ b/test/fixtures/sandbox/unload-plugin.cjs@@ -0,0 +1,13 @@+// Sandbox fixture: proves runLifecycle('onUnload') actually reaches the plugin inside the worker.+// onUnload flips a flag that healthCheck then reports, so the host can observe the hook ran.+module.exports = class UnloadPlugin {+ constructor() {+ this.unloaded = false;+ }+ async onUnload() {+ this.unloaded = true;+ }+ async healthCheck() {+ return { healthy: true, message: this.unloaded ? 'unloaded' : 'loaded' };+ }+};