Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): per-session activation (system-wide or per-number) (#438)

Yudhi Armyndharis9a8be807134e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d142a531..67d6ca43d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- Plugins: a new `ctx.net.fetch` capability lets a sandboxed plugin make outbound HTTP through the host's SSRF guard (resolve-once-pin, redirects refused), gated by a `net:fetch` permission plus a manifest `net.allow` host allowlist (`host:port`, bare `host`, or `*` for any public host; internal IPs are always blocked). Responses are bounded by a timeout and a size cap. (#437)
+- Plugins: per-session activation. A session-scoped plugin can now be activated for all numbers (`*`) or an explicit set of sessions via `PUT /plugins/:id/sessions`, and only receives hook events for the sessions it is active for (enforced at delivery). A plugin declares `sessionScoped` in its manifest (default `true`); a global plugin (`false`, e.g. a metrics logger) always runs. The active set is surfaced on the plugin API and survives a restart. (#438)
+- Plugins: a new `ctx.net.fetch` capability lets a sandboxed plugin make outbound HTTP through the host's SSRF guard (resolve-once-pin, redirects refused), gated by a `net:fetch` permission plus a manifest `net.allow` host allowlist (`host:port`, bare `host`, or `*` for any public host; internal IPs are always blocked). Responses are bounded by a timeout and a streamed size cap. (#437)
## [0.6.2] - 2026-06-23
diff --git a/src/core/plugins/plugin-activation.spec.ts b/src/core/plugins/plugin-activation.spec.ts
new file mode 100644
index 000000000..13eee0814
--- /dev/null
+++ b/src/core/plugins/plugin-activation.spec.ts
@@ -0,0 +1,26 @@
+import { isPluginActiveForSession } from './plugin-activation';
+
+describe('isPluginActiveForSession', () => {
+ it('a global (non-session-scoped) plugin is always active', () => {
+ expect(isPluginActiveForSession(false, [], 'sess-1')).toBe(true);
+ expect(isPluginActiveForSession(false, ['other'], 'sess-1')).toBe(true);
+ });
+
+ it("a session-scoped plugin with ['*'] is active for any session", () => {
+ expect(isPluginActiveForSession(true, ['*'], 'sess-1')).toBe(true);
+ expect(isPluginActiveForSession(true, ['*'], 'sess-2')).toBe(true);
+ });
+
+ it('a session-scoped plugin is active only for sessions in its list', () => {
+ expect(isPluginActiveForSession(true, ['sess-1', 'sess-2'], 'sess-1')).toBe(true);
+ expect(isPluginActiveForSession(true, ['sess-1', 'sess-2'], 'sess-3')).toBe(false);
+ });
+
+ it('an empty active list means active for no session', () => {
+ expect(isPluginActiveForSession(true, [], 'sess-1')).toBe(false);
+ });
+
+ it('a non-session-attributed event (no sessionId) is not gated', () => {
+ expect(isPluginActiveForSession(true, [], undefined)).toBe(true);
+ });
+});
diff --git a/src/core/plugins/plugin-activation.ts b/src/core/plugins/plugin-activation.ts
new file mode 100644
index 000000000..66ff2c797
--- /dev/null
+++ b/src/core/plugins/plugin-activation.ts
@@ -0,0 +1,18 @@
+/**
+ * Per-session activation gate. A plugin declares whether it is session-scoped (the default); the
+ * operator then activates it for all sessions (`['*']`) or an explicit set. A global plugin
+ * (`sessionScoped === false`, e.g. a metrics logger) ignores this and is always active.
+ *
+ * A non-session-attributed event (no `sessionId`) is never gated — the plugin chose to register that
+ * hook, and there is no number to scope it to.
+ */
+export function isPluginActiveForSession(
+ sessionScoped: boolean,
+ activeSessions: string[],
+ sessionId: string | undefined,
+): boolean {
+ if (!sessionScoped) return true;
+ if (sessionId === undefined) return true;
+ if (activeSessions.includes('*')) return true;
+ return activeSessions.includes(sessionId);
+}
diff --git a/src/core/plugins/plugin-loader-activation.spec.ts b/src/core/plugins/plugin-loader-activation.spec.ts
new file mode 100644
index 000000000..6f6310668
--- /dev/null
+++ b/src/core/plugins/plugin-loader-activation.spec.ts
@@ -0,0 +1,105 @@
+import { ConfigService } from '@nestjs/config';
+import { ModuleRef } from '@nestjs/core';
+import { PluginLoaderService } from './plugin-loader.service';
+import { PluginStorageService } from './plugin-storage.service';
+import { HookManager, HookHandler } from '../hooks';
+import { PluginContext, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
+
+function makePlugin(opts: { sessionScoped?: boolean; activeSessions?: string[] }): PluginInstance {
+ const manifest: PluginManifest = {
+ id: 'act-ext',
+ name: 'Activation Ext',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+ sessionScoped: opts.sessionScoped,
+ };
+ return { manifest, status: PluginStatus.ENABLED, config: {}, instance: null, activeSessions: opts.activeSessions };
+}
+
+describe('PluginLoaderService — per-session activation gate (hook delivery)', () => {
+ let loader: PluginLoaderService;
+ let hookManager: HookManager;
+ let setSessions: jest.Mock;
+
+ beforeEach(() => {
+ hookManager = new HookManager();
+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
+ setSessions = jest.fn();
+ const pluginStorage = {
+ createPluginStorage: jest.fn().mockReturnValue({}),
+ setPluginSessions: setSessions,
+ } as unknown as PluginStorageService;
+ loader = new PluginLoaderService(configService, hookManager, pluginStorage, {
+ get: jest.fn(),
+ } as unknown as ModuleRef);
+ });
+
+ const seed = (plugin: PluginInstance): void => {
+ (loader as unknown as { plugins: Map<string, PluginInstance> }).plugins.set(plugin.manifest.id, plugin);
+ };
+
+ function register(plugin: PluginInstance, handler: HookHandler): void {
+ const ctx = (
+ loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }
+ ).createPluginContext(plugin);
+ ctx.registerHook('message:received', handler);
+ }
+
+ const fire = (sessionId: string): Promise<unknown> =>
+ hookManager.execute('message:received', {}, { sessionId, source: 'Engine' });
+
+ it('delivers a hook only for the sessions a session-scoped plugin is activated for', async () => {
+ const handler = jest.fn().mockResolvedValue({ continue: true });
+ register(makePlugin({ activeSessions: ['sess-1'] }), handler);
+
+ await fire('sess-1');
+ expect(handler).toHaveBeenCalledTimes(1);
+
+ await fire('sess-2');
+ expect(handler).toHaveBeenCalledTimes(1); // not delivered for the inactive session
+ });
+
+ it("delivers for every session when activeSessions is ['*']", async () => {
+ const handler = jest.fn().mockResolvedValue({ continue: true });
+ register(makePlugin({ activeSessions: ['*'] }), handler);
+
+ await fire('a');
+ await fire('b');
+ expect(handler).toHaveBeenCalledTimes(2);
+ });
+
+ it('defaults to all sessions when activeSessions is unset', async () => {
+ const handler = jest.fn().mockResolvedValue({ continue: true });
+ register(makePlugin({}), handler); // no activeSessions
+
+ await fire('anything');
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('a global plugin (sessionScoped:false) always receives the hook, even with no active sessions', async () => {
+ const handler = jest.fn().mockResolvedValue({ continue: true });
+ register(makePlugin({ sessionScoped: false, activeSessions: [] }), handler);
+
+ await fire('x');
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ describe('setPluginSessions', () => {
+ it('updates a session-scoped plugin and persists the new active set', () => {
+ const plugin = makePlugin({ activeSessions: ['*'] });
+ seed(plugin);
+
+ loader.setPluginSessions('act-ext', ['sess-1', 'sess-2']);
+
+ expect(plugin.activeSessions).toEqual(['sess-1', 'sess-2']);
+ expect(setSessions).toHaveBeenCalledWith('act-ext', ['sess-1', 'sess-2']);
+ });
+
+ it('rejects activating a global (non-session-scoped) plugin per session', () => {
+ seed(makePlugin({ sessionScoped: false }));
+ expect(() => loader.setPluginSessions('act-ext', ['sess-1'])).toThrow(/global/i);
+ expect(setSessions).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 1509af7f2..0ffb9c078 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -21,6 +21,7 @@ import {
} from './plugin.interfaces';
import { isNetHostAllowed, performPluginFetch } from './plugin-net';
import { PluginStorageService } from './plugin-storage.service';
+import { isPluginActiveForSession } from './plugin-activation';
import { PluginWorkerHost } from './sandbox/plugin-worker-host';
import { WorkerThreadChannel } from './sandbox/worker-thread-channel';
import { dispatchCapabilityVerb } from './sandbox/capability-router';
@@ -188,8 +189,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
throw new Error(`Plugin ${manifest.id} is already loaded`);
}
- // Load any persisted config so an operator's settings survive a restart.
+ // Load any persisted config + per-session activation so an operator's choices survive a restart.
const storedConfig = this.pluginStorage.getPluginConfig(manifest.id) ?? {};
+ const storedSessions = this.pluginStorage.getPluginSessions(manifest.id) ?? undefined;
const pluginInstance: PluginInstance = {
manifest,
@@ -198,6 +200,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
instance: null,
loadedAt: new Date(),
builtIn: false,
+ activeSessions: storedSessions,
};
this.plugins.set(manifest.id, pluginInstance);
@@ -445,6 +448,31 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
});
}
+ /**
+ * Set the sessions a session-scoped plugin is activated for. `['*']` = all numbers (system-wide),
+ * an explicit list scopes it to those sessions, `[]` deactivates it everywhere. Takes effect on the
+ * next hook event (the gate reads plugin.activeSessions live) and survives a restart.
+ */
+ setPluginSessions(pluginId: string, sessions: string[]): 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 cannot be activated per session`);
+ }
+
+ plugin.activeSessions = sessions;
+ this.pluginStorage.setPluginSessions(pluginId, sessions);
+
+ this.logger.log(`Plugin active sessions updated: ${pluginId}`, {
+ pluginId,
+ action: 'plugin_sessions_updated',
+ sessions,
+ });
+ 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
@@ -507,6 +535,11 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
}
}
+ /** Per-session activation gate: is this plugin currently activated for `sessionId`'s event? */
+ private isHookActive(plugin: PluginInstance, sessionId: string | undefined): boolean {
+ return isPluginActiveForSession(plugin.manifest.sessionScoped ?? true, plugin.activeSessions ?? ['*'], sessionId);
+ }
+
/**
* Scope-check, then resolve the live engine for a session. getEngine returns undefined for an
* unknown OR unstarted session (no throw), so guard it into a defined PluginCapabilityError.
@@ -597,6 +630,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
async hookCtx => {
const liveHost = this.sandboxHosts.get(pluginId);
if (!liveHost) return { continue: true };
+ // Per-session activation gate: a session-scoped plugin only sees events for the sessions
+ // it is activated for. Pass-through (don't dispatch into the worker) otherwise.
+ if (!this.isHookActive(plugin, hookCtx.sessionId)) return { continue: true };
return liveHost
.dispatchHook({
event,
@@ -665,7 +701,17 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
logger: pluginLogger,
storage: this.pluginStorage.createPluginStorage(plugin.manifest.id),
registerHook: (event, handler, priority) => {
- this.hookManager.register(plugin.manifest.id, 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).
+ this.hookManager.register(
+ plugin.manifest.id,
+ event,
+ async hookCtx => {
+ if (!this.isHookActive(plugin, hookCtx.sessionId)) return { continue: true };
+ return handler(hookCtx);
+ },
+ priority,
+ );
},
messages: {
sendText: async (sessionId, chatId, text) => {
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index 684f32c94..f9b986e20 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -141,6 +141,20 @@ export class PluginStorageService {
}
}
+ getPluginSessions(pluginId: string): string[] | null {
+ const entry = this.registry.get(pluginId);
+ return entry?.activeSessions ?? null;
+ }
+
+ setPluginSessions(pluginId: string, sessions: string[]): void {
+ const entry = this.registry.get(pluginId);
+ if (entry) {
+ entry.activeSessions = sessions;
+ 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.ts
index e79911236..f9593c59f 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -70,6 +70,11 @@ export interface PluginManifest {
// capability facade. Static (manifest) by design: editing plugin config cannot widen scope.
sessions?: string[];
+ // Whether the plugin is scoped to specific sessions (default true). A session-scoped plugin only
+ // receives hook events for the sessions an operator has activated it for (see activeSessions); a
+ // global plugin (false) always runs, with no per-number notion (e.g. a metrics logger).
+ sessionScoped?: boolean;
+
// Outbound-HTTP host allowlist for `ctx.net.fetch` (requires the `net:fetch` permission). Each
// entry is `host:port` (exact) or a bare `host` (any port); `'*'` allows any public host. Absent /
// empty = deny all. The SSRF guard still blocks internal IPs regardless of this list.
@@ -236,6 +241,9 @@ export interface PluginInstance {
error?: string;
loadedAt?: Date;
enabledAt?: Date;
+ // 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[];
// 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;
@@ -255,4 +263,7 @@ export interface PluginRegistryEntry {
builtIn: boolean; // True for bundled plugins
installedAt: Date;
updatedAt: Date;
+ // Sessions a session-scoped plugin is activated for; ['*'] = all. Absent = not yet set (treated
+ // as ['*'] on enable).
+ activeSessions?: string[];
}
diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.ts
index 4cc819da4..1e6c28aa5 100644
--- a/src/modules/plugins/dto/plugin.dto.ts
+++ b/src/modules/plugins/dto/plugin.dto.ts
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { IsObject, IsString, IsUrl } from 'class-validator';
+import { IsArray, IsObject, IsString, IsUrl } from 'class-validator';
import type { PluginConfigSchema } from '../../../core/plugins';
import { PluginType, PluginStatus } from '../../../core/plugins';
@@ -34,6 +34,12 @@ export class PluginDto {
@ApiProperty({ description: 'Features provided by this plugin' })
provides!: string[];
+ @ApiProperty({ description: 'Whether the plugin is scoped to specific sessions (false = global)' })
+ sessionScoped!: boolean;
+
+ @ApiProperty({ description: "Sessions this plugin is activated for; ['*'] = all numbers" })
+ activeSessions!: string[];
+
@ApiPropertyOptional({ description: 'Configuration schema' })
configSchema?: PluginConfigSchema;
@@ -53,6 +59,17 @@ export class PluginConfigDto {
config!: Record<string, unknown>;
}
+export class PluginSessionsDto {
+ @ApiProperty({
+ description: "Sessions to activate the plugin for; ['*'] = all numbers, [] = none",
+ example: ['*'],
+ type: [String],
+ })
+ @IsArray()
+ @IsString({ each: true })
+ sessions!: string[];
+}
+
export class InstallFromUrlDto {
@ApiProperty({ description: 'HTTP(S) URL of the plugin .zip to download and install' })
@IsString()
diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.ts
index 009208cf3..74916b3a3 100644
--- a/src/modules/plugins/plugins.controller.ts
+++ b/src/modules/plugins/plugins.controller.ts
@@ -14,7 +14,7 @@ import {
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiOperation, ApiResponse, ApiConsumes } from '@nestjs/swagger';
import { PluginsService } from './plugins.service';
-import { PluginDto, PluginConfigDto, InstallFromUrlDto } from './dto/plugin.dto';
+import { PluginDto, PluginConfigDto, PluginSessionsDto, InstallFromUrlDto } from './dto/plugin.dto';
import type { CatalogPlugin } from './catalog';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -102,6 +102,16 @@ export class PluginsController {
return this.pluginsService.updateConfig(id, configDto.config);
}
+ @Put(':id/sessions')
+ @RequireRole(ApiKeyRole.ADMIN)
+ @ApiOperation({ summary: "Set which sessions a session-scoped plugin is activated for (['*'] = all)" })
+ @ApiResponse({ status: 200, description: 'Plugin session activation updated', type: PluginDto })
+ @ApiResponse({ status: 400, description: 'Plugin is global (not session-scoped)' })
+ @ApiResponse({ status: 404, description: 'Plugin not found' })
+ updateSessions(@Param('id') id: string, @Body() dto: PluginSessionsDto): PluginDto {
+ return this.pluginsService.updateSessions(id, dto.sessions);
+ }
+
@Post(':id/update')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Update an installed plugin in place from a URL (preserves config + enabled state)' })
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index 90bcce97b..e027fbba3 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -34,6 +34,8 @@ export class PluginsService {
builtIn: this.pluginLoader.isBuiltIn(plugin.manifest.id),
provides: plugin.manifest.provides ?? [],
configSchema: plugin.manifest.configSchema,
+ sessionScoped: plugin.manifest.sessionScoped !== false,
+ activeSessions: plugin.activeSessions ?? ['*'],
loadedAt: plugin.loadedAt?.toISOString(),
enabledAt: plugin.enabledAt?.toISOString(),
error: plugin.error,
@@ -59,6 +61,8 @@ export class PluginsService {
builtIn: this.pluginLoader.isBuiltIn(plugin.manifest.id),
provides: plugin.manifest.provides ?? [],
configSchema: plugin.manifest.configSchema,
+ sessionScoped: plugin.manifest.sessionScoped !== false,
+ activeSessions: plugin.activeSessions ?? ['*'],
loadedAt: plugin.loadedAt?.toISOString(),
enabledAt: plugin.enabledAt?.toISOString(),
error: plugin.error,
@@ -109,6 +113,19 @@ export class PluginsService {
}
}
+ updateSessions(id: string, sessions: string[]): PluginDto {
+ const plugin = this.pluginLoader.getPlugin(id);
+ if (!plugin) {
+ throw new NotFoundException(`Plugin ${id} not found`);
+ }
+ try {
+ this.pluginLoader.setPluginSessions(id, sessions);
+ } catch (error) {
+ throw new BadRequestException(error instanceof Error ? error.message : String(error));
+ }
+ return this.findOne(id);
+ }
+
updateConfig(id: string, config: Record<string, unknown>): { success: boolean; message: string } {
const plugin = this.pluginLoader.getPlugin(id);