Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(plugins): share one all-sessions scope key
Yudhi Armyndharis2b19de1b4719
diff --git a/src/core/plugins/plugin-activation.spec.ts b/src/core/plugins/plugin-activation.spec.tsindex a55592770..d0ab15197 100644--- a/src/core/plugins/plugin-activation.spec.ts+++ b/src/core/plugins/plugin-activation.spec.ts@@ -1,4 +1,9 @@-import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';+import {+ isAllSessionsScope,+ isPluginActiveForSession,+ resolvePluginConfig,+ sessionScopeKey,+} from './plugin-activation';describe('isPluginActiveForSession', () => {it('a global (non-session-scoped) plugin is always active', () => {@@ -75,3 +80,15 @@ describe('resolvePluginConfig', () => {expect(sc).toEqual({ 'sess-1': { a: 2 } });});});++describe('the all-sessions scope', () => {+ it.each([null, undefined, '', '*'])('is one key whichever way it is spelled (%j)', scope => {+ expect(sessionScopeKey(scope)).toBe('*');+ expect(isAllSessionsScope(scope)).toBe(true);+ });++ it('leaves a concrete session id as it is', () => {+ expect(sessionScopeKey('sess-1')).toBe('sess-1');+ expect(isAllSessionsScope('sess-1')).toBe(false);+ });+});diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.tsindex 1e2273b25..4c50b1873 100644--- a/src/core/plugins/plugin-sandbox-bridge.ts+++ b/src/core/plugins/plugin-sandbox-bridge.ts@@ -6,7 +6,12 @@ import { PluginCapabilityPermission, PluginContext, PluginInstance, PluginStatusimport { PluginStorageService } from './plugin-storage.service';import { PluginHostServices } from './plugin-host-services';import { PluginCapabilityContext } from './plugin-capability-context';-import { isPluginActiveForSession, resolveInstanceConfig, resolvePluginConfig } from './plugin-activation';+import {+ isPluginActiveForSession,+ resolveInstanceConfig,+ resolvePluginConfig,+ sessionScopeKey,+} from './plugin-activation';import { PluginWorkerHost } from './sandbox/plugin-worker-host';import { dispatchCapabilityVerb } from './sandbox/capability-router';import { PluginLogLevel } from './sandbox/protocol';@@ -17,9 +22,6 @@ import { registerPluginSearchProvider, unregisterPluginSearchProvider } from './import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integration.constants';import type { IngressJobData } from '../../modules/queue/processors/ingress.processor';-/** The all-sessions scope is spelled null, undefined or '*' depending on where it was stored. */-const scopeKey = (scope: string | null | undefined): string => (!scope || scope === '*' ? '*' : scope);-/** Time budget for a sandboxed plugin's hook handler before the chain proceeds without it. */const SANDBOX_HOOK_TIMEOUT_MS = 5000;/** A sandboxed plugin's healthCheck must answer within this, else it's reported unhealthy (not hung). */@@ -214,7 +216,7 @@ export class PluginSandboxBridge {}// The job carries the session the instance acted on at admission. Rebound since, the delivery would// reach the handler under that session with the new session's config, so it is refused instead.- if (scopeKey(instance.sessionScope) !== scopeKey(d.sessionId)) {+ if (sessionScopeKey(instance.sessionScope) !== sessionScopeKey(d.sessionId)) {throw new Error('instance ' + d.instanceId + ' of plugin ' + d.pluginId + ' was rebound since this delivery');}// Three layers, most specific last: the base ('*') config, then the operator's per-sessiondiff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.tsindex ea442f018..f89926ac7 100644--- a/src/modules/integration/integration-instance.controller.ts+++ b/src/modules/integration/integration-instance.controller.ts@@ -17,6 +17,7 @@ import { type ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';import { AuditAction } from '../audit/entities/audit-log.entity';import { AuditService } from '../audit/audit.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { isAllSessionsScope } from '../../core/plugins/plugin-activation';import { InstanceExistsError, PluginInstanceService } from './plugin-instance.service';import { ScopeBindingService } from './scope-binding.service';import { PluginInstance } from './entities/plugin-instance.entity';@@ -25,8 +26,6 @@ import { CreateInstanceDto, InstanceView, UpdateInstanceDto } from './dto/instanimport { sessionScopeVisible } from '../../common/security/session-scope';import { ApiTags, ApiResponse } from '@nestjs/swagger';-const isWildcardScope = (scope: string | null): boolean => !scope || scope === '*';-// A session-restricted key narrows nothing outside its own sessions: binding or releasing its instance// must not retire the plugin's all-sessions activation, which an unrestricted operator set.const isScopedKey = (apiKey: ApiKey | undefined): boolean => (apiKey?.allowedSessions?.length ?? 0) > 0;@@ -38,7 +37,7 @@ const isScopedKey = (apiKey: ApiKey | undefined): boolean => (apiKey?.allowedSes* disabled or on one session, left nothing there to take back.*/const contributedConfig = (inst: PluginInstance): Record<string, unknown> | undefined =>- inst.enabled && isWildcardScope(inst.sessionScope) ? (inst.config ?? undefined) : undefined;+ inst.enabled && isAllSessionsScope(inst.sessionScope) ? (inst.config ?? undefined) : undefined;// ADMIN-only provisioning surface for per-plugin instances (e.g. one Chatwoot account). Only plugins// that declare an ingress route AND the webhook:ingress permission can have instances; everything@@ -174,7 +173,7 @@ export class IntegrationInstanceController {// A move between the spellings of the wildcard scope is re-bound right below: retracting here would// only hand the running plugin a config without its secrets for the length of one call.await this.scopeBinding.applyScopeBinding(pluginId, previousScope, {}, false, {- previousConfig: isWildcardScope(updated.sessionScope) ? undefined : previousConfig,+ previousConfig: isAllSessionsScope(updated.sessionScope) ? undefined : previousConfig,additive: isScopedKey(apiKey),});}diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.tsindex 83b11e21f..3ec531a32 100644--- a/src/modules/integration/scope-binding.service.ts+++ b/src/modules/integration/scope-binding.service.ts@@ -5,6 +5,7 @@ import { Repository } from 'typeorm';import { AuditAction } from '../audit/entities/audit-log.entity';import { AuditService } from '../audit/audit.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { sessionScopeKey } from '../../core/plugins/plugin-activation';import { Session } from '../session/entities/session.entity';import { PluginInstanceService } from './plugin-instance.service';import { PluginInstance } from './entities/plugin-instance.entity';@@ -114,15 +115,14 @@ export class ScopeBindingService implements OnApplicationBootstrap {async resyncAfterImport(previous: ReadonlyArray<{ pluginId: string; sessionScope: string | null; enabled: boolean }>,): Promise<void> {- const scopeKey = (scope: string | null): string => (!scope || scope === '*' ? '*' : scope);const bound = new Set((await this.instances.listAll()).filter(row => row.enabled)- .map(row => `${row.pluginId}\u0000${scopeKey(row.sessionScope)}`),+ .map(row => `${row.pluginId}\u0000${sessionScopeKey(row.sessionScope)}`),);const retired = new Map<string, { pluginId: string; sessionScope: string | null }>();for (const row of previous) {- const key = `${row.pluginId}\u0000${scopeKey(row.sessionScope)}`;+ const key = `${row.pluginId}\u0000${sessionScopeKey(row.sessionScope)}`;if (row.enabled && !bound.has(key)) retired.set(key, row);}for (const { pluginId, sessionScope } of retired.values()) {