Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(integration): deliver per-instance config to the ingress worker (#589)

Yudhi Armyndharis1b75c1fbbcf3
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 8ac369ad0..5b7fa1913 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -483,3 +483,47 @@ describe('PluginLoaderService — enable-failure hook cleanup', () => {
expect(hooks.getHookCount('message:received')).toBe(1);
});
});
+
+describe('PluginLoaderService.dispatchWebhookForInstance config delivery', () => {
+ it('delivers the instance-session-resolved config to the sandbox host', async () => {
+ const fakeInstanceService = { resolve: jest.fn().mockResolvedValue({ sessionScope: 'sess-1' }) };
+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
+ const pluginStorage = {
+ getPluginEntry: jest.fn().mockReturnValue(undefined),
+ setPluginEntry: jest.fn(),
+ getPluginConfig: jest.fn().mockReturnValue(null),
+ getPluginSessions: jest.fn().mockReturnValue(undefined),
+ getPluginSessionConfig: jest.fn().mockReturnValue(undefined),
+ } as unknown as PluginStorageService;
+ const moduleRef = { get: jest.fn().mockReturnValue(fakeInstanceService) } as unknown as ModuleRef;
+ const loader = new PluginLoaderService(configService, new HookManager(), pluginStorage, moduleRef);
+
+ const internals = loader as unknown as {
+ plugins: Map<string, unknown>;
+ sandboxHosts: Map<string, { dispatchWebhook: jest.Mock }>;
+ };
+ internals.plugins.set('chatwoot-adapter', {
+ manifest: { id: 'chatwoot-adapter', sessionScoped: true },
+ config: { baseUrl: 'base', accountId: 1 },
+ sessionConfig: { 'sess-1': { baseUrl: 'https://tenant1' } },
+ });
+ const dispatchWebhook = jest.fn().mockResolvedValue({ ok: true, status: 200 });
+ internals.sandboxHosts.set('chatwoot-adapter', { dispatchWebhook });
+
+ await loader.dispatchWebhookForInstance({
+ pluginId: 'chatwoot-adapter',
+ instanceId: 'acct1',
+ route: 'chatwoot',
+ deliveryId: 'd1',
+ sessionId: 'sess-1',
+ payload: { headers: {}, query: {}, body: '', rawBody: '' },
+ });
+
+ expect(fakeInstanceService.resolve).toHaveBeenCalledWith('chatwoot-adapter', 'acct1');
+ expect(dispatchWebhook).toHaveBeenCalledTimes(1);
+ // Session override (tenant1) merged over the base — this is what makes an instance multi-tenant.
+ expect(dispatchWebhook).toHaveBeenCalledWith(
+ expect.objectContaining({ config: { baseUrl: 'https://tenant1', accountId: 1 } }),
+ );
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 861011c7d..705112f54 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -38,6 +38,7 @@ import type { MessageService } from '../../modules/message/message.service';
import type { SessionService } from '../../modules/session/session.service';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import type { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';
+import type { PluginInstanceService } from '../../modules/integration/plugin-instance.service';
import type { IngressJobData } from '../../modules/queue/processors/ingress.processor';
/** Default per-plugin heap cap for the sandbox worker; an OOM terminates the worker, not the host. */
@@ -572,6 +573,19 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
if (!host) {
throw new Error('no live sandbox host for plugin ' + d.pluginId);
}
+ // Resolve this instance's per-session config (the base merged with the sessionScope override that
+ // provisioning wrote) so the ingress handler reads it as ctx.config — this is what makes a minted
+ // instance multi-tenant. Best-effort: an unresolved plugin just yields undefined (base config only).
+ const plugin = this.plugins.get(d.pluginId);
+ const instance = await this.getPluginInstanceService().resolve(d.pluginId, d.instanceId);
+ const config = plugin
+ ? resolvePluginConfig(
+ plugin.config,
+ plugin.sessionConfig,
+ instance?.sessionScope ?? undefined,
+ plugin.manifest.sessionScoped !== false,
+ )
+ : undefined;
const result = await host.dispatchWebhook({
instanceId: d.instanceId,
route: d.route,
@@ -583,6 +597,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
verified: true,
deliveryId: d.deliveryId,
sessionId: d.sessionId,
+ config,
timeoutMs: INGRESS_DISPATCH_TIMEOUT_MS,
});
if (!result.ok) {
@@ -621,6 +636,13 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
return this.moduleRef.get(mod.ConversationMappingService, { strict: false });
}
+ private getPluginInstanceService(): PluginInstanceService {
+ const mod =
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ require('../../modules/integration/plugin-instance.service') as typeof import('../../modules/integration/plugin-instance.service');
+ return this.moduleRef.get(mod.PluginInstanceService, { strict: false });
+ }
+
/**
* Enforce a plugin's declared manifest permissions at the capability boundary. A plugin may only
* use a capability whose permission string it declares in `manifest.permissions`; anything else
diff --git a/src/core/plugins/sandbox/dispatch-webhook.spec.ts b/src/core/plugins/sandbox/dispatch-webhook.spec.ts
index 4f9260b4a..3e5f6afad 100644
--- a/src/core/plugins/sandbox/dispatch-webhook.spec.ts
+++ b/src/core/plugins/sandbox/dispatch-webhook.spec.ts
@@ -1,4 +1,6 @@
import { PluginWorkerHost } from './plugin-worker-host';
+import { WebhookRegistry } from './worker-webhooks';
+import { hookConfigStore } from './worker-hooks';
/**
* A fake worker channel mirroring the IPC surface the host talks to. It conforms to
@@ -101,3 +103,28 @@ describe('PluginWorkerHost.dispatchWebhook', () => {
await expect(promise).resolves.toMatchObject({ ok: false, status: 500, error: 'boom' });
});
});
+
+describe('WebhookRegistry config scoping', () => {
+ it('exposes the webhook message config via hookConfigStore during the handler', async () => {
+ let seen: Record<string, unknown> | undefined;
+ const reg = new WebhookRegistry(() => {});
+ reg.register('r', () => {
+ seen = hookConfigStore.getStore()?.config;
+ });
+ await reg.handleWebhook({
+ kind: 'webhook',
+ id: 1,
+ instanceId: 'i',
+ route: 'r',
+ method: 'POST',
+ headers: {},
+ query: {},
+ body: '',
+ rawBody: '',
+ verified: true,
+ deliveryId: 'd',
+ config: { baseUrl: 'https://x' },
+ });
+ expect(seen).toEqual({ baseUrl: 'https://x' });
+ });
+});
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index ea73607e3..6cb5a8772 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -153,6 +153,7 @@ export class PluginWorkerHost {
verified: boolean;
deliveryId: string;
sessionId?: string;
+ config?: Record<string, unknown>;
timeoutMs: number;
onTimeout?: () => void;
}): Promise<{ status: number; headers?: Record<string, string>; body?: string; ok: boolean; error?: string }> {
@@ -177,6 +178,7 @@ export class PluginWorkerHost {
verified: options.verified,
deliveryId: options.deliveryId,
sessionId: options.sessionId,
+ config: options.config,
});
});
}
diff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.ts
index 79439b9af..0327ad023 100644
--- a/src/core/plugins/sandbox/protocol.ts
+++ b/src/core/plugins/sandbox/protocol.ts
@@ -58,6 +58,9 @@ export type HostToWorkerMessage =
verified: boolean;
deliveryId: string;
sessionId?: string;
+ // Per-instance-resolved config for this delivery (like the `hook` message's config). The worker
+ // exposes it as ctx.config for the duration of the handler via hookConfigStore.
+ config?: Record<string, unknown>;
};
export type WorkerToHostMessage =
diff --git a/src/core/plugins/sandbox/worker-webhooks.ts b/src/core/plugins/sandbox/worker-webhooks.ts
index 73cb32c2f..52c0595ca 100644
--- a/src/core/plugins/sandbox/worker-webhooks.ts
+++ b/src/core/plugins/sandbox/worker-webhooks.ts
@@ -1,4 +1,5 @@
import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';
+import { hookConfigStore } from './worker-hooks';
/**
* The verified inbound webhook a sandboxed plugin's handler sees. Mirrors the `webhook` wire message
@@ -41,32 +42,38 @@ export class WebhookRegistry {
this.post({ kind: 'webhook-result', id: message.id, status: 404, error: 'no handler for route' });
return;
}
- try {
- const result = await handler({
- instanceId: message.instanceId,
- method: message.method,
- headers: message.headers,
- query: message.query,
- body: message.body,
- rawBody: message.rawBody,
- verified: message.verified,
- deliveryId: message.deliveryId,
- sessionId: message.sessionId,
- });
- this.post({
- kind: 'webhook-result',
- id: message.id,
- status: result?.status ?? 200,
- headers: result?.headers,
- body: result?.body,
- });
- } catch (err) {
- this.post({
- kind: 'webhook-result',
- id: message.id,
- status: 500,
- error: err instanceof Error ? err.message : String(err),
- });
- }
+ // Run inside the per-instance config scope so ctx.config resolves to this delivery's instance config
+ // (mirrors WorkerHookRegistry.handleHook). Absent config => the bootstrap getter falls back to base.
+ const run = async () => {
+ try {
+ const result = await handler({
+ instanceId: message.instanceId,
+ method: message.method,
+ headers: message.headers,
+ query: message.query,
+ body: message.body,
+ rawBody: message.rawBody,
+ verified: message.verified,
+ deliveryId: message.deliveryId,
+ sessionId: message.sessionId,
+ });
+ this.post({
+ kind: 'webhook-result',
+ id: message.id,
+ status: result?.status ?? 200,
+ headers: result?.headers,
+ body: result?.body,
+ });
+ } catch (err) {
+ this.post({
+ kind: 'webhook-result',
+ id: message.id,
+ status: 500,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ };
+ if (message.config !== undefined) await hookConfigStore.run({ config: message.config }, run);
+ else await run();
}
}
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 047e30135..d44118693 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -30,6 +30,7 @@ export enum AuditAction {
// Integration plugin-instance events
INTEGRATION_INSTANCE_CREATED = 'integration_instance_created',
+ INTEGRATION_INSTANCE_UPDATED = 'integration_instance_updated',
INTEGRATION_INSTANCE_SECRET_REGENERATED = 'integration_instance_secret_regenerated',
INTEGRATION_INSTANCE_DELETED = 'integration_instance_deleted',
}
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.ts
new file mode 100644
index 000000000..7b69681c1
--- /dev/null
+++ b/src/modules/integration/integration-instance.controller.spec.ts
@@ -0,0 +1,113 @@
+import { IntegrationInstanceController } from './integration-instance.controller';
+import { PluginInstanceService } from './plugin-instance.service';
+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
+import { AuditService } from '../audit/audit.service';
+
+// The provisioning bridge is what makes a minted instance's config reach the ingress worker: on
+// create/patch it mirrors the instance config into the plugin's per-session config and activates the
+// bound session; on delete it clears both. dispatchWebhookForInstance then resolves it as ctx.config.
+describe('IntegrationInstanceController provisioning bridge', () => {
+ function build() {
+ const setPluginSessionConfig = jest.fn();
+ const setPluginSessions = jest.fn();
+ const updatePluginConfig = jest.fn();
+ const loader = {
+ getPlugin: jest.fn().mockReturnValue({
+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },
+ activeSessions: [],
+ }),
+ setPluginSessionConfig,
+ setPluginSessions,
+ updatePluginConfig,
+ } as unknown as PluginLoaderService;
+ const audit = { logInfo: jest.fn() } as unknown as AuditService;
+ return { loader, audit, setPluginSessionConfig, setPluginSessions, updatePluginConfig };
+ }
+
+ it('bridges instance config into per-session config + activates the session on create', async () => {
+ const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();
+ const instances = {
+ create: jest.fn().mockResolvedValue({
+ id: 'chatwoot-adapter:acct1',
+ pluginId: 'chatwoot-adapter',
+ instanceId: 'acct1',
+ sessionScope: 'sess-1',
+ secret: 's',
+ verifyToken: null,
+ config: { baseUrl: 'https://x' },
+ enabled: true,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ }),
+ } as unknown as PluginInstanceService;
+ const controller = new IntegrationInstanceController(instances, loader, audit);
+
+ await controller.create('chatwoot-adapter', {
+ instanceId: 'acct1',
+ sessionScope: 'sess-1',
+ config: { baseUrl: 'https://x' },
+ });
+
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', { baseUrl: 'https://x' });
+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', ['sess-1']);
+ });
+
+ it('deactivates the session + clears its config when the instance is disabled (PATCH enabled:false)', 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: { baseUrl: 'https://x' },
+ };
+ const instances = {
+ resolve: jest.fn().mockResolvedValue({ ...base, enabled: true }),
+ setEnabled: jest.fn().mockResolvedValue({ ...base, enabled: false }),
+ update: jest.fn(),
+ maskedView: (i: unknown) => i,
+ } as unknown as PluginInstanceService;
+ const controller = new IntegrationInstanceController(instances, loader, audit);
+
+ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });
+
+ // A disabled instance must stop firing outbound: session cleared + removed from activeSessions.
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {});
+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', []);
+ });
+
+ it('tears down the OLD scope when the bound session changes (PATCH sessionScope)', async () => {
+ const { loader, audit, setPluginSessionConfig } = 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,
+ }),
+ maskedView: (i: unknown) => i,
+ } as unknown as PluginInstanceService;
+ const controller = new IntegrationInstanceController(instances, loader, audit);
+
+ await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' });
+
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', {}); // old scope torn down
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-2', { baseUrl: 'https://y' }); // new bound
+ });
+});
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
index 3d5aede00..170f786f1 100644
--- a/src/modules/integration/integration-instance.controller.ts
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -47,6 +47,7 @@ export class IntegrationInstanceController {
void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_CREATED, {
metadata: { pluginId, instanceId: dto.instanceId },
});
+ this.applyScopeBinding(pluginId, inst.sessionScope, inst.config ?? {}, inst.enabled);
return this.view(inst, routes, /* reveal */ true);
} catch (err) {
if (err instanceof InstanceExistsError) throw new ConflictException(err.message);
@@ -90,18 +91,28 @@ export class IntegrationInstanceController {
): Promise<InstanceView> {
let inst: PluginInstance | null = await this.instances.resolve(pluginId, instanceId);
if (!inst) throw new NotFoundException('instance not found');
+ const previousScope = inst.sessionScope;
if (dto.enabled !== undefined) inst = await this.instances.setEnabled(pluginId, instanceId, dto.enabled);
if (dto.sessionScope !== undefined || dto.config !== undefined) {
inst = await this.instances.update(pluginId, instanceId, { sessionScope: dto.sessionScope, config: dto.config });
}
- return this.view(inst as PluginInstance, this.pluginRoutes(pluginId), false);
+ const updated = inst as PluginInstance;
+ // If the bound session changed, tear down the old scope so it stops firing with stale config.
+ if (previousScope && previousScope !== '*' && previousScope !== updated.sessionScope) {
+ this.applyScopeBinding(pluginId, previousScope, {}, false);
+ }
+ this.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);
+ return this.view(updated, this.pluginRoutes(pluginId), false);
}
@Delete(':instanceId')
@HttpCode(204)
async remove(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<void> {
- const removed = await this.instances.remove(pluginId, instanceId);
- if (!removed) throw new NotFoundException('instance not found');
+ const inst = await this.instances.resolve(pluginId, instanceId);
+ if (!inst) throw new NotFoundException('instance not found');
+ // Deactivate + clear the session config BEFORE deletion (needs the instance's scope).
+ this.applyScopeBinding(pluginId, inst.sessionScope, {}, false);
+ await this.instances.remove(pluginId, instanceId);
void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_DELETED, { metadata: { pluginId, instanceId } });
}
@@ -139,4 +150,39 @@ export class IntegrationInstanceController {
ingressUrls: buildIngressUrls(process.env.BASE_URL, inst.pluginId, inst.instanceId, routes),
};
}
+
+ // Bind an instance's config to the plugin's runtime so an ingress handler resolves it as ctx.config
+ // (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 ('*').
+ // Best-effort: provisioning must not fail because the plugin is momentarily unloaded.
+ private applyScopeBinding(
+ pluginId: string,
+ scope: string | null,
+ config: Record<string, unknown>,
+ activate: boolean,
+ ): void {
+ try {
+ if (!scope || scope === '*') {
+ // 'all sessions' → base config + activate ['*']. A base binding cannot be cleanly torn down
+ // (updatePluginConfig merges, so one instance's keys aren't separable) — deactivation is a no-op.
+ if (activate) {
+ this.loader.updatePluginConfig(pluginId, config);
+ this.loader.setPluginSessions(pluginId, ['*']);
+ }
+ 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);
+ this.loader.setPluginSessions(pluginId, [...set]);
+ } catch (err) {
+ // Best-effort: don't fail provisioning if the plugin is momentarily unloaded.
+ void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_UPDATED, {
+ metadata: { pluginId, scope, bridgeError: String(err) },
+ });
+ }
+ }
}