Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): do not tear down a session scope still shared by an enabled sibling instance (#922)
Yudhi Armyndharise45fb27a2e57
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.tsindex eef1a5350..cb287f12e 100644--- a/src/modules/integration/integration-instance.controller.spec.ts+++ b/src/modules/integration/integration-instance.controller.spec.ts@@ -42,6 +42,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {createdAt: new Date(0),updatedAt: new Date(0),}),+ list: jest.fn().mockResolvedValue([]),} as unknown as PluginInstanceService;const controller = new IntegrationInstanceController(instances,@@ -76,6 +77,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {resolve: jest.fn().mockResolvedValue({ ...base, enabled: true }),setEnabled: jest.fn().mockResolvedValue({ ...base, enabled: false }),update: jest.fn(),+ list: jest.fn().mockResolvedValue([]), // no sibling shares the scopemaskedView: (i: unknown) => i,} as unknown as PluginInstanceService;const controller = new IntegrationInstanceController(@@ -171,6 +173,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {config: { baseUrl: 'https://y' },enabled: true,}),+ list: jest.fn().mockResolvedValue([]), // no sibling shares the old scopemaskedView: (i: unknown) => i,} as unknown as PluginInstanceService;const controller = new IntegrationInstanceController(@@ -185,6 +188,222 @@ describe('IntegrationInstanceController provisioning bridge', () => {expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {}); // old scope torn downexpect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-2', { baseUrl: 'https://y' }); // new bound});++ it('keeps the session + its config when a disabled instance shares its scope with an ENABLED sibling', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['sess-1'],+ });+ const base = { pluginId: 'chatwoot-adapter', instanceId: 'acct1', sessionScope: 'sess-1', config: {} };+ const instances = {+ resolve: jest.fn().mockResolvedValue({ ...base, enabled: true }),+ setEnabled: jest.fn().mockResolvedValue({ ...base, enabled: false }),+ update: jest.fn(),+ // The row is already disabled when the teardown lists instances; an ENABLED sibling still binds sess-1.+ list: jest.fn().mockResolvedValue([+ { ...base, enabled: false },+ { pluginId: 'chatwoot-adapter', instanceId: 'acct2', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );++ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });++ // The sibling still fires on sess-1: neither the session nor its sessionConfig may be torn down.+ expect(setPluginSessionConfig).not.toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {});+ expect(setPluginSessions).not.toHaveBeenCalled();+ });++ it('keeps the session + its config when a deleted instance shares its scope with an ENABLED sibling', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['sess-1'],+ });+ const instances = {+ resolve: jest.fn().mockResolvedValue({+ pluginId: 'chatwoot-adapter',+ instanceId: 'acct1',+ sessionScope: 'sess-1',+ config: {},+ enabled: true,+ }),+ remove: jest.fn().mockResolvedValue(true),+ // The row is already deleted when the teardown lists instances; only the ENABLED sibling remains.+ list: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot-adapter', instanceId: 'acct2', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );++ await controller.remove('chatwoot-adapter', 'acct1');++ expect(setPluginSessionConfig).not.toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {});+ expect(setPluginSessions).not.toHaveBeenCalled();+ });++ it('still tears down the session on delete when no ENABLED sibling shares its scope', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['sess-1'],+ });+ const instances = {+ resolve: jest.fn().mockResolvedValue({+ pluginId: 'chatwoot-adapter',+ instanceId: 'acct1',+ sessionScope: 'sess-1',+ config: {},+ enabled: true,+ }),+ remove: jest.fn().mockResolvedValue(true),+ list: jest.fn().mockResolvedValue([]), // no instances left at all+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );++ await controller.remove('chatwoot-adapter', 'acct1');++ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {});+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', []);+ });++ it('keeps the OLD scope bound by an ENABLED sibling on a scope move (PATCH sessionScope) and binds the new one', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['sess-1'],+ });+ const instances = {+ resolve: jest.fn().mockResolvedValue({+ pluginId: 'chatwoot-adapter',+ instanceId: 'acct1',+ sessionScope: 'sess-1',+ config: { baseUrl: 'https://x' },+ enabled: true,+ }),+ setEnabled: jest.fn(),+ update: jest.fn().mockResolvedValue({+ pluginId: 'chatwoot-adapter',+ instanceId: 'acct1',+ sessionScope: 'sess-2',+ config: { baseUrl: 'https://y' },+ enabled: true,+ }),+ // The row is already on sess-2 when the old scope's teardown lists instances; the sibling still binds sess-1.+ list: jest.fn().mockResolvedValue([+ { pluginId: 'chatwoot-adapter', instanceId: 'acct1', sessionScope: 'sess-2', config: {}, enabled: true },+ { pluginId: 'chatwoot-adapter', instanceId: 'acct2', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );++ await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' });++ expect(setPluginSessionConfig).not.toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {}); // old scope kept for the sibling+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-2', { baseUrl: 'https://y' }); // new scope bound+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', ['sess-1', 'sess-2']); // sess-1 never stripped+ });++ it('keeps "*" active when a concrete-scope instance is disabled while an ENABLED wildcard sibling remains', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['*', 'sess-1'],+ });+ const base = { pluginId: 'chatwoot-adapter', instanceId: 'acct1', sessionScope: 'sess-1', config: {} };+ const instances = {+ resolve: jest.fn().mockResolvedValue({ ...base, enabled: true }),+ setEnabled: jest.fn().mockResolvedValue({ ...base, enabled: false }),+ update: jest.fn(),+ list: jest.fn().mockResolvedValue([+ { ...base, enabled: false },+ { pluginId: 'chatwoot-adapter', instanceId: 'acct2', sessionScope: null, config: {}, enabled: true },+ ]),+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );++ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });++ // Its own scope is torn down (no concrete sibling), but the wildcard sibling's '*' must survive.+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {});+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', ['*']);+ });++ it('keeps "*" when a concrete-scope instance is created while an ENABLED wildcard instance exists', async () => {+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['*'],+ });+ const instances = {+ create: jest.fn().mockResolvedValue({+ id: 'chatwoot-adapter:acct2',+ pluginId: 'chatwoot-adapter',+ instanceId: 'acct2',+ sessionScope: 'sess-1',+ secret: 's',+ verifyToken: null,+ config: { baseUrl: 'https://x' },+ enabled: true,+ createdAt: new Date(0),+ updatedAt: new Date(0),+ }),+ list: jest.fn().mockResolvedValue([+ { pluginId: 'chatwoot-adapter', instanceId: 'acct1', sessionScope: '*', config: {}, enabled: true },+ { pluginId: 'chatwoot-adapter', instanceId: 'acct2', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ instances,+ loader,+ audit,+ new ScopeBindingService(instances, loader, audit),+ );++ await controller.create('chatwoot-adapter', {+ instanceId: 'acct2',+ sessionScope: 'sess-1',+ config: { baseUrl: 'https://x' },+ });++ // Previously the concrete activation stripped '*', silencing the wildcard instance until the next boot.+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', { baseUrl: 'https://x' });+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', ['sess-1', '*']);+ });});// sessionScope travels in the request body, which the ApiKeyGuard's route-param fence never sees —diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.tsindex 817fdff14..1d92ab77b 100644--- a/src/modules/integration/scope-binding.service.spec.ts+++ b/src/modules/integration/scope-binding.service.spec.ts@@ -29,6 +29,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {.mockResolvedValue([{ pluginId: 'chatwoot', instanceId: 'a', sessionScope: 'sess-1', config: { baseUrl: 'x' }, enabled: true },]),+ list: jest.fn().mockResolvedValue([]),} as unknown as PluginInstanceService;await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();@@ -114,7 +115,10 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {[concrete, wildcard],] as const) {plugin.activeSessions = [];- const instances = { listAll: jest.fn().mockResolvedValue(rowOrder) } as unknown as PluginInstanceService;+ const instances = {+ listAll: jest.fn().mockResolvedValue(rowOrder),+ list: jest.fn().mockResolvedValue([]),+ } as unknown as PluginInstanceService;await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();// The wildcard activation must survive in both row orders ('*' subsumes the concrete scope).expect(plugin.activeSessions).toContain('*');diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.tsindex dda909ad6..89380a7ad 100644--- a/src/modules/integration/scope-binding.service.ts+++ b/src/modules/integration/scope-binding.service.ts@@ -46,12 +46,13 @@ export class ScopeBindingService implements OnApplicationBootstrap {// Order-independent reconciliation: listAll() is repo.find() with no ORDER BY, so its row order// is DB/restart-dependent (differs between SQLite and Postgres). applyScopeBinding mutates the- // SAME in-memory plugin.activeSessions each iteration — the concrete-scope path strips '*' while- // the wildcard path overwrites with ['*'] — so for a plugin with BOTH a wildcard and a concrete- // instance the final set would otherwise depend on row order (a concrete processed after a- // wildcard drops the '*'). Sort concrete scopes before wildcard/null so the wildcard's ['*'] is- // the last write (correct: '*' subsumes every concrete scope), making the result stable across- // DBs and restarts. instanceId is the deterministic tiebreak among same-rank rows.+ // SAME in-memory plugin.activeSessions each iteration — the concrete-scope path strips '*' (unless+ // an enabled wildcard sibling still binds it) while the wildcard path overwrites with ['*'] — so for+ // a plugin with BOTH a wildcard and a concrete instance the final set would otherwise depend on row+ // order (a concrete processed after a wildcard could drop the '*'). Sort concrete scopes before+ // wildcard/null so the wildcard's ['*'] is the last write (correct: '*' subsumes every concrete+ // scope), making the result stable across DBs and restarts. instanceId is the deterministic+ // tiebreak among same-rank rows.rows.sort((a, b) => {const rank = (i: PluginInstance) => (!i.sessionScope || i.sessionScope === '*' ? 1 : 0);if (rank(a) !== rank(b)) return rank(a) - rank(b);@@ -80,6 +81,9 @@ export class ScopeBindingService implements OnApplicationBootstrap {* (see PluginLoaderService.dispatchWebhookForInstance) and activate the session — iff `activate` (a* disabled or removed instance must not keep firing). A concrete scope writes sessionConfig[scope] and* toggles that session in activeSessions; a null/'*' scope binds the base config + all sessions ('*').+ * A concrete teardown/activation never strips state a still-ENABLED sibling depends on: the scope's+ * session + sessionConfig survive while a sibling binds the same scope, and '*' survives while a+ * sibling binds a wildcard/null scope.* Best-effort: provisioning must not fail because the plugin is momentarily unloaded.*/async applyScopeBinding(@@ -112,11 +116,27 @@ export class ScopeBindingService implements OnApplicationBootstrap {}return;}+ // Concrete scope → per-session config + toggle that session in activeSessions. Mirror the+ // wildcard path's retirement guard in BOTH directions: runtime state a still-ENABLED sibling+ // instance depends on must survive this instance's change. The controller persists the row+ // first (PATCH updates/disables it, DELETE removes it), so the list below never counts the+ // instance being torn down.+ const siblings = await this.instances.list(pluginId);+ if (!activate && siblings.some(i => i.enabled && i.sessionScope === scope)) {+ // A sibling still binds this scope: leave the session active and its sessionConfig intact —+ // stripping either would silence the sibling until the next boot-time reconciliation.+ return;+ }this.loader.setPluginSessionConfig(pluginId, scope, activate ? config : {});const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];const set = new Set(current.filter(s => s !== '*'));if (activate) set.add(scope);else set.delete(scope);+ // Preserve '*' while an enabled wildcard/null sibling still binds all sessions ('*' subsumes+ // every concrete scope): a concrete activation/teardown must not silence that sibling either.+ if (current.includes('*') && siblings.some(i => i.enabled && (!i.sessionScope || i.sessionScope === '*'))) {+ set.add('*');+ }this.loader.setPluginSessions(pluginId, [...set]);} catch (err) {// Best-effort: don't fail provisioning if the plugin is momentarily unloaded.