Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): per-session config overrides (#441)
Yudhi Armyndharis6a4e760f0b1d
diff --git a/src/core/plugins/plugin-activation.spec.ts b/src/core/plugins/plugin-activation.spec.tsindex 13eee0814..ccde9856c 100644--- a/src/core/plugins/plugin-activation.spec.ts+++ b/src/core/plugins/plugin-activation.spec.ts@@ -1,4 +1,4 @@-import { isPluginActiveForSession } from './plugin-activation';+import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';describe('isPluginActiveForSession', () => {it('a global (non-session-scoped) plugin is always active', () => {@@ -24,3 +24,39 @@ describe('isPluginActiveForSession', () => {expect(isPluginActiveForSession(true, [], undefined)).toBe(true);});});++describe('resolvePluginConfig', () => {+ const base = { greeting: 'hi', lang: 'en', timeoutMs: 4000 };++ it('returns the base config when there is no per-session override', () => {+ expect(resolvePluginConfig(base, undefined, 'sess-1', true)).toEqual(base);+ expect(resolvePluginConfig(base, {}, 'sess-1', true)).toEqual(base);+ expect(resolvePluginConfig(base, { 'other-sess': { lang: 'he' } }, 'sess-1', true)).toEqual(base);+ });++ it('shallow-merges the session override over the base (override wins per top-level key)', () => {+ expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he', extra: true } }, 'sess-1', true)).toEqual({+ greeting: 'hi',+ lang: 'he',+ timeoutMs: 4000,+ extra: true,+ });+ });++ it('ignores overrides for a global (non-session-scoped) plugin', () => {+ expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, 'sess-1', false)).toEqual(base);+ });++ it('ignores overrides for a non-session-attributed event (no sessionId)', () => {+ expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, undefined, true)).toEqual(base);+ });++ it('does not mutate the base or the override', () => {+ const b = { a: 1 };+ const sc = { 'sess-1': { a: 2 } };+ const out = resolvePluginConfig(b, sc, 'sess-1', true);+ expect(out).toEqual({ a: 2 });+ expect(b).toEqual({ a: 1 });+ expect(sc).toEqual({ 'sess-1': { a: 2 } });+ });+});diff --git a/src/core/plugins/plugin-activation.ts b/src/core/plugins/plugin-activation.tsindex 66ff2c797..b5bd33076 100644--- a/src/core/plugins/plugin-activation.ts+++ b/src/core/plugins/plugin-activation.ts@@ -16,3 +16,20 @@ export function isPluginActiveForSession(if (activeSessions.includes('*')) return true;return activeSessions.includes(sessionId);}++/**+ * Resolve the config a plugin sees for a given session: the per-session override (if any) shallow-+ * merged over the base ('*') config, so an override wins per top-level key. A global plugin and a+ * non-session-attributed event (no sessionId) always get the base unchanged. Returns a fresh object+ * on merge; never mutates the inputs.+ */+export function resolvePluginConfig(+ base: Record<string, unknown>,+ sessionConfig: Record<string, Record<string, unknown>> | undefined,+ sessionId: string | undefined,+ sessionScoped: boolean,+): Record<string, unknown> {+ if (!sessionScoped || sessionId === undefined || !sessionConfig) return base;+ const override = sessionConfig[sessionId];+ return override ? { ...base, ...override } : base;+}diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 0ffb9c078..4bdef2409 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -1,6 +1,7 @@import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';+import { AsyncLocalStorage } from 'async_hooks';import * as fs from 'fs';import * as path from 'path';import { createLogger } from '../../common/services/logger.service';@@ -21,7 +22,7 @@ import {} from './plugin.interfaces';import { isNetHostAllowed, performPluginFetch } from './plugin-net';import { PluginStorageService } from './plugin-storage.service';-import { isPluginActiveForSession } from './plugin-activation';+import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';import { PluginWorkerHost } from './sandbox/plugin-worker-host';import { WorkerThreadChannel } from './sandbox/worker-thread-channel';import { dispatchCapabilityVerb } from './sandbox/capability-router';@@ -87,6 +88,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {private readonly enabling = new Set<string>();// Live worker host per enabled sandboxed (untrusted) plugin. Built-ins are not in here.private readonly sandboxHosts = new Map<string, PluginWorkerHost>();+ // Carries the firing event's sessionId across an in-process hook handler so ctx.config (a getter)+ // resolves the per-session slice. Per async call tree, so concurrent sessions don't cross over.+ private readonly hookSession = new AsyncLocalStorage<{ sessionId?: string }>();private readonly pluginsDir: string;constructor(@@ -189,9 +193,11 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {throw new Error(`Plugin ${manifest.id} is already loaded`);}- // Load any persisted config + per-session activation so an operator's choices survive a restart.+ // Load any persisted config + per-session activation + per-session config so an operator's choices+ // survive a restart.const storedConfig = this.pluginStorage.getPluginConfig(manifest.id) ?? {};const storedSessions = this.pluginStorage.getPluginSessions(manifest.id) ?? undefined;+ const storedSessionConfig = this.pluginStorage.getPluginSessionConfig(manifest.id) ?? undefined;const pluginInstance: PluginInstance = {manifest,@@ -201,6 +207,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {loadedAt: new Date(),builtIn: false,activeSessions: storedSessions,+ sessionConfig: storedSessionConfig,};this.plugins.set(manifest.id, pluginInstance);@@ -242,6 +249,10 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {builtIn,installedAt: existing?.installedAt ?? new Date(),updatedAt: new Date(),+ // setPluginEntry REPLACES the entry, so the operator's per-session activation + config must be+ // carried over or every boot wipes them from disk (lost after the second restart).+ activeSessions: existing?.activeSessions,+ sessionConfig: existing?.sessionConfig,});}@@ -473,6 +484,38 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {return plugin;}+ /**+ * Set (or clear) a plugin's per-session config override for `sessionId`. Hooks for that session then+ * see the override shallow-merged over the base via ctx.config — applied on the next event+ * (resolution reads plugin.sessionConfig live) and persisted across restart. An empty override+ * removes it (the session falls back to the base). Global plugins have no per-session config.+ */+ setPluginSessionConfig(pluginId: string, sessionId: string, config: Record<string, unknown>): PluginInstance {+ const plugin = this.plugins.get(pluginId);+ if (!plugin) {+ throw new Error(`Plugin ${pluginId} not found`);+ }+ if (plugin.manifest.sessionScoped === false) {+ throw new Error(`Plugin ${pluginId} is global (not session-scoped) and has no per-session config`);+ }++ const next = { ...(plugin.sessionConfig ?? {}) };+ if (config && Object.keys(config).length > 0) {+ next[sessionId] = config;+ } else {+ delete next[sessionId];+ }+ plugin.sessionConfig = next;+ this.pluginStorage.setPluginSessionConfig(pluginId, next);++ this.logger.debug(`Plugin session config updated: ${pluginId}`, {+ pluginId,+ action: 'plugin_session_config_updated',+ sessionId,+ });+ return plugin;+ }+/*** Run a plugin's healthCheck across both tiers. A sandboxed plugin's healthCheck lives in the worker* (plugin.instance is null), so route to the live worker host (time-bounded); built-ins use the@@ -639,6 +682,14 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {data: hookCtx.data,sessionId: hookCtx.sessionId,source: hookCtx.source,+ // The host resolves the per-session slice (real secrets — the worker is the plugin's+ // trusted execution context) and ships it; the worker exposes it as ctx.config.+ config: resolvePluginConfig(+ plugin.config,+ plugin.sessionConfig,+ hookCtx.sessionId,+ plugin.manifest.sessionScoped !== false,+ ),timeoutMs: SANDBOX_HOOK_TIMEOUT_MS,onTimeout: () =>this.logger.warn(`Sandboxed plugin ${pluginId} hook '${event}' timed out`, {@@ -693,22 +744,33 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {),};+ const hookSession = this.hookSession;return {pluginId: plugin.manifest.id,manifest: plugin.manifest,- config: plugin.config,+ // Per-session: inside a hook, returns the override merged over the base for the firing session;+ // outside a hook (lifecycle), the base config. A getter so it reflects live config edits too.+ get config() {+ return resolvePluginConfig(+ plugin.config,+ plugin.sessionConfig,+ hookSession.getStore()?.sessionId,+ plugin.manifest.sessionScoped !== false,+ );+ },hookManager: this.hookManager,logger: pluginLogger,storage: this.pluginStorage.createPluginStorage(plugin.manifest.id),registerHook: (event, handler, priority) => {// Wrap with the per-session activation gate so an in-process plugin only handles events for- // the sessions it is activated for (mirrors the sandboxed shim).+ // the sessions it is activated for (mirrors the sandboxed shim), and scope the firing+ // sessionId so ctx.config resolves the right per-session slice for the handler.this.hookManager.register(plugin.manifest.id,event,async hookCtx => {if (!this.isHookActive(plugin, hookCtx.sessionId)) return { continue: true };- return handler(hookCtx);+ return this.hookSession.run({ sessionId: hookCtx.sessionId }, () => handler(hookCtx));},priority,);diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.tsindex f9b986e20..c661a37b5 100644--- a/src/core/plugins/plugin-storage.service.ts+++ b/src/core/plugins/plugin-storage.service.ts@@ -155,6 +155,20 @@ export class PluginStorageService {}}+ getPluginSessionConfig(pluginId: string): Record<string, Record<string, unknown>> | null {+ const entry = this.registry.get(pluginId);+ return entry?.sessionConfig ?? null;+ }++ setPluginSessionConfig(pluginId: string, sessionConfig: Record<string, Record<string, unknown>>): void {+ const entry = this.registry.get(pluginId);+ if (entry) {+ entry.sessionConfig = sessionConfig;+ entry.updatedAt = new Date();+ this.saveRegistry();+ }+ }+// ============================================================================// Plugin Data Storage (sandboxed per-plugin storage)// ============================================================================diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex e72085998..8fe7dc4e7 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -263,6 +263,10 @@ export interface PluginInstance {// Sessions a session-scoped plugin is activated for; ['*'] = all. Defaulted to ['*'] on enable.// Ignored for a global (sessionScoped:false) plugin. Persisted on the registry entry.activeSessions?: string[];+ // Per-session config overrides, keyed by sessionId. The config a hook sees for session S is the+ // override shallow-merged over `config` (the '*' base) — see resolvePluginConfig. Absent = no+ // overrides (every session gets the base). Persisted on the registry entry.+ sessionConfig?: Record<string, Record<string, unknown>>;// First-party built-ins (engines, bundled extensions) run in-process; plugins loaded from the// plugins directory are untrusted and run sandboxed in a worker. `false` => sandboxed.builtIn?: boolean;@@ -285,4 +289,6 @@ export interface PluginRegistryEntry {// Sessions a session-scoped plugin is activated for; ['*'] = all. Absent = not yet set (treated// as ['*'] on enable).activeSessions?: string[];+ // Per-session config overrides (keyed by sessionId), merged over `config` per session at hook time.+ sessionConfig?: Record<string, Record<string, unknown>>;}diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.tsindex f2755b060..64d873a26 100644--- a/src/core/plugins/sandbox/plugin-worker-host.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.ts@@ -61,6 +61,7 @@ export class PluginWorkerHost {data: unknown;source: string;sessionId?: string;+ config?: Record<string, unknown>;timeoutMs: number;onTimeout?: () => void;}): Promise<{ continue: boolean; data?: unknown }> {@@ -79,6 +80,7 @@ export class PluginWorkerHost {data: options.data,sessionId: options.sessionId,source: options.source,+ config: options.config,});});}diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.tsindex e50e1ba19..92723fc45 100644--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts@@ -11,6 +11,7 @@ const HOOK_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-plugin.cjs')const HOOK_HANG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-hang-plugin.cjs');const RUNAWAY_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/runaway-plugin.cjs');const CTX_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-aware-plugin.cjs');+const 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 flushAsync = (): Promise<void> => new Promise(resolve => setImmediate(resolve));@@ -137,6 +138,57 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {await host.terminate();});+ it('exposes the host-resolved per-session config slice as ctx.config during a hook', async () => {+ const host = new PluginWorkerHost(makeChannel(), undefined, () => undefined);+ await host.load(HOOK_CONFIG_FIXTURE, { pluginId: 'hc', config: { greeting: 'base', lang: 'en' } });+ await host.runLifecycle('onEnable');+ await flushAsync();++ // A dispatch carrying the resolved slice → the handler sees exactly that as ctx.config.+ const overridden = await host.dispatchHook({+ event: 'message:received',+ data: {},+ source: 'Engine',+ timeoutMs: 5000,+ config: { greeting: 'hello-A', lang: 'en', extra: 1 },+ });+ expect((overridden.data as { config: unknown }).config).toEqual({ greeting: 'hello-A', lang: 'en', extra: 1 });++ // No resolved slice → ctx.config falls back to the base config.+ const base = await host.dispatchHook({ event: 'message:received', data: {}, source: 'Engine', timeoutMs: 5000 });+ expect((base.data as { config: unknown }).config).toEqual({ greeting: 'base', lang: 'en' });+ await host.terminate();+ });++ it('keeps ctx.config correct when hooks for different sessions interleave across an await', async () => {+ const host = new PluginWorkerHost(makeChannel(), undefined, () => undefined);+ await host.load(HOOK_CONFIG_FIXTURE, { pluginId: 'hc', config: { who: 'base' } });+ await host.runLifecycle('onEnable');+ await flushAsync();++ // Dispatch A (slow: reads ctx.config AFTER an await) and B (fast) concurrently. Without an+ // AsyncLocalStorage scope, B's config would clobber a shared ctx.config and A would read B's.+ const [a, b] = await Promise.all([+ host.dispatchHook({+ event: 'message:received',+ data: { delay: 80 },+ source: 'Engine',+ timeoutMs: 5000,+ config: { who: 'session-A' },+ }),+ host.dispatchHook({+ event: 'message:received',+ data: { delay: 0 },+ source: 'Engine',+ timeoutMs: 5000,+ config: { who: 'session-B' },+ }),+ ]);+ expect((a.data as { config: { who: string } }).config.who).toBe('session-A');+ expect((b.data as { config: { who: string } }).config.who).toBe('session-B');+ await host.terminate();+ });+it('bridges ctx.logger and ctx.config into a sandboxed plugin', async () => {const logs: Array<{ level: string; message: string; meta?: Record<string, unknown> }> = [];const host = new PluginWorkerHost(makeChannel(), undefined, undefined, (level, message, meta) =>diff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.tsindex 6766efb2f..dde5e267d 100644--- a/src/core/plugins/sandbox/protocol.ts+++ b/src/core/plugins/sandbox/protocol.ts@@ -26,7 +26,17 @@ export type HostToWorkerMessage =| { kind: 'cap-result'; id: number; ok: true; result: unknown }| { kind: 'cap-result'; id: number; ok: false; error: string }// Dispatch a subscribed hook to the worker; it runs its handler(s) and replies with hook-result.- | { kind: 'hook'; id: number; event: string; data: unknown; sessionId?: string; source: string }+ // `config` is the per-session-resolved config the host computed for this event's sessionId (the+ // override merged over the base); the worker exposes it as ctx.config for the duration of the call.+ | {+ kind: 'hook';+ id: number;+ event: string;+ data: unknown;+ sessionId?: string;+ source: string;+ config?: Record<string, unknown>;+ }// The plugin's config was updated: refresh ctx.config and invoke onConfigChange (fire-and-forget).| { kind: 'config-change'; config: Record<string, unknown> }// Ask the worker plugin to run its healthCheck(); it replies with health-result.diff --git a/src/core/plugins/sandbox/worker-bootstrap.ts b/src/core/plugins/sandbox/worker-bootstrap.tsindex ff69d83bf..6b3fbfa9d 100644--- a/src/core/plugins/sandbox/worker-bootstrap.ts+++ b/src/core/plugins/sandbox/worker-bootstrap.ts@@ -1,7 +1,7 @@import { parentPort } from 'worker_threads';import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';import { WorkerCapabilityClient, buildSandboxContext } from './worker-capability';-import { WorkerHookRegistry, WorkerHookHandler } from './worker-hooks';+import { WorkerHookRegistry, WorkerHookHandler, hookConfigStore } from './worker-hooks';/*** Worker entry for an untrusted plugin. Loads the plugin module and drives its lifecycle in response@@ -45,6 +45,8 @@ const logger = {};let plugin: LifecyclePlugin | null = null;let context: Record<string, unknown> | null = null;+// The base ('*') config; ctx.config returns the per-hook session slice when one is in scope, else this.+let baseConfig: Record<string, unknown> = {};port.on('message', (message: HostToWorkerMessage) => {if (message.kind === 'cap-result') {@@ -66,9 +68,14 @@ async function handle(message: HostToWorkerMessage): Promise<void> {const PluginCtor = mod.default ?? mod;plugin = new PluginCtor();const staticContext = message.context ?? { pluginId: 'unknown', config: {} };+ baseConfig = staticContext.config;context = {pluginId: staticContext.pluginId,- config: staticContext.config,+ // Per-session: a hook dispatch scopes its resolved slice via hookConfigStore; outside a hook+ // (lifecycle, onConfigChange) this is the base config.+ get config() {+ return hookConfigStore.getStore()?.config ?? baseConfig;+ },logger,...buildSandboxContext(capClient),registerHook: (event: string, handler: WorkerHookHandler, priority?: number) =>@@ -92,9 +99,9 @@ async function handle(message: HostToWorkerMessage): Promise<void> {}if (message.kind === 'config-change') {- // Refresh ctx.config so later reads see the new value, then notify the plugin (fire-and-forget —- // onConfigChange returns void, and an ack would just race the next operation).- if (context) context.config = message.config;+ // Refresh the base config so later (non-hook) reads of ctx.config see the new value, then notify+ // the plugin (fire-and-forget — onConfigChange returns void, and an ack would race the next op).+ baseConfig = message.config;void Promise.resolve(plugin?.onConfigChange?.(context, message.config)).catch(error =>logger.error('onConfigChange threw', error),);diff --git a/src/core/plugins/sandbox/worker-hooks.ts b/src/core/plugins/sandbox/worker-hooks.tsindex 7106cc3f1..48d69df11 100644--- a/src/core/plugins/sandbox/worker-hooks.ts+++ b/src/core/plugins/sandbox/worker-hooks.ts@@ -1,5 +1,13 @@+import { AsyncLocalStorage } from 'async_hooks';import { WorkerToHostMessage, HostToWorkerMessage } from './protocol';+/**+ * Carries the per-session-resolved config for the duration of a hook dispatch so ctx.config (a getter+ * in worker-bootstrap) returns the right slice — even when events for different sessions interleave.+ * AsyncLocalStorage scopes it per async call tree, so concurrent dispatches never see each other's.+ */+export const hookConfigStore = new AsyncLocalStorage<{ config: Record<string, unknown> }>();+export interface WorkerHookContext {event: string;data: unknown;@@ -38,6 +46,18 @@ export class WorkerHookRegistry {}async handleHook(message: Extract<HostToWorkerMessage, { kind: 'hook' }>): Promise<void> {+ // Run the whole dispatch inside the per-session config scope so every handler (and any async work+ // it awaits) sees ctx.config resolved for THIS event's session. Absent config => the bootstrap+ // getter falls back to the base config.+ const run = () => this.dispatch(message);+ if (message.config !== undefined) {+ await hookConfigStore.run({ config: message.config }, run);+ } else {+ await run();+ }+ }++ private async dispatch(message: Extract<HostToWorkerMessage, { kind: 'hook' }>): Promise<void> {const list = this.handlers.get(message.event) ?? [];let data = message.data;let shouldContinue = true;diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.tsindex 4457bc7eb..30e09959c 100644--- a/src/modules/plugins/dto/plugin.dto.ts+++ b/src/modules/plugins/dto/plugin.dto.ts@@ -46,6 +46,9 @@ export class PluginDto {@ApiPropertyOptional({ description: 'Sandboxed-iframe config editor (entry HTML + optional height)' })configUi?: { entry: string; height?: number };+ @ApiPropertyOptional({ description: 'Per-session config overrides, keyed by sessionId (secrets redacted)' })+ sessionConfig?: Record<string, Record<string, unknown>>;+@ApiPropertyOptional({ description: 'When the plugin was loaded' })loadedAt?: string;diff --git a/src/modules/plugins/plugins.controller.spec.ts b/src/modules/plugins/plugins.controller.spec.tsindex 41be06cd2..700c65fa5 100644--- a/src/modules/plugins/plugins.controller.spec.ts+++ b/src/modules/plugins/plugins.controller.spec.ts@@ -9,7 +9,16 @@ describe('PluginsController authorization', () => {// Plugin reads expose installed versions, non-secret config, and health/error text — privileged// inventory on par with the ADMIN-gated write routes and the InfraController convention. A// VIEWER/OPERATOR key (or a session-scoped key) must not be able to enumerate it via the raw API.- const adminOnly = ['findAll', 'findOne', 'healthCheck', 'enable', 'disable', 'updateConfig', 'getConfigUi'] as const;+ const adminOnly = [+ 'findAll',+ 'findOne',+ 'healthCheck',+ 'enable',+ 'disable',+ 'updateConfig',+ 'getConfigUi',+ 'updateSessionConfig',+ ] as const;it.each(adminOnly)('%s requires the ADMIN role', method => {const handler = PluginsController.prototype[method];diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex 4cf0cd4eb..d0647ba5f 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -118,6 +118,20 @@ export class PluginsController {return this.pluginsService.getConfigUiHtml(id);}+ @Put(':id/config/:sessionId')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'Set a plugin config override for a specific session (empty = clear it)' })+ @ApiResponse({ status: 200, description: 'Per-session plugin configuration updated' })+ @ApiResponse({ status: 400, description: 'Plugin is global (not session-scoped)' })+ @ApiResponse({ status: 404, description: 'Plugin not found' })+ updateSessionConfig(+ @Param('id') id: string,+ @Param('sessionId') sessionId: string,+ @Body() configDto: PluginConfigDto,+ ): { success: boolean; message: string } {+ return this.pluginsService.updateSessionConfig(id, sessionId, configDto.config);+ }+@Put(':id/sessions')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: "Set which sessions a session-scoped plugin is activated for (['*'] = all)" })diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex fe8635f44..66b5ac6fb 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -2,6 +2,7 @@ import * as fs from 'fs';import * as os from 'os';import * as path from 'path';import AdmZip from 'adm-zip';+import { BadRequestException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { PluginsService } from './plugins.service';@@ -203,3 +204,111 @@ describe('PluginsService — getConfigUiHtml (sandboxed config editor)', () => {expect(() => service.getConfigUiHtml('cfgui-plg')).toThrow(/not found/i);});});++describe('PluginsService — per-session config', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;+ let service: PluginsService;++ const schemaManifest = {+ ...manifest,+ id: 'sess-cfg',+ configSchema: {+ type: 'object',+ properties: { apiKey: { type: 'string', secret: true }, lang: { type: 'string' } },+ },+ };++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-sesscfg-'));+ 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);+ const z = new AdmZip();+ z.addFile('manifest.json', Buffer.from(JSON.stringify(schemaManifest)));+ z.addFile('index.js', Buffer.from('module.exports = class {};'));+ service.install({ buffer: z.toBuffer() });+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ it('stores a per-session override and exposes it (secrets redacted) on the DTO', () => {+ service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: 'A-secret', lang: 'he' });+ const dto = service.findOne('sess-cfg');+ expect(dto.sessionConfig).toEqual({ 'sess-A': { apiKey: '***', lang: 'he' } });+ });++ it('restores the stored per-session secret when the incoming value is the sentinel', () => {+ service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: 'A-secret', lang: 'he' });+ // The dashboard PUTs the masked slice back; the real per-session secret must survive.+ service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: '***', lang: 'en' });+ expect(loader.getPlugin('sess-cfg')?.sessionConfig?.['sess-A']).toEqual({ apiKey: 'A-secret', lang: 'en' });+ });++ it('keeps the base config and per-session overrides independent', () => {+ service.updateConfig('sess-cfg', { apiKey: 'BASE', lang: 'en' });+ service.updateSessionConfig('sess-cfg', 'sess-A', { apiKey: 'A-secret', lang: 'he' });+ const plugin = loader.getPlugin('sess-cfg');+ expect(plugin?.config).toEqual({ apiKey: 'BASE', lang: 'en' });+ expect(plugin?.sessionConfig?.['sess-A']).toEqual({ apiKey: 'A-secret', lang: 'he' });+ });++ it('clears the override when an empty slice is written', () => {+ service.updateSessionConfig('sess-cfg', 'sess-A', { lang: 'he' });+ service.updateSessionConfig('sess-cfg', 'sess-A', {});+ expect(loader.getPlugin('sess-cfg')?.sessionConfig?.['sess-A']).toBeUndefined();+ });++ it('404s for an unknown plugin', () => {+ expect(() => service.updateSessionConfig('ghost', 'sess-A', { lang: 'he' })).toThrow(/not found/i);+ });++ it('rejects per-session config for a global (non-session-scoped) plugin with 400', () => {+ const z = new AdmZip();+ z.addFile('manifest.json', Buffer.from(JSON.stringify({ ...manifest, id: 'global-plg', sessionScoped: false })));+ z.addFile('index.js', Buffer.from('module.exports = class {};'));+ service.install({ buffer: z.toBuffer() });+ expect(() => service.updateSessionConfig('global-plg', 'sess-A', { lang: 'he' })).toThrow(BadRequestException);+ });++ // A reload rebuilds the registry entry; it must NOT drop the operator's per-session config or+ // active-session selection. The wipe only surfaces on the SECOND restart (the first still has the+ // pre-wipe in-memory copy), so exercise two reload cycles.+ it('preserves per-session config and active sessions across two restarts', () => {+ const pluginDir = path.join(pluginsDir, 'sess-cfg');+ service.updateSessionConfig('sess-cfg', 'sess-A', { lang: 'he' });+ loader.setPluginSessions('sess-cfg', ['sess-A']);++ const reload = (): PluginLoaderService => {+ const l = new PluginLoaderService(+ {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService,+ new HookManager(),+ new PluginStorageService({+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService),+ {} as unknown as ModuleRef,+ );+ l.loadPlugin(pluginDir);+ return l;+ };++ const boot2 = reload();+ expect(boot2.getPlugin('sess-cfg')?.sessionConfig?.['sess-A']).toEqual({ lang: 'he' });+ expect(boot2.getPlugin('sess-cfg')?.activeSessions).toEqual(['sess-A']);++ const boot3 = reload();+ expect(boot3.getPlugin('sess-cfg')?.sessionConfig?.['sess-A']).toEqual({ lang: 'he' });+ expect(boot3.getPlugin('sess-cfg')?.activeSessions).toEqual(['sess-A']);+ });+});diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex a8dcf83ad..46c5afadd 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -3,6 +3,7 @@ import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';import { PluginLoaderService, PluginStatus, resolvePluginMainPath } 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';@@ -35,6 +36,7 @@ export class PluginsService {provides: plugin.manifest.provides ?? [],configSchema: plugin.manifest.configSchema,configUi: plugin.manifest.configUi,+ sessionConfig: this.redactSessionConfig(plugin.sessionConfig, plugin.manifest.configSchema),sessionScoped: plugin.manifest.sessionScoped !== false,activeSessions: plugin.activeSessions ?? ['*'],loadedAt: plugin.loadedAt?.toISOString(),@@ -63,6 +65,7 @@ export class PluginsService {provides: plugin.manifest.provides ?? [],configSchema: plugin.manifest.configSchema,configUi: plugin.manifest.configUi,+ sessionConfig: this.redactSessionConfig(plugin.sessionConfig, plugin.manifest.configSchema),sessionScoped: plugin.manifest.sessionScoped !== false,activeSessions: plugin.activeSessions ?? ['*'],loadedAt: plugin.loadedAt?.toISOString(),@@ -149,6 +152,50 @@ export class PluginsService {}}+ /**+ * Set a plugin's per-session config override for `sessionId`. Like updateConfig, the dashboard PUTs+ * the whole (redacted) slice back, so a sentinel secret restores the stored per-session value. An+ * empty slice clears the override (the session falls back to the base config).+ */+ updateSessionConfig(+ id: string,+ sessionId: string,+ config: Record<string, unknown>,+ ): { success: boolean; message: string } {+ const plugin = this.pluginLoader.getPlugin(id);++ if (!plugin) {+ throw new NotFoundException(`Plugin ${id} not found`);+ }+ if (plugin.manifest.sessionScoped === false) {+ // A global plugin has no per-session config — reject with 400 (mirrors PUT /:id/sessions).+ throw new BadRequestException(`Plugin ${id} is global (not session-scoped) and has no per-session config`);+ }++ try {+ const existing = plugin.sessionConfig?.[sessionId];+ const merged = restoreSecretConfig(config, existing, plugin.manifest.configSchema);+ this.pluginLoader.setPluginSessionConfig(id, sessionId, merged);+ return { success: true, message: `Plugin ${id} configuration for session ${sessionId} updated` };+ } catch (error) {+ return {+ success: false,+ message: error instanceof Error ? error.message : String(error),+ };+ }+ }++ /** Redact secrets in every per-session config slice for the DTO (mirrors the base config redaction). */+ private redactSessionConfig(+ sessionConfig: Record<string, Record<string, unknown>> | undefined,+ schema: PluginConfigSchema | undefined,+ ): Record<string, Record<string, unknown>> | undefined {+ if (!sessionConfig) return undefined;+ return Object.fromEntries(+ Object.entries(sessionConfig).map(([sid, cfg]) => [sid, redactSecretConfig(cfg, schema)]),+ );+ }+/*** Read a plugin's sandboxed config-UI entry HTML (manifest `configUi.entry`). The dashboard fetches* this with the API key and injects it as an iframe `srcdoc`, so the file must be self-contained.diff --git a/test/fixtures/sandbox/hook-config-plugin.cjs b/test/fixtures/sandbox/hook-config-plugin.cjsnew file mode 100644index 000000000..8ff19b840--- /dev/null+++ b/test/fixtures/sandbox/hook-config-plugin.cjs@@ -0,0 +1,13 @@+// Sandbox fixture: a message:received hook that echoes ctx.config back in the result data — after an+// optional `data.delay` await. Lets the integration test assert (a) the host-resolved per-session+// config slice reaches ctx.config, and (b) it stays correct when dispatches for different sessions+// interleave across an await (the AsyncLocalStorage scope must survive the await).+module.exports = class HookConfigPlugin {+ async onEnable(ctx) {+ ctx.registerHook('message:received', async (hookCtx) => {+ const delay = hookCtx.data && hookCtx.data.delay ? hookCtx.data.delay : 0;+ if (delay) await new Promise((r) => setTimeout(r, delay));+ return { continue: true, data: { config: ctx.config } };+ });+ }+};