Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat: Integration Fabric — inbound webhook substrate for sandboxed plugins (P0) (#568)
Yudhi Armyndharis90729c968851
diff --git a/src/app.module.ts b/src/app.module.tsindex 627d47ab2..3e4666f4e 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -33,6 +33,7 @@ import { HooksModule } from './core/hooks';import { PluginsModule } from './core/plugins';import { PluginsApiModule } from './modules/plugins/plugins.module';import { AgentToolsModule } from './core/agent-tools/agent-tools.module';+import { IntegrationModule } from './modules/integration/integration.module';// Only import QueueModule if explicitly enabled to avoid Redis connection errorsconst queueModules: Array<Type | DynamicModule> = [];@@ -132,6 +133,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {__dirname + '/modules/message/**/*.entity{.ts,.js}',__dirname + '/modules/template/**/*.entity{.ts,.js}',__dirname + '/engine/**/*.entity{.ts,.js}',+ __dirname + '/modules/integration/**/*.entity{.ts,.js}',],migrations: [__dirname + '/database/migrations/*{.ts,.js}'],logging: configService.get<boolean>('dataDatabase.logging', false),@@ -241,6 +243,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {CatalogModule, // Phase 3: Catalog API (WhatsApp Business)PluginsApiModule, // Phase 5: Plugins APIAgentToolsModule, // Agent-invocable tool registry (protocol-neutral)+ IntegrationModule, // Integration Fabric: @Public provider-webhook ingress + fast-ack pipeline...mcpModules, // MCP Streamable-HTTP server (opt-in via MCP_ENABLED=true)...serveStaticModules, // Bundled dashboard SPA (production single-port setup)],diff --git a/src/core/hooks/hook.interfaces.ts b/src/core/hooks/hook.interfaces.tsindex 19456f40c..b0549243f 100644--- a/src/core/hooks/hook.interfaces.ts+++ b/src/core/hooks/hook.interfaces.ts@@ -23,7 +23,9 @@ export type HookEvent =| 'webhook:queued' // After webhook job added to queue (queue mode only)| 'webhook:delivered' // After webhook successfully delivered (direct or queue)| 'webhook:after' // After webhook attempt (direct mode only, deprecated for queue)- | 'webhook:error'; // After webhook delivery failed (all retries exhausted)+ | 'webhook:error' // After webhook delivery failed (all retries exhausted)+ // Ingress (inbound provider webhook -> plugin) lifecycle+ | 'ingress:error'; // After an ingress dispatch failed (all retries exhausted)// Runtime allowlist of every HookEvent. The Record is exhaustively typed, so adding a HookEvent above// without listing it here is a COMPILE error — keeping the runtime set in lockstep with the type.@@ -47,6 +49,7 @@ const HOOK_EVENT_REGISTRY: Record<HookEvent, true> = {'webhook:delivered': true,'webhook:after': true,'webhook:error': true,+ 'ingress:error': true,};export const KNOWN_HOOK_EVENTS: ReadonlySet<HookEvent> = new Set(Object.keys(HOOK_EVENT_REGISTRY) as HookEvent[]);diff --git a/src/core/plugins/conversation-send-facade.spec.ts b/src/core/plugins/conversation-send-facade.spec.tsnew file mode 100644index 000000000..b86ee31a6--- /dev/null+++ b/src/core/plugins/conversation-send-facade.spec.ts@@ -0,0 +1,48 @@+import { buildConversationSendFacade } from './conversation-send-facade';++describe('conversation.send facade', () => {+ const manifest = (perms: string[]) => ({ id: 'chatwoot', permissions: perms, sessions: ['*'] });++ it('throws PluginCapabilityError when conversation:send is not granted', async () => {+ const facade = buildConversationSendFacade({+ manifest: manifest([]) as never,+ assertPermission: (m: { permissions: string[] }, p: string) => {+ if (!m.permissions.includes(p)) throw new Error(`missing ${p}`);+ },+ assertSessionAllowed: () => undefined,+ resolveChatId: () => Promise.resolve('[email protected]'),+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),+ sendText: jest.fn(),+ reply: jest.fn(),+ } as never);+ await expect(facade.send({ type: 'text', text: 'x', sessionId: 's', chatId: 'c' })).rejects.toThrow(+ /conversation:send/,+ );+ });++ it('resolves chatId from the mapping when the envelope omits it, then sends text', async () => {+ const sendText = jest.fn().mockResolvedValue({ id: 'm1' });+ const resolveChatId = jest.fn().mockResolvedValue('[email protected]');+ const runGuarded = jest.fn((_events: string[], run: () => Promise<unknown>) => run());+ const facade = buildConversationSendFacade({+ manifest: manifest(['conversation:send']) as never,+ assertPermission: () => undefined,+ assertSessionAllowed: jest.fn(),+ resolveChatId,+ runGuarded,+ sendText,+ reply: jest.fn(),+ } as never);+ const res = await facade.send({+ type: 'text',+ text: 'hi',+ sessionId: 's',+ source: { provider: 'chatwoot', externalConversationId: '42' },+ });+ expect(resolveChatId).toHaveBeenCalled();+ expect(sendText).toHaveBeenCalledWith('s', { chatId: '[email protected]', text: 'hi' });+ // re-entrancy guard must wrap the downstream send so the adapter's own message:* hook is short-circuited+ expect(runGuarded).toHaveBeenCalled();+ expect(res).toEqual({ id: 'm1' });+ });+});diff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.tsnew file mode 100644index 000000000..9ab905cab--- /dev/null+++ b/src/core/plugins/conversation-send-facade.ts@@ -0,0 +1,37 @@+import { ConversationSendEnvelope, PluginCapabilityPermission, PluginManifest } from './plugin.interfaces';++export interface ConversationSendDeps {+ manifest: PluginManifest;+ assertPermission: (manifest: PluginManifest, permission: string) => void;+ assertSessionAllowed: (manifest: PluginManifest, sessionId: string) => void;+ // Resolve the WA chat id from conversation_mappings when the envelope omits chatId.+ resolveChatId: (env: ConversationSendEnvelope) => Promise<string>;+ // Seed the hook in-flight set so an adapter's own outbound message:sending hook cannot echo-loop+ // back into this same send. Only 'message:sending' is reachable this way — MessageService fires it+ // synchronously inside sendText/reply. 'message:sent' is emitted later by SessionService's engine+ // callback (onMessageCreate), outside this call's async scope, so seeding it here would be a no-op.+ runGuarded: <T>(events: string[], run: () => Promise<T>) => Promise<T>;+ sendText: (sessionId: string, opts: { chatId: string; text: string }) => Promise<unknown>;+ reply: (sessionId: string, opts: { chatId: string; quotedMessageId: string; text: string }) => Promise<unknown>;+}++const MESSAGE_HOOK_EVENTS = ['message:sending'];++export function buildConversationSendFacade(deps: ConversationSendDeps) {+ return {+ async send(env: ConversationSendEnvelope): Promise<unknown> {+ deps.assertPermission(deps.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ const sessionId = env.sessionId;+ if (!sessionId) throw new Error('conversation.send: sessionId is required');+ deps.assertSessionAllowed(deps.manifest, sessionId);+ const chatId = env.chatId ?? (await deps.resolveChatId(env));+ // Only text/reply are wired in P0; media types are additive in a later minor.+ return deps.runGuarded(MESSAGE_HOOK_EVENTS, async () => {+ if (env.replyTo) {+ return deps.reply(sessionId, { chatId, quotedMessageId: env.replyTo, text: env.text ?? '' });+ }+ return deps.sendText(sessionId, { chatId, text: env.text ?? '' });+ });+ },+ };+}diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 589a2761a..d50465164 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -13,6 +13,7 @@ import {PluginManifest,PluginMessagingCapability,PluginNetCapability,+ PluginConversationsCapability,PluginInstance,PluginStatus,PluginContext,@@ -27,9 +28,14 @@ import { PluginWorkerHost } from './sandbox/plugin-worker-host';import { WorkerThreadChannel } from './sandbox/worker-thread-channel';import { dispatchCapabilityVerb } from './sandbox/capability-router';import { PluginLogLevel } from './sandbox/protocol';+import { buildConversationSendFacade } from './conversation-send-facade';+import { makeOnWebhookSubscribe } from './webhook-subscribe.util';+import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integration.constants';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 { IngressJobData } from '../../modules/queue/processors/ingress.processor';/** Default per-plugin heap cap for the sandbox worker; an OOM terminates the worker, not the host. */const SANDBOX_MAX_OLD_GEN_MB = 256;@@ -548,6 +554,35 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {return { healthy: true, message: 'Plugin does not implement health check' };}+ /**+ * Dispatch a queued ingress job into its plugin's live sandbox worker. Called from IngressProcessor,+ * mirroring checkPluginHealth's sandboxHosts lookup. Throws when the plugin has no live+ * worker (disabled/crashed since the job was enqueued) or when the worker's handler itself reports+ * failure (`!result.ok`, e.g. a 502/504/500) — either way BullMQ's retry/DLQ machinery takes over.+ */+ async dispatchWebhookForInstance(d: IngressJobData): Promise<void> {+ const host = this.sandboxHosts.get(d.pluginId);+ if (!host) {+ throw new Error('no live sandbox host for plugin ' + d.pluginId);+ }+ const result = await host.dispatchWebhook({+ instanceId: d.instanceId,+ route: d.route,+ method: 'POST',+ headers: d.payload.headers,+ query: d.payload.query,+ body: d.payload.body,+ rawBody: d.payload.rawBody,+ verified: true,+ deliveryId: d.deliveryId,+ sessionId: d.sessionId,+ timeoutMs: INGRESS_DISPATCH_TIMEOUT_MS,+ });+ if (!result.ok) {+ throw new Error(result.error ?? 'ingress dispatch failed with status ' + result.status);+ }+ }+/*** Resolve MessageService at call time via a lazy require so plugin-loader creates NO top-level* module-load edge to message.service. A static import closes the cycle@@ -568,6 +603,17 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {return this.moduleRef.get(mod.SessionService, { strict: false });}+ /**+ * Same lazy-require pattern as getMessageService/getSessionService: a static import of the+ * integration module would add a top-level edge back into plugin-loader's own module graph.+ */+ private getConversationMappingService(): ConversationMappingService {+ const mod =+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ require('../../modules/integration/conversation-mapping.service') as typeof import('../../modules/integration/conversation-mapping.service');+ return this.moduleRef.get(mod.ConversationMappingService, { 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@@ -625,6 +671,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {protected createSandboxHost(capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,onHookSubscribe?: (event: string, priority?: number) => void,+ onWebhookSubscribe?: (route: string) => void,onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,): PluginWorkerHost {@@ -638,6 +685,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {}),capDispatcher,onHookSubscribe,+ onWebhookSubscribe,onLog,runWithHookGuard,SANDBOX_MAX_INFLIGHT_CAPS,@@ -745,6 +793,22 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {);};+ // When the worker claims an ingress route, record it against the manifest-declared routes so the+ // host knows which routes this worker will handle. Same hardening as onHookSubscribe (the wire+ // `route` is an arbitrary untrusted string): drop when the manifest lacks 'webhook:ingress', drop+ // an undeclared route (warn once), dedup, and cap. subscribedRoutes is local to this enable call,+ // so it is dropped on disable exactly as subscribedEvents is.+ const subscribedRoutes = new Set<string>();+ const declaredRoutes = new Set((plugin.manifest.ingress ?? []).map(r => r.route));+ const onWebhookSubscribe = makeOnWebhookSubscribe({+ pluginId,+ declaredRoutes,+ hasPermission: (plugin.manifest.permissions ?? []).includes(PluginCapabilityPermission.WEBHOOK_INGRESS),+ subscribed: subscribedRoutes,+ maxRoutes: declaredRoutes.size,+ warn: (message, meta) => this.logger.warn(message, meta),+ });+// Route the worker plugin's ctx.logger.* calls to the same per-plugin logger an in-process plugin// uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout.const onLog = (level: PluginLogLevel, message: string, meta?: Record<string, unknown>): void => {@@ -755,6 +819,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {const host = this.createSandboxHost((verb, args) => dispatchCapabilityVerb(context, verb, args),onHookSubscribe,+ onWebhookSubscribe,onLog,// Re-establish the in-flight hook context for worker-initiated capability calls, so a sandboxed// plugin that sends from within a send hook can't loop the event back into itself unboundedly.@@ -858,6 +923,35 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {return performPluginFetch(url, init);},} satisfies PluginNetCapability,+ conversations: buildConversationSendFacade({+ manifest: plugin.manifest,+ assertPermission: this.assertPermission.bind(this),+ assertSessionAllowed: this.assertSessionAllowed.bind(this),+ resolveChatId: async env => {+ if (!env.instanceId || !env.source) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: conversation.send requires chatId, or both instanceId and source to resolve one`,+ );+ }+ const mapping = await this.getConversationMappingService().getByProvider(+ plugin.manifest.id,+ env.instanceId,+ env.source.externalConversationId,+ );+ if (!mapping) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: no conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId}`,+ );+ }+ return mapping.chatId;+ },+ // Re-establish the in-flight hook context around the downstream send so an adapter that calls+ // conversation.send from within its own ingress handling can't echo-loop back into itself via+ // its own outbound message:sending hook (mirrors the sandboxed worker-cap wrap below).+ runGuarded: (events, run) => this.hookManager.runInFlight(events as HookEvent[], run),+ sendText: (sessionId, opts) => this.getMessageService().sendText(sessionId, opts),+ reply: (sessionId, opts) => this.getMessageService().reply(sessionId, opts),+ } satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability,};}diff --git a/src/core/plugins/plugin-manifest-ingress.spec.ts b/src/core/plugins/plugin-manifest-ingress.spec.tsnew file mode 100644index 000000000..3a7d9e0ac--- /dev/null+++ b/src/core/plugins/plugin-manifest-ingress.spec.ts@@ -0,0 +1,57 @@+import { validateIngressManifest, SUPPORTED_SDK_MAJOR } from './plugin.interfaces';++const baseManifest = () => ({+ id: 'chatwoot',+ name: 'Chatwoot',+ version: '1.0.0',+ main: 'index.js',+ sdkVersion: '1',+ permissions: ['webhook:ingress', 'conversation:send', 'net:fetch'],+ ingress: [+ {+ route: 'chatwoot',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 262144,+ signature: {+ scheme: 'hmac-sha256',+ header: 'X-Chatwoot-Signature',+ contentTemplate: '{rawBody}',+ encoding: 'hex',+ toleranceSec: 300,+ dedupHeader: 'X-Chatwoot-Delivery',+ },+ },+ ],+});++describe('validateIngressManifest', () => {+ it('accepts a well-formed sdkVersion 1 ingress manifest', () => {+ expect(() => validateIngressManifest(baseManifest() as never)).not.toThrow();+ });++ it('refuses a plugin whose declared SDK major differs from the host major', () => {+ const m = baseManifest();+ m.sdkVersion = '2';+ expect(() => validateIngressManifest(m as never)).toThrow(/sdk.*major/i);+ expect(SUPPORTED_SDK_MAJOR).toBe(1);+ });++ it('rejects an ingress route declared without the webhook:ingress permission', () => {+ const m = baseManifest();+ m.permissions = ['conversation:send'];+ expect(() => validateIngressManifest(m as never)).toThrow(/webhook:ingress/);+ });++ it('rejects toleranceSec <= 0 (replay guard would be a no-op)', () => {+ const m = baseManifest();+ m.ingress[0].signature.toleranceSec = 0;+ expect(() => validateIngressManifest(m as never)).toThrow(/toleranceSec/);+ });++ it('rejects a duplicate route within one manifest', () => {+ const m = baseManifest();+ m.ingress.push({ ...m.ingress[0] });+ expect(() => validateIngressManifest(m as never)).toThrow(/duplicate/i);+ });+});diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 0414f7eb7..dacae1c26 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -90,6 +90,14 @@ export interface PluginManifest {// Localized dashboard text (name/description/config field titles) per locale code. English is the// base manifest + fallback. Dashboard-only; does not affect runtime behavior.i18n?: PluginI18n;++ // Integration SDK major.minor the plugin was authored against (e.g. '1' or '1.2'). Only the major+ // is enforced — see SUPPORTED_SDK_MAJOR / validateIngressManifest. Absent = treated as '1'.+ sdkVersion?: string;++ // Inbound webhook routes this plugin claims (requires the `webhook:ingress` permission). Validated+ // by validateIngressManifest; not yet wired into the loader (see that function's doc comment).+ ingress?: PluginIngressRoute[];}/** Localized overrides for a plugin's dashboard-facing text, per locale (dashboard i18n). */@@ -150,9 +158,98 @@ export const PluginCapabilityPermission = {ENGINE_READ: 'engine:read',/** `ctx.net.fetch` — SSRF-guarded outbound HTTP, scoped to the manifest `net.allow` host list. */NET_FETCH: 'net:fetch',+ /** `ctx.registerWebhook` — claim an inbound ingress route. Loader-enforced; cannot be widened by config. */+ WEBHOOK_INGRESS: 'webhook:ingress',+ /** `ctx.conversations.send` — normalized outbound send translated to MessageService. */+ CONVERSATION_SEND: 'conversation:send',} as const;export type PluginCapabilityPermission = (typeof PluginCapabilityPermission)[keyof typeof PluginCapabilityPermission];+// ============================================================================+// Integration SDK v1 — inbound webhook ingress + normalized outbound send+// ============================================================================++/** How an inbound webhook's authenticity is established before the plugin sees it. */+export interface IngressSignatureSpec {+ scheme: 'hmac-sha256' | 'shared-secret' | 'none';+ header?: string;+ // Template over which the HMAC is computed. `{rawBody}` `{timestamp}` `{id}` placeholders.+ contentTemplate?: string;+ encoding?: 'hex' | 'base64';+ prefix?: string;+ timestampHeader?: string;+ toleranceSec?: number; // when present, must be > 0 (see validateIngressManifest)+ dedupHeader?: string;+}++/** Provider webhook-verification challenge (e.g. a GET handshake on route registration). */+export interface IngressChallengeSpec {+ method: 'GET';+ tokenParam: string;+ echoParam: string;+}++/** One inbound webhook route a plugin claims. Requires the `webhook:ingress` permission. */+export interface PluginIngressRoute {+ route: string; // host prefixes it; the plugin never binds a port+ mode: 'async' | 'sync-reply';+ signature: IngressSignatureSpec;+ challenge?: IngressChallengeSpec;+ verify: 'core' | 'self';+ maxBodyBytes: number;+ // Optional: where the provider's conversation id lives, so the host can compute a per-conversation+ // ordering key (P1). Absent => the P1 lock falls back to per-instance serialization. The host never+ // needs to understand the provider's schema beyond this one pointer.+ conversationId?: { header?: string; jsonPointer?: string };+}++// Normalized outbound envelope for ctx.conversations.send (POJO across the wire).+export interface ConversationSendEnvelope {+ sessionId?: string;+ instanceId?: string;+ chatId?: string;+ type: 'text' | 'image' | 'file' | 'audio' | 'video' | 'location';+ text?: string;+ mediaUrl?: string;+ replyTo?: string;+ source?: { provider: string; externalConversationId: string };+}++/** Integration SDK major version this host supports. A plugin whose `sdkVersion` major differs is refused. */+export const SUPPORTED_SDK_MAJOR = 1;++/**+ * Validates a manifest's `ingress` declarations: SDK major compatibility, the `webhook:ingress`+ * permission, route uniqueness, and that a declared `toleranceSec` is usable (> 0 — a replay window+ * of zero or less would make the tolerance check a no-op). A manifest with no `ingress` entries is a+ * no-op. Pure validation — not yet called from the plugin loader (wiring lands in a later task).+ */+export function validateIngressManifest(manifest: PluginManifest): void {+ if (!manifest.ingress?.length) return; // no ingress declared → nothing to validate+ const declaredMajor = Number.parseInt((manifest.sdkVersion ?? '1').split('.')[0], 10);+ if (!Number.isFinite(declaredMajor) || declaredMajor !== SUPPORTED_SDK_MAJOR) {+ throw new Error(+ `Plugin ${manifest.id}: SDK major ${manifest.sdkVersion} is not supported by this host (supports ${SUPPORTED_SDK_MAJOR})`,+ );+ }+ const perms = manifest.permissions ?? [];+ if (!perms.includes(PluginCapabilityPermission.WEBHOOK_INGRESS)) {+ throw new Error(`Plugin ${manifest.id}: declares ingress routes but is missing the 'webhook:ingress' permission`);+ }+ const seen = new Set<string>();+ for (const r of manifest.ingress) {+ if (!r.route || seen.has(r.route)) {+ throw new Error(`Plugin ${manifest.id}: duplicate or empty ingress route '${r.route}'`);+ }+ seen.add(r.route);+ if (r.signature.toleranceSec !== undefined && r.signature.toleranceSec <= 0) {+ throw new Error(+ `Plugin ${manifest.id}: route '${r.route}' toleranceSec must be > 0 (a replay guard would be a no-op)`,+ );+ }+ }+}+/*** Thrown by a plugin capability when a call is rejected (missing permission, out-of-scope session,* unstarted session, etc.). Gives plugins a predictable failure instead of a raw TypeError.@@ -182,6 +279,11 @@ export interface PluginNetCapability {fetch(url: string, init?: PluginNetRequestInit): Promise<PluginNetResponse>;}+/** Normalized outbound send for a plugin — translated host-side to MessageService.sendText/reply. */+export interface PluginConversationsCapability {+ send(env: ConversationSendEnvelope): Promise<unknown>;+}+// ============================================================================// Plugin Context (passed to plugin on initialization)// ============================================================================@@ -214,6 +316,9 @@ export interface PluginContext {// SSRF-guarded outbound HTTP, scoped to the manifest `net.allow` host list.net: PluginNetCapability;++ // Normalized outbound send, translated to MessageService. Requires `conversation:send`.+ conversations: PluginConversationsCapability;}export interface PluginLogger {diff --git a/src/core/plugins/plugins.module.ts b/src/core/plugins/plugins.module.tsindex d05689224..1cdc1324e 100644--- a/src/core/plugins/plugins.module.ts+++ b/src/core/plugins/plugins.module.ts@@ -1,10 +1,17 @@import { Global, Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';import { PluginLoaderService } from './plugin-loader.service';import { PluginStorageService } from './plugin-storage.service';+import { ConversationMapping } from '../../modules/integration/entities/conversation-mapping.entity';+import { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';@Global() // Make plugin services available everywhere@Module({- providers: [PluginStorageService, PluginLoaderService],+ imports: [TypeOrmModule.forFeature([ConversationMapping], 'data')],+ // ConversationMappingService is resolved lazily (ModuleRef) by PluginLoaderService, the same+ // pattern used for MessageService/SessionService, to avoid a static import edge back into this+ // module's graph — so it only needs to be a provider here, not re-exported.+ providers: [PluginStorageService, PluginLoaderService, ConversationMappingService],exports: [PluginLoaderService, PluginStorageService],})export class PluginsModule {}diff --git a/src/core/plugins/sandbox/capability-router.spec.ts b/src/core/plugins/sandbox/capability-router.spec.tsindex 36652d8be..906dc6406 100644--- a/src/core/plugins/sandbox/capability-router.spec.ts+++ b/src/core/plugins/sandbox/capability-router.spec.ts@@ -22,6 +22,9 @@ function makeContext() {net: {fetch: jest.fn().mockResolvedValue({ ok: true, status: 200, statusText: 'OK', headers: {}, body: 'x' }),},+ conversations: {+ send: jest.fn().mockResolvedValue({ id: 'm3' }),+ },};}diff --git a/src/core/plugins/sandbox/capability-router.ts b/src/core/plugins/sandbox/capability-router.tsindex 44e846f78..ddb321b71 100644--- a/src/core/plugins/sandbox/capability-router.ts+++ b/src/core/plugins/sandbox/capability-router.ts@@ -1,7 +1,11 @@-import { PluginContext } from '../plugin.interfaces';+import { ConversationSendEnvelope, PluginContext } from '../plugin.interfaces';/** The subset of the plugin context a sandboxed plugin reaches across the bridge. */-export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'storage' | 'net'>;+export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'storage' | 'net'> & {+ conversations: {+ send(env: ConversationSendEnvelope): Promise<unknown>;+ };+};/*** Dispatch a worker-initiated capability `verb` to the live, permission-enforcing context the loader@@ -43,6 +47,8 @@ export async function dispatchCapabilityVerb(return context.storage.list(args[0] as string | undefined);case 'net.fetch':return context.net.fetch(s(0), args[1] as Parameters<typeof context.net.fetch>[1]);+ case 'conversation.send':+ return context.conversations.send(args[0] as ConversationSendEnvelope);default:throw new Error(`Unknown capability verb: ${verb}`);}diff --git a/src/core/plugins/sandbox/conversation-send.spec.ts b/src/core/plugins/sandbox/conversation-send.spec.tsnew file mode 100644index 000000000..894fecc0b--- /dev/null+++ b/src/core/plugins/sandbox/conversation-send.spec.ts@@ -0,0 +1,12 @@+import { dispatchCapabilityVerb } from './capability-router';++describe('dispatchCapabilityVerb conversation.send', () => {+ it('routes conversation.send to context.conversations.send with the envelope POJO', async () => {+ const env = { type: 'text', text: 'hi', source: { provider: 'chatwoot', externalConversationId: '42' } };+ const send = jest.fn().mockResolvedValue({ id: 'm1' });+ const context = { conversations: { send } } as never;+ const result = await dispatchCapabilityVerb(context, 'conversation.send', [env]);+ expect(send).toHaveBeenCalledWith(env);+ expect(result).toEqual({ id: 'm1' });+ });+});diff --git a/src/core/plugins/sandbox/dispatch-webhook.spec.ts b/src/core/plugins/sandbox/dispatch-webhook.spec.tsnew file mode 100644index 000000000..4f9260b4a--- /dev/null+++ b/src/core/plugins/sandbox/dispatch-webhook.spec.ts@@ -0,0 +1,103 @@+import { PluginWorkerHost } from './plugin-worker-host';++/**+ * A fake worker channel mirroring the IPC surface the host talks to. It conforms to+ * PluginWorkerChannel so the real PluginWorkerHost constructor accepts it (channel-only), and lets a+ * test drive the worker side: capture posted messages, replay a `webhook-result`, or simulate a crash.+ */+function fakeChannel() {+ const handlers: { message?: (m: unknown) => void; exit?: (code: number) => void } = {};+ const posted: unknown[] = [];+ return {+ posted,+ postMessage: (m: unknown) => {+ posted.push(m);+ },+ onMessage: (cb: (m: unknown) => void) => {+ handlers.message = cb;+ },+ onExit: (cb: (code: number) => void) => {+ handlers.exit = cb;+ },+ terminate: () => Promise.resolve(),+ emitMessage: (m: unknown) => handlers.message?.(m),+ emitExit: (code: number) => handlers.exit?.(code),+ };+}++const webhookOptions = () => ({+ instanceId: 'i',+ route: 'chatwoot',+ method: 'POST',+ headers: {},+ query: {},+ body: '{}',+ rawBody: '{}',+ verified: true,+ deliveryId: 'd1',+ timeoutMs: 1000,+});++describe('PluginWorkerHost.dispatchWebhook', () => {+ it('resolves with the worker webhook-result when the worker replies', async () => {+ const channel = fakeChannel();+ const host = new PluginWorkerHost(channel as never);+ const promise = host.dispatchWebhook(webhookOptions());++ const sent = channel.posted.find(m => (m as { kind: string }).kind === 'webhook') as { id: number };+ channel.emitMessage({ kind: 'webhook-result', id: sent.id, status: 200, body: 'ok' });++ await expect(promise).resolves.toMatchObject({ ok: true, status: 200, body: 'ok' });+ });++ it('fail-opens to 504 when the worker never replies before the timeout', async () => {+ jest.useFakeTimers();+ try {+ const host = new PluginWorkerHost(fakeChannel() as never);+ const promise = host.dispatchWebhook(webhookOptions());++ jest.advanceTimersByTime(1001);++ await expect(promise).resolves.toMatchObject({ ok: false, status: 504 });+ } finally {+ jest.useRealTimers();+ }+ });++ it('invokes onTimeout when the fail-open timeout fires', async () => {+ jest.useFakeTimers();+ try {+ const onTimeout = jest.fn();+ const host = new PluginWorkerHost(fakeChannel() as never);+ const promise = host.dispatchWebhook({ ...webhookOptions(), onTimeout });++ jest.advanceTimersByTime(1001);+ await promise;++ expect(onTimeout).toHaveBeenCalledTimes(1);+ } finally {+ jest.useRealTimers();+ }+ });++ it('drains pending webhooks to 502 when the worker crashes mid-request', async () => {+ const channel = fakeChannel();+ const host = new PluginWorkerHost(channel as never);+ const promise = host.dispatchWebhook({ ...webhookOptions(), timeoutMs: 100000 });++ channel.emitExit(1);++ await expect(promise).resolves.toMatchObject({ ok: false, status: 502 });+ });++ it('surfaces a worker handler error as ok:false with the reported status', async () => {+ const channel = fakeChannel();+ const host = new PluginWorkerHost(channel as never);+ const promise = host.dispatchWebhook(webhookOptions());++ const sent = channel.posted.find(m => (m as { kind: string }).kind === 'webhook') as { id: number };+ channel.emitMessage({ kind: 'webhook-result', id: sent.id, status: 500, error: 'boom' });++ await expect(promise).resolves.toMatchObject({ ok: false, status: 500, error: 'boom' });+ });+});diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.tsindex b7225891e..8dfa39f0b 100644--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts@@ -169,8 +169,8 @@ describe('PluginWorkerHost', () => {.fn().mockImplementationOnce(() => new Promise(r => (resolveFirst = r))) // first cap hangs, holding the slot.mockResolvedValue({ ok: true });- // maxInFlightCaps = 1 (6th positional arg)- new PluginWorkerHost(ch, dispatcher, undefined, undefined, undefined, 1);+ // maxInFlightCaps = 1 (7th positional arg)+ new PluginWorkerHost(ch, dispatcher, undefined, undefined, undefined, undefined, 1);ch.reply({ kind: 'cap', id: 1, verb: 'messages.sendText', args: [] }); // takes the only slotawait flush();@@ -285,7 +285,7 @@ describe('PluginWorkerHost', () => {it('routes a worker log message to onLog', async () => {const ch = new FakeChannel();const onLog = jest.fn();- new PluginWorkerHost(ch, undefined, undefined, onLog);+ new PluginWorkerHost(ch, undefined, undefined, undefined, onLog);ch.reply({ kind: 'log', level: 'warn', message: 'heads up', meta: { x: 1 } });await flush();@@ -413,7 +413,7 @@ describe('PluginWorkerHost', () => {return { messageId: 'wamid' };};- const host = new PluginWorkerHost(ch, capDispatcher, undefined, undefined, (events, run) =>+ const host = new PluginWorkerHost(ch, capDispatcher, undefined, undefined, undefined, (events, run) =>hm.runInFlight(events as HookEvent[], run),);diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.tsindex 61deea54a..ea73607e3 100644--- a/src/core/plugins/sandbox/plugin-worker-host.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.ts@@ -31,6 +31,19 @@ export class PluginWorkerHost {number,{ resolve: (result: { continue: boolean; data?: unknown }) => void; timer: ReturnType<typeof setTimeout> }>();+ private readonly webhookPending = new Map<+ number,+ {+ resolve: (result: {+ status: number;+ headers?: Record<string, string>;+ body?: string;+ ok: boolean;+ error?: string;+ }) => void;+ timer: ReturnType<typeof setTimeout>;+ }+ >();private readonly healthPending = new Map<number,{ resolve: (result: { healthy: boolean; message?: string }) => void; timer: ReturnType<typeof setTimeout> }@@ -52,6 +65,9 @@ export class PluginWorkerHost {// Called when the worker subscribes a handler to an event, so the host can register a shim with// the hook manager that dispatches into the worker.private readonly onHookSubscribe?: (event: string, priority?: number) => void,+ // Called when the worker claims an ingress route (registered a webhook handler for it), so the+ // host can record it against the manifest-declared routes (mirrors onHookSubscribe for ingress).+ private readonly onWebhookSubscribe?: (route: string) => void,// Routes a worker plugin's ctx.logger.* call to the host's per-plugin logger.private readonly onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,// Runs a worker-initiated capability call inside the in-flight hook context, so a capability that@@ -120,6 +136,51 @@ export class PluginWorkerHost {});}+ /**+ * Dispatch a verified inbound webhook to the worker and await its handler result. Cloned from+ * dispatchHook: bounded by `timeoutMs`, and fail-open — a slow or wedged worker resolves a default+ * 504 (the provider was already ack'd in async mode) rather than hanging the HTTP request. A+ * mid-request worker crash is drained to 502 in handleExit, so the request never hangs forever.+ */+ dispatchWebhook(options: {+ instanceId: string;+ route: string;+ method: string;+ headers: Record<string, string>;+ query: Record<string, string>;+ body: string;+ rawBody: string;+ verified: boolean;+ deliveryId: string;+ sessionId?: string;+ timeoutMs: number;+ onTimeout?: () => void;+ }): Promise<{ status: number; headers?: Record<string, string>; body?: string; ok: boolean; error?: string }> {+ const id = this.nextId++;+ return new Promise(resolve => {+ const timer = setTimeout(() => {+ this.webhookPending.delete(id);+ options.onTimeout?.();+ resolve({ ok: false, status: 504 }); // fail-open: provider already ack'd in async mode+ }, options.timeoutMs);+ this.webhookPending.set(id, { resolve, timer });+ this.channel.postMessage({+ kind: 'webhook',+ id,+ instanceId: options.instanceId,+ route: options.route,+ method: options.method,+ headers: options.headers,+ query: options.query,+ body: options.body,+ rawBody: options.rawBody,+ verified: options.verified,+ deliveryId: options.deliveryId,+ sessionId: options.sessionId,+ });+ });+ }+/*** Load the plugin module in the worker; resolves once it reports `ready`, rejects if it errors.* When `timeoutMs` is given, a worker that never reports ready rejects the call (the caller then@@ -229,6 +290,9 @@ export class PluginWorkerHost {case 'hook-subscribe':this.onHookSubscribe?.(message.event, message.priority);break;+ case 'webhook-subscribe':+ this.onWebhookSubscribe?.(message.route);+ break;case 'log':this.onLog?.(message.level, message.message, message.meta);break;@@ -242,6 +306,20 @@ export class PluginWorkerHost {waiter.resolve(result);break;}+ case 'webhook-result': {+ const waiter = this.webhookPending.get(message.id);+ if (!waiter) return;+ this.webhookPending.delete(message.id);+ clearTimeout(waiter.timer);+ waiter.resolve({+ ok: message.error == null,+ status: message.status,+ headers: message.headers,+ body: message.body,+ error: message.error,+ });+ break;+ }case 'health-result': {const waiter = this.healthPending.get(message.id);if (!waiter) return;@@ -315,6 +393,14 @@ export class PluginWorkerHost {resolve({ continue: true });});this.hookPending.clear();+ // Drain in-flight webhooks: a mid-request worker crash must return 502, never hang the HTTP+ // request. (The per-request timeout would eventually fail-open to 504, but the request should not+ // wait the full window when the worker is already known dead.)+ this.webhookPending.forEach(({ resolve, timer }) => {+ clearTimeout(timer);+ resolve({ ok: false, status: 502 });+ });+ this.webhookPending.clear();}private drain<T>(waiters: T[], fn: (w: T) => void): void {diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.tsindex 92723fc45..e86cae076 100644--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts@@ -191,7 +191,7 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {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) =>+ const host = new PluginWorkerHost(makeChannel(), undefined, undefined, undefined, (level, message, meta) =>logs.push({ level, message, meta }),);diff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.tsindex dde5e267d..79439b9af 100644--- a/src/core/plugins/sandbox/protocol.ts+++ b/src/core/plugins/sandbox/protocol.ts@@ -40,7 +40,25 @@ export type HostToWorkerMessage =// 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.- | { kind: 'health-check'; id: number };+ | { kind: 'health-check'; id: number }+ // Dispatch a verified inbound webhook to the worker for a route it subscribed to (webhook-subscribe).+ // `body`/`rawBody` are buffered host-side to a string, like PluginNetResponse.body. `verified`+ // reflects the host's signature check (see PluginIngressRoute.verify); the worker still re-checks+ // when `verify: 'self'`. The worker replies with webhook-result.+ | {+ kind: 'webhook';+ id: number;+ instanceId: string;+ route: string;+ method: string;+ headers: Record<string, string>;+ query: Record<string, string>;+ body: string;+ rawBody: string;+ verified: boolean;+ deliveryId: string;+ sessionId?: string;+ };export type WorkerToHostMessage =| { kind: 'ready' }@@ -57,6 +75,18 @@ export type WorkerToHostMessage =| { kind: 'log'; level: PluginLogLevel; message: string; meta?: Record<string, unknown> }// The worker plugin's healthCheck() result for a host health-check request.| { kind: 'health-result'; id: number; healthy: boolean; message?: string }+ // The worker claims an ingress route declared in its manifest (registered a webhook handler for it).+ | { kind: 'webhook-subscribe'; route: string }+ // The worker's response to a dispatched webhook — the host relays this to the caller (sync-reply+ // mode) or discards it (async mode). `error` set = the handler threw.+ | {+ kind: 'webhook-result';+ id: number;+ status: number;+ headers?: Record<string, string>;+ body?: string;+ error?: string;+ }| { kind: 'error'; error: string };/**diff --git a/src/core/plugins/sandbox/worker-bootstrap.ts b/src/core/plugins/sandbox/worker-bootstrap.tsindex 6b3fbfa9d..2ecfb186f 100644--- a/src/core/plugins/sandbox/worker-bootstrap.ts+++ b/src/core/plugins/sandbox/worker-bootstrap.ts@@ -2,6 +2,7 @@ import { parentPort } from 'worker_threads';import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';import { WorkerCapabilityClient, buildSandboxContext } from './worker-capability';import { WorkerHookRegistry, WorkerHookHandler, hookConfigStore } from './worker-hooks';+import { WebhookRegistry, WebhookHandler } from './worker-webhooks';/*** Worker entry for an untrusted plugin. Loads the plugin module and drives its lifecycle in response@@ -29,6 +30,7 @@ const errorMessage = (error: unknown): string => (error instanceof Error ? errorconst capClient = new WorkerCapabilityClient(send);const hookRegistry = new WorkerHookRegistry(send);+const webhookRegistry = new WebhookRegistry(send);// ctx.logger proxy: forwards to the host's per-plugin logger (the same one in-process plugins use).const logger = {@@ -57,6 +59,10 @@ port.on('message', (message: HostToWorkerMessage) => {void hookRegistry.handleHook(message);return;}+ if (message.kind === 'webhook') {+ void webhookRegistry.handleWebhook(message);+ return;+ }void handle(message);});@@ -80,6 +86,7 @@ async function handle(message: HostToWorkerMessage): Promise<void> {...buildSandboxContext(capClient),registerHook: (event: string, handler: WorkerHookHandler, priority?: number) =>hookRegistry.register(event, handler, priority),+ registerWebhook: (route: string, handler: WebhookHandler) => webhookRegistry.register(route, handler),};send({ kind: 'ready' });} catch (error) {diff --git a/src/core/plugins/sandbox/worker-capability.ts b/src/core/plugins/sandbox/worker-capability.tsindex 89095cf86..501b20755 100644--- a/src/core/plugins/sandbox/worker-capability.ts+++ b/src/core/plugins/sandbox/worker-capability.ts@@ -1,4 +1,5 @@import { WorkerToHostMessage, HostToWorkerMessage } from './protocol';+import { ConversationSendEnvelope } from '../plugin.interfaces';/*** Worker-side correlation for capability calls. Each `call` posts a `cap` request and resolves when@@ -49,6 +50,9 @@ export interface SandboxCapabilityContext {net: {fetch(url: string, init?: unknown): Promise<unknown>;};+ conversations: {+ send(env: ConversationSendEnvelope): Promise<unknown>;+ };}/** Build the proxy capability context handed to a sandboxed plugin in the worker. */@@ -75,5 +79,8 @@ export function buildSandboxContext(client: WorkerCapabilityClient): SandboxCapanet: {fetch: (url, init) => client.call('net.fetch', [url, init]),},+ conversations: {+ send: env => client.call('conversation.send', [env]),+ },};}diff --git a/src/core/plugins/sandbox/worker-webhooks.ts b/src/core/plugins/sandbox/worker-webhooks.tsnew file mode 100644index 000000000..73cb32c2f--- /dev/null+++ b/src/core/plugins/sandbox/worker-webhooks.ts@@ -0,0 +1,72 @@+import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';++/**+ * The verified inbound webhook a sandboxed plugin's handler sees. Mirrors the `webhook` wire message+ * minus the correlation `id` and `route` (the registry routes on `route` before invoking the handler).+ */+export interface WebhookRequest {+ instanceId: string;+ method: string;+ headers: Record<string, string>;+ query: Record<string, string>;+ body: string;+ rawBody: string;+ verified: boolean;+ deliveryId: string;+ sessionId?: string;+}++export type WebhookResponse = { status?: number; headers?: Record<string, string>; body?: string };+export type WebhookHandler = (req: WebhookRequest) => Promise<WebhookResponse | void> | WebhookResponse | void;++/**+ * Worker-side webhook handling, mirroring WorkerHookRegistry. A sandboxed plugin registers one+ * handler per ingress route (via ctx.registerWebhook). The registry subscribes the host to the route+ * the first time it sees a handler for it, and on a `webhook` message runs the handler and replies+ * with `webhook-result` — a thrown handler becomes a 500 error result, an unknown route a 404.+ */+export class WebhookRegistry {+ private readonly handlers = new Map<string, WebhookHandler>();++ constructor(private readonly post: (message: WorkerToHostMessage) => void) {}++ register(route: string, handler: WebhookHandler): void {+ this.handlers.set(route, handler);+ this.post({ kind: 'webhook-subscribe', route });+ }++ async handleWebhook(message: Extract<HostToWorkerMessage, { kind: 'webhook' }>): Promise<void> {+ const handler = this.handlers.get(message.route);+ if (!handler) {+ 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),+ });+ }+ }+}diff --git a/src/core/plugins/webhook-subscribe.spec.ts b/src/core/plugins/webhook-subscribe.spec.tsnew file mode 100644index 000000000..365eb2155--- /dev/null+++ b/src/core/plugins/webhook-subscribe.spec.ts@@ -0,0 +1,90 @@+import { makeOnWebhookSubscribe } from './webhook-subscribe.util';++describe('onWebhookSubscribe hardening', () => {+ const declaredRoutes = new Set(['chatwoot']);++ it('registers a declared route once and dedups repeats', () => {+ const subscribed = new Set<string>();+ const on = makeOnWebhookSubscribe({+ pluginId: 'p',+ declaredRoutes,+ hasPermission: true,+ subscribed,+ maxRoutes: 8,+ warn: jest.fn(),+ });++ on('chatwoot');+ on('chatwoot');++ expect([...subscribed]).toEqual(['chatwoot']);+ });++ it('silently drops a route the manifest never declared', () => {+ const subscribed = new Set<string>();+ makeOnWebhookSubscribe({+ pluginId: 'p',+ declaredRoutes,+ hasPermission: true,+ subscribed,+ maxRoutes: 8,+ warn: jest.fn(),+ })('unknown');++ expect(subscribed.size).toBe(0);+ });++ it('warns at most once about undeclared routes so a flood is not a log-flood vector', () => {+ const subscribed = new Set<string>();+ const warn = jest.fn();+ const on = makeOnWebhookSubscribe({+ pluginId: 'p',+ declaredRoutes,+ hasPermission: true,+ subscribed,+ maxRoutes: 8,+ warn,+ });++ on('x');+ on('y');+ on('z');++ expect(warn).toHaveBeenCalledTimes(1);+ });++ it('silently drops all routes when the manifest lacks webhook:ingress', () => {+ const subscribed = new Set<string>();+ const warn = jest.fn();+ makeOnWebhookSubscribe({+ pluginId: 'p',+ declaredRoutes,+ hasPermission: false,+ subscribed,+ maxRoutes: 8,+ warn,+ })('chatwoot');++ expect(subscribed.size).toBe(0);+ expect(warn).not.toHaveBeenCalled();+ });++ it('size-caps the subscribed set', () => {+ const subscribed = new Set<string>();+ const routes = new Set(['a', 'b', 'c']);+ const on = makeOnWebhookSubscribe({+ pluginId: 'p',+ declaredRoutes: routes,+ hasPermission: true,+ subscribed,+ maxRoutes: 2,+ warn: jest.fn(),+ });++ on('a');+ on('b');+ on('c');++ expect(subscribed.size).toBe(2);+ });+});diff --git a/src/core/plugins/webhook-subscribe.util.ts b/src/core/plugins/webhook-subscribe.util.tsnew file mode 100644index 000000000..5cbc3f7f0--- /dev/null+++ b/src/core/plugins/webhook-subscribe.util.ts@@ -0,0 +1,39 @@+/**+ * Pure guard logic for a sandboxed worker's `webhook-subscribe` messages, mirroring the loader's+ * onHookSubscribe hardening. The IPC boundary is untrusted: a hostile/buggy worker can post+ * `webhook-subscribe` with an undeclared route, the same route repeatedly, or a flood of fabricated+ * routes. Without guards each call records a live host-side ingress registration (unbounded growth).+ *+ * Three guards, all keyed off the manifest (which the operator authored, not the worker): drop when+ * the manifest lacks `webhook:ingress` (silent — the plugin has no ingress at all), drop an+ * undeclared route (warn at most once so a flood isn't a log-flood vector), dedup, and a size cap.+ */+export interface OnWebhookSubscribeDeps {+ pluginId: string;+ declaredRoutes: Set<string>; // routes from manifest.ingress[].route+ hasPermission: boolean; // manifest declares webhook:ingress+ subscribed: Set<string>;+ maxRoutes: number;+ warn: (message: string, meta: Record<string, unknown>) => void;+}++export function makeOnWebhookSubscribe(deps: OnWebhookSubscribeDeps): (route: string) => void {+ let unknownRouteWarned = false;+ return (route: string): void => {+ if (!deps.hasPermission) return; // no ingress permission => the plugin claims no routes at all+ if (!deps.declaredRoutes.has(route)) {+ if (!unknownRouteWarned) {+ unknownRouteWarned = true; // warn at most once per plugin so a flood isn't a log-flood vector+ deps.warn(`Sandboxed plugin ${deps.pluginId} subscribed to an undeclared ingress route; ignoring`, {+ pluginId: deps.pluginId,+ route,+ action: 'sandbox_unknown_ingress_route',+ });+ }+ return;+ }+ if (deps.subscribed.has(route)) return;+ if (deps.subscribed.size >= deps.maxRoutes) return; // belt-and-suspenders cap+ deps.subscribed.add(route);+ };+}diff --git a/src/database/add-integration-fabric.spec.ts b/src/database/add-integration-fabric.spec.tsnew file mode 100644index 000000000..0d1f0df80--- /dev/null+++ b/src/database/add-integration-fabric.spec.ts@@ -0,0 +1,42 @@+import { DataSource } from 'typeorm';+import { AddIntegrationFabric1781900000000 } from './migrations/1781900000000-AddIntegrationFabric';++describe('AddIntegrationFabric migration (sqlite)', () => {+ let ds: DataSource;+ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [], migrations: [] });+ await ds.initialize();+ });+ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ });++ it('creates all four tables and is idempotent, then drops cleanly on down()', async () => {+ const runner = ds.createQueryRunner();+ const mig = new AddIntegrationFabric1781900000000();+ await mig.up(runner);+ await mig.up(runner); // idempotent: hasTable guard must not throw on re-run+ for (const t of ['plugin_instances', 'conversation_mappings', 'ingress_events', 'integration_delivery_failures']) {+ expect(await runner.hasTable(t)).toBe(true);+ }+ await mig.down(runner);+ for (const t of ['plugin_instances', 'conversation_mappings', 'ingress_events', 'integration_delivery_failures']) {+ expect(await runner.hasTable(t)).toBe(false);+ }+ await runner.release();+ });++ it('enforces UNIQUE(instanceId, providerDeliveryId) on ingress_events', async () => {+ const runner = ds.createQueryRunner();+ await new AddIntegrationFabric1781900000000().up(runner);+ await runner.query(+ `INSERT INTO "ingress_events" ("id","instanceId","pluginId","providerDeliveryId","route","payload","createdAt") VALUES ('a','inst','plug','d1','chatwoot','{}',datetime('now'))`,+ );+ await expect(+ runner.query(+ `INSERT INTO "ingress_events" ("id","instanceId","pluginId","providerDeliveryId","route","payload","createdAt") VALUES ('b','inst','plug','d1','chatwoot','{}',datetime('now'))`,+ ),+ ).rejects.toThrow();+ await runner.release();+ });+});diff --git a/src/database/data-source.ts b/src/database/data-source.tsindex 1d0f7f225..8602c65ab 100644--- a/src/database/data-source.ts+++ b/src/database/data-source.ts@@ -23,6 +23,7 @@ const sqliteDataSource = new DataSource({sourceGlob('..', 'modules', 'message', '**', '*.entity{.ts,.js}'),sourceGlob('..', 'modules', 'template', '**', '*.entity{.ts,.js}'),sourceGlob('..', 'engine', '**', '*.entity{.ts,.js}'),+ sourceGlob('..', 'modules', 'integration', '**', '*.entity{.ts,.js}'),],migrations: [sourceGlob('migrations', '*{.ts,.js}')],synchronize: false,@@ -46,6 +47,7 @@ export const postgresDataSource = new DataSource({sourceGlob('..', 'modules', 'message', '**', '*.entity{.ts,.js}'),sourceGlob('..', 'modules', 'template', '**', '*.entity{.ts,.js}'),sourceGlob('..', 'engine', '**', '*.entity{.ts,.js}'),+ sourceGlob('..', 'modules', 'integration', '**', '*.entity{.ts,.js}'),],migrations: [sourceGlob('migrations', '*{.ts,.js}')],synchronize: false, // Never auto-sync in productiondiff --git a/src/database/migrations/1781900000000-AddIntegrationFabric.ts b/src/database/migrations/1781900000000-AddIntegrationFabric.tsnew file mode 100644index 000000000..0dffa07f8--- /dev/null+++ b/src/database/migrations/1781900000000-AddIntegrationFabric.ts@@ -0,0 +1,81 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++export class AddIntegrationFabric1781900000000 implements MigrationInterface {+ name = 'AddIntegrationFabric1781900000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ const isPostgres = queryRunner.connection.options.type === 'postgres';+ const ts = isPostgres ? 'timestamp' : 'datetime';+ const now = isPostgres ? 'NOW()' : "(datetime('now'))";+ const boolTrue = isPostgres ? 'true' : '1';+ const boolFalse = isPostgres ? 'false' : '0';++ if (!(await queryRunner.hasTable('plugin_instances'))) {+ await queryRunner.query(+ `CREATE TABLE "plugin_instances" (` ++ `"id" varchar PRIMARY KEY NOT NULL, "pluginId" varchar NOT NULL, "instanceId" varchar NOT NULL, ` ++ `"sessionScope" varchar, "secret" varchar NOT NULL, "verifyToken" varchar, "config" text, ` ++ `"enabled" boolean NOT NULL DEFAULT ${boolTrue}, ` ++ `"createdAt" ${ts} NOT NULL DEFAULT ${now}, "updatedAt" ${ts} NOT NULL DEFAULT ${now})`,+ );+ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_plugin_instances_plugin_instance" ON "plugin_instances" ("pluginId", "instanceId")`,+ );+ }++ if (!(await queryRunner.hasTable('conversation_mappings'))) {+ await queryRunner.query(+ `CREATE TABLE "conversation_mappings" (` ++ `"id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "chatId" varchar NOT NULL, ` ++ `"pluginId" varchar NOT NULL, "instanceId" varchar NOT NULL, "providerConversationId" varchar NOT NULL, ` ++ `"handoverState" varchar NOT NULL DEFAULT 'bot', "metadata" text, ` ++ `"updatedAt" ${ts} NOT NULL DEFAULT ${now})`,+ );+ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_conversation_mappings_forward" ON "conversation_mappings" ("sessionId", "chatId", "pluginId", "instanceId")`,+ );+ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_conversation_mappings_reverse" ON "conversation_mappings" ("pluginId", "instanceId", "providerConversationId")`,+ );+ }++ if (!(await queryRunner.hasTable('ingress_events'))) {+ await queryRunner.query(+ `CREATE TABLE "ingress_events" (` ++ `"id" varchar PRIMARY KEY NOT NULL, "instanceId" varchar NOT NULL, "pluginId" varchar NOT NULL, ` ++ `"providerDeliveryId" varchar NOT NULL, "route" varchar NOT NULL, "payload" text NOT NULL, ` ++ `"sessionId" varchar, "createdAt" ${ts} NOT NULL DEFAULT ${now})`,+ );+ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_ingress_events_instance_delivery" ON "ingress_events" ("instanceId", "providerDeliveryId")`,+ );+ await queryRunner.query(`CREATE INDEX "IDX_ingress_events_createdAt" ON "ingress_events" ("createdAt")`);+ }++ if (!(await queryRunner.hasTable('integration_delivery_failures'))) {+ await queryRunner.query(+ `CREATE TABLE "integration_delivery_failures" (` ++ `"id" varchar PRIMARY KEY NOT NULL, "direction" varchar NOT NULL, "pluginId" varchar NOT NULL, ` ++ `"instanceId" varchar NOT NULL, "sessionId" varchar, "deliveryId" varchar, "attempts" integer NOT NULL, ` ++ `"lastError" text NOT NULL, "payload" text, "redriven" boolean NOT NULL DEFAULT ${boolFalse}, ` ++ `"createdAt" ${ts} NOT NULL DEFAULT ${now})`,+ );+ await queryRunner.query(+ `CREATE INDEX "IDX_integration_delivery_failures_instance" ON "integration_delivery_failures" ("pluginId", "instanceId")`,+ );+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_integration_delivery_failures_instance"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_ingress_events_createdAt"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_ingress_events_instance_delivery"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_conversation_mappings_reverse"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_conversation_mappings_forward"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_plugin_instances_plugin_instance"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "integration_delivery_failures"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "ingress_events"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "conversation_mappings"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "plugin_instances"`);+ }+}diff --git a/src/main.ts b/src/main.tsindex 59ebb4000..d1a0b4d30 100644--- a/src/main.ts+++ b/src/main.ts@@ -71,7 +71,17 @@ async function bootstrap() {// Cap request body size (DoS hardening). Media sends carry base64 in the JSON body,// so the default is generous; tune with BODY_SIZE_LIMIT.const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);- app.use(json({ limit: bodyLimit }));+ // The `verify` callback stashes the EXACT bytes json() received on req.rawBody, byte-identical to+ // what a provider signed, so the @Public ingress controller can HMAC-verify over the raw body+ // (JSON.stringify(req.body) is NOT byte-identical). Cheap for every route; non-ingress routes ignore it.+ app.use(+ json({+ limit: bodyLimit,+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {+ req.rawBody = buf;+ },+ }),+ );app.use(urlencoded({ extended: true, limit: bodyLimit }));// Enable shutdown hooks for graceful shutdowndiff --git a/src/modules/integration/__fixtures__/chatwoot-message_created.json b/src/modules/integration/__fixtures__/chatwoot-message_created.jsonnew file mode 100644index 000000000..ab413c6b7--- /dev/null+++ b/src/modules/integration/__fixtures__/chatwoot-message_created.json@@ -0,0 +1,8 @@+{+ "event": "message_created",+ "message_type": "outgoing",+ "private": false,+ "content": "Hello from a human agent",+ "conversation": { "id": 42 },+ "account": { "id": 1 }+}diff --git a/src/modules/integration/conversation-mapping.service.spec.ts b/src/modules/integration/conversation-mapping.service.spec.tsnew file mode 100644index 000000000..3ae47fcd5--- /dev/null+++ b/src/modules/integration/conversation-mapping.service.spec.ts@@ -0,0 +1,53 @@+import { DataSource } from 'typeorm';+import { ConversationMapping } from './entities/conversation-mapping.entity';+import { ConversationMappingService, MappingKey } from './conversation-mapping.service';+import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';++describe('ConversationMappingService', () => {+ let ds: DataSource;+ let service: ConversationMappingService;+ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [ConversationMapping], migrations: [] });+ await ds.initialize();+ const runner = ds.createQueryRunner();+ await new AddIntegrationFabric1781900000000().up(runner);+ await runner.release();+ service = new ConversationMappingService(ds.getRepository(ConversationMapping));+ });+ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ });++ const key: MappingKey = { sessionId: 'sess-1', chatId: 'chat-1', pluginId: 'chatwoot', instanceId: 'acct1' };++ it('upserts a mapping then get(forwardKey) returns it with a non-empty id', async () => {+ await service.upsert(key, 'conv-1');+ const found = await service.get(key);+ expect(found).not.toBeNull();+ expect(found?.id).toEqual(expect.any(String));+ expect(found?.id.length).toBeGreaterThan(0);+ expect(found?.providerConversationId).toBe('conv-1');+ });++ it('getByProvider reverse lookup returns the same row', async () => {+ await service.upsert(key, 'conv-1');+ const forward = await service.get(key);+ const reverse = await service.getByProvider(key.pluginId, key.instanceId, 'conv-1');+ expect(reverse).not.toBeNull();+ expect(reverse?.id).toBe(forward?.id);+ });++ it('upserting again on the same forward key updates providerConversationId instead of inserting a duplicate', async () => {+ await service.upsert(key, 'conv-1');+ const first = await service.get(key);++ await service.upsert(key, 'conv-2');+ const second = await service.get(key);++ expect(second?.id).toBe(first?.id);+ expect(second?.providerConversationId).toBe('conv-2');++ const stale = await service.getByProvider(key.pluginId, key.instanceId, 'conv-1');+ expect(stale).toBeNull();+ });+});diff --git a/src/modules/integration/conversation-mapping.service.ts b/src/modules/integration/conversation-mapping.service.tsnew file mode 100644index 000000000..addb38888--- /dev/null+++ b/src/modules/integration/conversation-mapping.service.ts@@ -0,0 +1,44 @@+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { QueryDeepPartialEntity, Repository } from 'typeorm';+import { ConversationMapping, HandoverState } from './entities/conversation-mapping.entity';++export interface MappingKey {+ sessionId: string;+ chatId: string;+ pluginId: string;+ instanceId: string;+}++@Injectable()+export class ConversationMappingService {+ constructor(@InjectRepository(ConversationMapping, 'data') private readonly repo: Repository<ConversationMapping>) {}++ async upsert(key: MappingKey, providerConversationId: string, patch?: Partial<ConversationMapping>): Promise<void> {+ const existing = await this.repo.findOne({ where: key });+ if (existing) {+ await this.repo.update({ id: existing.id }, {+ providerConversationId,+ ...patch,+ } as QueryDeepPartialEntity<ConversationMapping>);+ return;+ }+ await this.repo.save(this.repo.create({ ...key, providerConversationId, handoverState: 'bot', ...patch }));+ }++ get(key: MappingKey): Promise<ConversationMapping | null> {+ return this.repo.findOne({ where: key });+ }++ getByProvider(+ pluginId: string,+ instanceId: string,+ providerConversationId: string,+ ): Promise<ConversationMapping | null> {+ return this.repo.findOne({ where: { pluginId, instanceId, providerConversationId } });+ }++ async setHandover(id: string, state: HandoverState): Promise<void> {+ await this.repo.update({ id }, { handoverState: state });+ }+}diff --git a/src/modules/integration/entities/conversation-mapping.entity.ts b/src/modules/integration/entities/conversation-mapping.entity.tsnew file mode 100644index 000000000..1667330aa--- /dev/null+++ b/src/modules/integration/entities/conversation-mapping.entity.ts@@ -0,0 +1,38 @@+import { Column, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';+import { jsonColumnType } from '../../../common/utils/column-types';++export type HandoverState = 'bot' | 'human' | 'closed';++// Maps a WA chat to a provider conversation, both directions. sessionId is non-FK provenance+// (a mapping outlives a session; last-write-wins).+@Entity('conversation_mappings')+@Index('UQ_conversation_mappings_forward', ['sessionId', 'chatId', 'pluginId', 'instanceId'], { unique: true })+@Index('UQ_conversation_mappings_reverse', ['pluginId', 'instanceId', 'providerConversationId'], { unique: true })+export class ConversationMapping {+ @PrimaryGeneratedColumn('uuid')+ id: string;++ @Column()+ sessionId: string;++ @Column()+ chatId: string;++ @Column()+ pluginId: string;++ @Column()+ instanceId: string;++ @Column()+ providerConversationId: string;++ @Column({ default: 'bot' })+ handoverState: HandoverState;++ @Column({ type: jsonColumnType(), nullable: true })+ metadata: Record<string, unknown> | null;++ @UpdateDateColumn()+ updatedAt: Date;+}diff --git a/src/modules/integration/entities/ingress-event.entity.ts b/src/modules/integration/entities/ingress-event.entity.tsnew file mode 100644index 000000000..5582b1975--- /dev/null+++ b/src/modules/integration/entities/ingress-event.entity.ts@@ -0,0 +1,34 @@+import { Column, CreateDateColumn, Entity, Index, PrimaryColumn } from 'typeorm';+import { jsonColumnType } from '../../../common/utils/column-types';++// Persist-before-ack durable row + inbound dedup oracle. UNIQUE(instanceId, providerDeliveryId).+@Entity('ingress_events')+@Index('UQ_ingress_events_instance_delivery', ['instanceId', 'providerDeliveryId'], { unique: true })+@Index('IDX_ingress_events_createdAt', ['createdAt'])+export class IngressEvent {+ // Host-minted uuid (crypto.randomUUID()), NOT DB-generated — the id and the jobId (= deliveryId)+ // are decoupled on purpose. @PrimaryColumn, not @PrimaryGeneratedColumn.+ @PrimaryColumn()+ id: string;++ @Column()+ instanceId: string;++ @Column()+ pluginId: string;++ @Column()+ providerDeliveryId: string;++ @Column()+ route: string;++ @Column({ type: jsonColumnType() })+ payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };++ @Column({ type: 'varchar', nullable: true })+ sessionId: string | null;++ @CreateDateColumn()+ createdAt: Date;+}diff --git a/src/modules/integration/entities/integration-delivery-failure.entity.ts b/src/modules/integration/entities/integration-delivery-failure.entity.tsnew file mode 100644index 000000000..80e7e2630--- /dev/null+++ b/src/modules/integration/entities/integration-delivery-failure.entity.ts@@ -0,0 +1,41 @@+import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';+import { jsonColumnType } from '../../../common/utils/column-types';++// DLQ-of-record for both inbound (ingress) and outbound (provider egress) delivery failures.+// Generalizes webhook_delivery_failures. sessionId is provenance (no FK).+@Entity('integration_delivery_failures')+@Index('IDX_integration_delivery_failures_instance', ['pluginId', 'instanceId'])+export class IntegrationDeliveryFailure {+ @PrimaryGeneratedColumn('uuid')+ id: string;++ @Column()+ direction: 'inbound' | 'outbound';++ @Column()+ pluginId: string;++ @Column()+ instanceId: string;++ @Column({ type: 'varchar', nullable: true })+ sessionId: string | null;++ @Column({ type: 'varchar', nullable: true })+ deliveryId: string | null;++ @Column({ type: 'int' })+ attempts: number;++ @Column({ type: 'text' })+ lastError: string;++ @Column({ type: jsonColumnType(), nullable: true })+ payload: Record<string, unknown> | null;++ @Column({ default: false })+ redriven: boolean;++ @CreateDateColumn()+ createdAt: Date;+}diff --git a/src/modules/integration/entities/plugin-instance.entity.ts b/src/modules/integration/entities/plugin-instance.entity.tsnew file mode 100644index 000000000..4546ccadd--- /dev/null+++ b/src/modules/integration/entities/plugin-instance.entity.ts@@ -0,0 +1,38 @@+import { Column, CreateDateColumn, Entity, Index, PrimaryColumn, UpdateDateColumn } from 'typeorm';+import { jsonColumnType } from '../../../common/utils/column-types';++// One configured instance of an adapter plugin (e.g. one Chatwoot account). instanceId is namespaced+// under pluginId; NOT a separate worker. Secret is host-minted and masked-on-read.+@Entity('plugin_instances')+@Index('UQ_plugin_instances_plugin_instance', ['pluginId', 'instanceId'], { unique: true })+export class PluginInstance {+ @PrimaryColumn()+ id: string; // `${pluginId}:${instanceId}`++ @Column()+ pluginId: string;++ @Column()+ instanceId: string;++ @Column({ type: 'varchar', nullable: true })+ sessionScope: string | null; // resolved session id this instance acts on; null = inherit manifest.sessions++ @Column()+ secret: string; // host-minted ingress HMAC secret (masked on read via redactSecretConfig)++ @Column({ type: 'varchar', nullable: true })+ verifyToken: string | null; // optional provider challenge token++ @Column({ type: jsonColumnType(), nullable: true })+ config: Record<string, unknown> | null;++ @Column({ default: true })+ enabled: boolean;++ @CreateDateColumn()+ createdAt: Date;++ @UpdateDateColumn()+ updatedAt: Date;+}diff --git a/src/modules/integration/ingress-event.service.spec.ts b/src/modules/integration/ingress-event.service.spec.tsnew file mode 100644index 000000000..b3de5163d--- /dev/null+++ b/src/modules/integration/ingress-event.service.spec.ts@@ -0,0 +1,39 @@+import { DataSource } from 'typeorm';+import { IngressEvent } from './entities/ingress-event.entity';+import { IngressEventService } from './ingress-event.service';+import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';++describe('IngressEventService.recordOrSkip', () => {+ let ds: DataSource;+ let service: IngressEventService;+ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [IngressEvent], migrations: [] });+ await ds.initialize();+ const runner = ds.createQueryRunner();+ await new AddIntegrationFabric1781900000000().up(runner);+ await runner.release();+ service = new IngressEventService(ds.getRepository(IngressEvent));+ });+ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ });++ const row = () => ({+ instanceId: 'inst',+ pluginId: 'plug',+ providerDeliveryId: 'd1',+ route: 'chatwoot',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ sessionId: null,+ });++ it('returns true for a first delivery and false for a replay of the same delivery id', async () => {+ expect(await service.recordOrSkip(row())).toBe(true);+ expect(await service.recordOrSkip(row())).toBe(false);+ });++ it('treats the same delivery id under a different instance as new', async () => {+ expect(await service.recordOrSkip(row())).toBe(true);+ expect(await service.recordOrSkip({ ...row(), instanceId: 'inst2' })).toBe(true);+ });+});diff --git a/src/modules/integration/ingress-event.service.ts b/src/modules/integration/ingress-event.service.tsnew file mode 100644index 000000000..4ef09fed2--- /dev/null+++ b/src/modules/integration/ingress-event.service.ts@@ -0,0 +1,40 @@+import { randomUUID } from 'node:crypto';+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { QueryFailedError, Repository } from 'typeorm';+import { IngressEvent } from './entities/ingress-event.entity';++// Cross-dialect unique-violation check by driver code/message — the two dialects we ship+// (sqlite dev, postgres prod). Add another branch if a third driver is ever supported.+export function isUniqueViolation(err: unknown): boolean {+ if (!(err instanceof QueryFailedError)) return false;+ const driver = err.driverError as { code?: string; message?: string } | undefined;+ const code = driver?.code ?? '';+ const message = driver?.message ?? err.message ?? '';+ return code === '23505' /* postgres */ || /UNIQUE constraint failed|SQLITE_CONSTRAINT/i.test(message);+}++export interface IngressEventInput {+ instanceId: string;+ pluginId: string;+ providerDeliveryId: string;+ route: string;+ payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+ sessionId: string | null;+}++@Injectable()+export class IngressEventService {+ constructor(@InjectRepository(IngressEvent, 'data') private readonly repo: Repository<IngressEvent>) {}++ // Persist-before-ack + dedup. true = newly recorded (enqueue it); false = duplicate (drop, already handled).+ async recordOrSkip(input: IngressEventInput): Promise<boolean> {+ try {+ await this.repo.insert({ id: randomUUID(), ...input });+ return true;+ } catch (err) {+ if (isUniqueViolation(err)) return false;+ throw err;+ }+ }+}diff --git a/src/modules/integration/ingress-golden.spec.ts b/src/modules/integration/ingress-golden.spec.tsnew file mode 100644index 000000000..fae2abae3--- /dev/null+++ b/src/modules/integration/ingress-golden.spec.ts@@ -0,0 +1,121 @@+import { createHmac, randomBytes } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { IngressService, IngressDeps } from './ingress.service';++// This wires the real IngressService + verifier + a fake dedup/enqueue + a fake loader to prove the+// whole SDK v1 contract: a signed Chatwoot delivery flows to a conversation.send. It is the frozen+// executable spec — a break here means the wire ABI changed.+describe('Integration SDK v1 golden contract — Chatwoot message_created', () => {+ const secret = randomBytes(32).toString('hex');+ // Read the RAW bytes from disk — the HMAC must be computed over exactly what a provider would sign,+ // not a re-serialized object (JSON.stringify(JSON.parse(raw)) is not guaranteed byte-identical).+ const raw = readFileSync(join(__dirname, '__fixtures__/chatwoot-message_created.json'), 'utf8');+ const sig = 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex');++ const manifestRoute = () => ({+ route: 'chatwoot',+ mode: 'async' as const,+ verify: 'core' as const,+ maxBodyBytes: 262144,+ signature: {+ scheme: 'hmac-sha256' as const,+ header: 'X-Chatwoot-Signature',+ contentTemplate: '{rawBody}',+ encoding: 'hex' as const,+ prefix: 'sha256=',+ },+ dedupHeader: 'x-chatwoot-delivery',+ });++ const resolveInstance = () =>+ Promise.resolve({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ secret,+ enabled: true,+ sessionScope: 'sess-1',+ verifyToken: null,+ });++ interface ChatwootFixtureBody {+ message_type: string;+ private: boolean;+ content: string;+ }++ it('verifies the signature, dedups, enqueues, and the dispatched handler sends to WhatsApp', async () => {+ const dispatched: unknown[] = [];+ const enqueued: unknown[] = [];+ // Simulate the worker handler + conversation.send by resolving the mapping and calling sendText.+ const sentToWhatsApp: unknown[] = [];+ const fakeLoaderDispatch = (data: { payload: { rawBody: string } }) => {+ const body = JSON.parse(data.payload.rawBody) as ChatwootFixtureBody;+ if (body.message_type === 'outgoing' && !body.private) {+ sentToWhatsApp.push({ chatId: '[email protected]', text: body.content });+ }+ };++ const deps: IngressDeps = {+ instances: { resolve: resolveInstance },+ manifestRoute,+ events: {+ recordOrSkip: () => {+ enqueued.push('recorded');+ return Promise.resolve(true);+ },+ },+ enqueue: (data, jobId) => {+ enqueued.push({ data, jobId });+ fakeLoaderDispatch(data);+ dispatched.push(jobId);+ return Promise.resolve();+ },+ now: () => 0,+ };+ const svc = new IngressService(deps);++ const res = await svc.handle({+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ method: 'POST',+ headers: { 'x-chatwoot-signature': sig, 'x-chatwoot-delivery': 'delivery-1' },+ query: {},+ rawBody: raw,+ });++ expect(res.status).toBe(202);+ expect(dispatched).toEqual(['delivery-1']);+ expect(sentToWhatsApp).toEqual([{ chatId: '[email protected]', text: 'Hello from a human agent' }]);+ });++ it('rejects the same fixture with a wrong signature (401) and never dispatches', async () => {+ const dispatched: unknown[] = [];+ const deps: IngressDeps = {+ instances: { resolve: resolveInstance },+ manifestRoute,+ events: { recordOrSkip: () => Promise.resolve(true) },+ enqueue: (_data, jobId) => {+ dispatched.push(jobId);+ return Promise.resolve();+ },+ now: () => 0,+ };+ const svc = new IngressService(deps);++ const res = await svc.handle({+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ method: 'POST',+ headers: { 'x-chatwoot-signature': 'sha256=deadbeef', 'x-chatwoot-delivery': 'delivery-2' },+ query: {},+ rawBody: raw,+ });++ expect(res.status).toBe(401);+ expect(dispatched).toEqual([]);+ });+});diff --git a/src/modules/integration/ingress-signature.spec.ts b/src/modules/integration/ingress-signature.spec.tsnew file mode 100644index 000000000..b5e2c4e12--- /dev/null+++ b/src/modules/integration/ingress-signature.spec.ts@@ -0,0 +1,77 @@+import { createHmac } from 'node:crypto';+import { verifyIngressSignature } from './ingress-signature';++const secret = 'topsecret';+const rawBody = '{"event":"message_created"}';+const sig = (body: string) => 'sha256=' + createHmac('sha256', secret).update(body).digest('hex');++describe('verifyIngressSignature', () => {+ const spec = {+ scheme: 'hmac-sha256' as const,+ header: 'X-Sig',+ contentTemplate: '{rawBody}',+ encoding: 'hex' as const,+ prefix: 'sha256=',+ };++ it('accepts a correct hmac-sha256 signature over the raw body', () => {+ const r = verifyIngressSignature(spec, { rawBody, headers: { 'x-sig': sig(rawBody) }, secret, now: 0 });+ expect(r.ok).toBe(true);+ });++ it('rejects a tampered body (constant-time mismatch)', () => {+ const r = verifyIngressSignature(spec, {+ rawBody: rawBody + ' ',+ headers: { 'x-sig': sig(rawBody) },+ secret,+ now: 0,+ });+ expect(r.ok).toBe(false);+ });++ it('rejects a stale timestamp beyond tolerance', () => {+ const withTs = { ...spec, timestampHeader: 'X-Ts', toleranceSec: 300, contentTemplate: '{timestamp}.{rawBody}' };+ const t = 1000;+ const signed = 'sha256=' + createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');+ const r = verifyIngressSignature(withTs, {+ rawBody,+ headers: { 'x-sig': signed, 'x-ts': String(t) },+ secret,+ now: (t + 400) * 1000,+ });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/replay|stale|tolerance/i);+ });++ it('accepts a fresh timestamp within tolerance', () => {+ const withTs = { ...spec, timestampHeader: 'X-Ts', toleranceSec: 300, contentTemplate: '{timestamp}.{rawBody}' };+ const t = 1000;+ const signed = 'sha256=' + createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');+ const r = verifyIngressSignature(withTs, {+ rawBody,+ headers: { 'x-sig': signed, 'x-ts': String(t) },+ secret,+ now: (t + 10) * 1000,+ });+ expect(r.ok).toBe(true);+ });++ it('rejects a missing signature header', () => {+ const r = verifyIngressSignature(spec, { rawBody, headers: {}, secret, now: 0 });+ expect(r.ok).toBe(false);+ });++ it('accepts a shared-secret match and rejects a mismatch (constant time)', () => {+ const sharedSpec = { scheme: 'shared-secret' as const, header: 'X-Token' };+ expect(verifyIngressSignature(sharedSpec, { rawBody, headers: { 'x-token': secret }, secret, now: 0 }).ok).toBe(+ true,+ );+ expect(verifyIngressSignature(sharedSpec, { rawBody, headers: { 'x-token': 'nope' }, secret, now: 0 }).ok).toBe(+ false,+ );+ });++ it('accepts scheme "none" without a signature', () => {+ expect(verifyIngressSignature({ scheme: 'none' }, { rawBody, headers: {}, secret, now: 0 }).ok).toBe(true);+ });+});diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.tsnew file mode 100644index 000000000..133e6437e--- /dev/null+++ b/src/modules/integration/ingress-signature.ts@@ -0,0 +1,61 @@+import { createHmac, timingSafeEqual } from 'node:crypto';+import { IngressSignatureSpec } from '../../core/plugins/plugin.interfaces';++export interface VerifyInput {+ rawBody: string;+ headers: Record<string, string>; // lower-cased keys+ secret: string;+ now: number; // ms epoch (injected so replay tests are deterministic — never Date.now() in here)+}++function header(headers: Record<string, string>, name?: string): string | undefined {+ if (!name) return undefined;+ return headers[name.toLowerCase()];+}++/**+ * Inverts the outbound signer (webhook.service.ts:527-531) — but over the provider's declared+ * contentTemplate applied to the RAW request bytes, and with a constant-time compare. `now` is+ * injected so the replay-window check is deterministic in tests.+ */+export function verifyIngressSignature(+ spec: IngressSignatureSpec,+ input: VerifyInput,+): { ok: boolean; reason?: string } {+ if (spec.scheme === 'none') return { ok: true };++ if (spec.timestampHeader) {+ const tsRaw = header(input.headers, spec.timestampHeader);+ const ts = Number.parseInt(tsRaw ?? '', 10);+ if (!Number.isFinite(ts)) return { ok: false, reason: 'missing/invalid timestamp' };+ const skewSec = Math.abs(input.now / 1000 - ts);+ if (!(spec.toleranceSec && skewSec <= spec.toleranceSec)) {+ return { ok: false, reason: 'replay: timestamp outside tolerance' };+ }+ }++ const provided = header(input.headers, spec.header);+ if (!provided) return { ok: false, reason: 'missing signature header' };++ if (spec.scheme === 'shared-secret') {+ return safeEqualStr(provided, input.secret) ? { ok: true } : { ok: false, reason: 'shared-secret mismatch' };+ }++ // hmac-sha256+ const template = spec.contentTemplate ?? '{rawBody}';+ const signedContent = template+ .replace('{rawBody}', input.rawBody)+ .replace('{timestamp}', header(input.headers, spec.timestampHeader) ?? '');+ const digest = createHmac('sha256', input.secret)+ .update(signedContent)+ .digest(spec.encoding ?? 'hex');+ const expected = (spec.prefix ?? '') + digest;+ return safeEqualStr(provided, expected) ? { ok: true } : { ok: false, reason: 'hmac mismatch' };+}++function safeEqualStr(a: string, b: string): boolean {+ const ba = Buffer.from(a);+ const bb = Buffer.from(b);+ if (ba.length !== bb.length) return false;+ return timingSafeEqual(ba, bb);+}diff --git a/src/modules/integration/ingress.controller.spec.ts b/src/modules/integration/ingress.controller.spec.tsnew file mode 100644index 000000000..da2076bb3--- /dev/null+++ b/src/modules/integration/ingress.controller.spec.ts@@ -0,0 +1,68 @@+import type { Request, Response } from 'express';+import { IngressController } from './ingress.controller';+import { IngressService } from './ingress.service';++// A byte sequence whose JSON.stringify(parse(x)) would NOT round-trip identically: extra whitespace,+// key order, and a trailing newline. The controller must forward the RAW bytes, not a re-serialized body.+const RAW = '{\n "event": "message_created",\n "id": 42\n}\n';++function fakeRes() {+ const captured: { status?: number; body?: string } = {};+ const res = {+ status: jest.fn((code: number) => {+ captured.status = code;+ return res;+ }),+ send: jest.fn((body: string) => {+ captured.body = body;+ return res;+ }),+ } as unknown as Response;+ return { res, captured };+}++describe('IngressController', () => {+ it('forwards the RAW request bytes byte-identically to the pipeline', async () => {+ const handle = jest.fn().mockResolvedValue({ status: 202, body: 'accepted' });+ const controller = new IngressController({ handle } as unknown as IngressService);++ const { res, captured } = fakeRes();+ const req = {+ method: 'POST',+ params: { path: ['chatwoot'] },+ headers: { 'x-delivery': 'd1', 'content-type': 'application/json' },+ rawBody: Buffer.from(RAW, 'utf8'),+ } as unknown as Request & { rawBody?: Buffer };++ await controller.receive('chatwoot', 'acct1', {}, req, res);++ expect(handle).toHaveBeenCalledTimes(1);+ const arg = (handle.mock.calls[0] as [{ rawBody: string; route: string; method: string }])[0];+ // Byte-for-byte identical to what the provider signed — no JSON round-trip.+ expect(arg.rawBody).toBe(RAW);+ expect(arg.route).toBe('chatwoot');+ expect(arg.method).toBe('POST');+ expect(captured.status).toBe(202);+ expect(captured.body).toBe('accepted');+ });++ it('lower-cases headers and tolerates an absent rawBody (empty string)', async () => {+ const handle = jest.fn().mockResolvedValue({ status: 200, body: '' });+ const controller = new IngressController({ handle } as unknown as IngressService);++ const { res } = fakeRes();+ const req = {+ method: 'GET',+ params: { path: ['meta', 'webhook'] },+ headers: { 'X-Verify-Token': 'vtok' },+ } as unknown as Request & { rawBody?: Buffer };++ await controller.receive('meta', 'acct1', { 'hub.challenge': '1' }, req, res);++ const arg = (handle.mock.calls[0] as [{ headers: Record<string, string>; route: string; rawBody: string }])[0];+ // Header keys lower-cased; multi-segment splat reduced to the first route segment.+ expect(arg.headers['x-verify-token']).toBe('vtok');+ expect(arg.route).toBe('meta');+ expect(arg.rawBody).toBe('');+ });+});diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.tsnew file mode 100644index 000000000..7bbd4a9b5--- /dev/null+++ b/src/modules/integration/ingress.controller.ts@@ -0,0 +1,48 @@+import { All, Controller, Param, Query, Req, Res } from '@nestjs/common';+import type { Request, Response } from 'express';+import { Public } from '../auth/decorators/auth.decorators';+import { IngressService } from './ingress.service';++// @Public so the global ApiKeyGuard early-returns (providers can't present an API key), but NOT+// @SkipThrottle — the global IP throttle stays as a coarse guard (per-instance fairness is P1).+// The provider body is read as RAW bytes from req.rawBody (stashed by the json() verify callback in+// main.ts) — it is intentionally NOT DTO-bound, so the global ValidationPipe never 400s on the+// provider's unknown keys, and the exact signed bytes reach the HMAC verifier.+@Public()+@Controller('ingress')+export class IngressController {+ constructor(private readonly ingress: IngressService) {}++ // Express 5 (path-to-regexp v8) has no bare `*` — Nest's route converter rewrites it to the named+ // wildcard `*path`, so the trailing segments land in req.params.path (an array), not req.params[0].+ @All(':pluginId/:instanceId/*path')+ async receive(+ @Param('pluginId') pluginId: string,+ @Param('instanceId') instanceId: string,+ @Query() query: Record<string, string>,+ @Req() req: Request & { rawBody?: Buffer },+ @Res() res: Response,+ ): Promise<void> {+ const wildcard = (req.params as Record<string, string | string[] | undefined>).path;+ const segments = Array.isArray(wildcard)+ ? wildcard+ : typeof wildcard === 'string'+ ? wildcard.split('/').filter(Boolean)+ : [];+ const route = segments[0] ?? '';+ const headers: Record<string, string> = Object.fromEntries(+ Object.entries(req.headers).map(([k, v]) => [k.toLowerCase(), Array.isArray(v) ? v.join(',') : String(v ?? '')]),+ );+ const rawBody = req.rawBody?.toString('utf8') ?? '';+ const result = await this.ingress.handle({+ pluginId,+ instanceId,+ route,+ method: req.method,+ headers,+ query,+ rawBody,+ });+ res.status(result.status).send(result.body ?? '');+ }+}diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.tsnew file mode 100644index 000000000..252c21576--- /dev/null+++ b/src/modules/integration/ingress.service.spec.ts@@ -0,0 +1,224 @@+import { IngressService, extractConversationId } from './ingress.service';++function deps(overrides: Record<string, unknown> = {}) {+ return {+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ secret: 's',+ enabled: true,+ sessionScope: 'sess-1',+ verifyToken: null,+ }),+ },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'chatwoot',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ }),+ events: { recordOrSkip: jest.fn().mockResolvedValue(true) },+ enqueue: jest.fn().mockResolvedValue(undefined),+ now: () => 0,+ ...overrides,+ };+}++describe('IngressService.handle', () => {+ const req = {+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ method: 'POST',+ headers: { 'x-delivery': 'd1' },+ query: {},+ rawBody: '{}',+ };++ it('verifies, persists, enqueues, and fast-acks 202', async () => {+ const d = deps();+ const svc = new IngressService(d);+ const res = await svc.handle(req);+ expect(d.events.recordOrSkip).toHaveBeenCalled();+ expect(d.enqueue).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'd1' }), 'd1');+ expect(res.status).toBe(202);+ });++ it('short-circuits a duplicate delivery with 200 and no enqueue', async () => {+ const d = deps({ events: { recordOrSkip: jest.fn().mockResolvedValue(false) } });+ const svc = new IngressService(d);+ const res = await svc.handle(req);+ expect(d.enqueue).not.toHaveBeenCalled();+ expect(res.status).toBe(200);+ });++ it('rejects an oversized body with 413 before any dedup or enqueue', async () => {+ const d = deps({+ manifestRoute: jest.fn().mockReturnValue({+ route: 'chatwoot',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ }),+ });+ const svc = new IngressService(d);+ const res = await svc.handle(req);+ expect(res.status).toBe(413);+ expect(d.events.recordOrSkip).not.toHaveBeenCalled();+ });++ it('rejects a bad signature with 401 before any dedup or enqueue', async () => {+ const d = deps({+ manifestRoute: jest.fn().mockReturnValue({+ route: 'chatwoot',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'hmac-sha256', header: 'x-sig', prefix: 'sha256=' },+ dedupHeader: 'x-delivery',+ }),+ });+ const svc = new IngressService(d);+ const res = await svc.handle({ ...req, headers: { 'x-delivery': 'd1', 'x-sig': 'sha256=deadbeef' } });+ expect(res.status).toBe(401);+ expect(d.events.recordOrSkip).not.toHaveBeenCalled();+ expect(d.enqueue).not.toHaveBeenCalled();+ });++ it('404s for an unknown or disabled instance', async () => {+ const d = deps({ instances: { resolve: jest.fn().mockResolvedValue(null) } });+ const svc = new IngressService(d);+ expect((await svc.handle(req)).status).toBe(404);+ });++ it('404s for a disabled instance', async () => {+ const d = deps({+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ secret: 's',+ enabled: false,+ sessionScope: null,+ verifyToken: null,+ }),+ },+ });+ const svc = new IngressService(d);+ expect((await svc.handle(req)).status).toBe(404);+ });++ it('answers a GET challenge handshake host-side without enqueuing', async () => {+ const d = deps({+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'meta:acct1',+ pluginId: 'meta',+ instanceId: 'acct1',+ secret: 's',+ enabled: true,+ sessionScope: null,+ verifyToken: 'vtok',+ }),+ },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'meta',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ challenge: { method: 'GET', tokenParam: 'hub.verify_token', echoParam: 'hub.challenge' },+ }),+ });+ const svc = new IngressService(d);+ const res = await svc.handle({+ pluginId: 'meta',+ instanceId: 'acct1',+ route: 'meta',+ method: 'GET',+ headers: {},+ query: { 'hub.verify_token': 'vtok', 'hub.challenge': '12345' },+ rawBody: '',+ });+ expect(res.status).toBe(200);+ expect(res.body).toBe('12345');+ expect(d.enqueue).not.toHaveBeenCalled();+ });++ it('rejects a GET challenge with the wrong verify token', async () => {+ const d = deps({+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'meta:acct1',+ pluginId: 'meta',+ instanceId: 'acct1',+ secret: 's',+ enabled: true,+ sessionScope: null,+ verifyToken: 'vtok',+ }),+ },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'meta',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ challenge: { method: 'GET', tokenParam: 'hub.verify_token', echoParam: 'hub.challenge' },+ }),+ });+ const svc = new IngressService(d);+ const res = await svc.handle({+ pluginId: 'meta',+ instanceId: 'acct1',+ route: 'meta',+ method: 'GET',+ headers: {},+ query: { 'hub.verify_token': 'wrong', 'hub.challenge': '12345' },+ rawBody: '',+ });+ expect(res.status).toBe(403);+ });++ it('404s for an unknown route', async () => {+ const d = deps({ manifestRoute: jest.fn().mockReturnValue(undefined) });+ const svc = new IngressService(d);+ expect((await svc.handle(req)).status).toBe(404);+ });++ it('falls back to a generated delivery id when the dedup header is absent', async () => {+ const d = deps();+ const svc = new IngressService(d);+ const res = await svc.handle({ ...req, headers: {} });+ expect(res.status).toBe(202);+ const [jobData, jobId] = d.enqueue.mock.calls[0] as [{ deliveryId: string }, string];+ expect(typeof jobId).toBe('string');+ expect(jobId.length).toBeGreaterThan(0);+ expect(jobData.deliveryId).toBe(jobId);+ });+});++describe('extractConversationId', () => {+ it('returns undefined when no spec is declared', () => {+ expect(extractConversationId(undefined, {}, '{}')).toBeUndefined();+ });++ it('reads a declared header (case-insensitive)', () => {+ expect(extractConversationId({ header: 'X-Conv' }, { 'x-conv': 'c1' }, '{}')).toBe('c1');+ });++ it('reads a JSON pointer into the body', () => {+ expect(extractConversationId({ jsonPointer: '/conversation/id' }, {}, '{"conversation":{"id":42}}')).toBe('42');+ });++ it('returns undefined on a malformed body without throwing', () => {+ expect(extractConversationId({ jsonPointer: '/a/b' }, {}, 'not json')).toBeUndefined();+ });+});diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsnew file mode 100644index 000000000..780608bbd--- /dev/null+++ b/src/modules/integration/ingress.service.ts@@ -0,0 +1,142 @@+import { randomUUID } from 'node:crypto';+import { verifyIngressSignature } from './ingress-signature';+import { PluginIngressRoute } from '../../core/plugins/plugin.interfaces';+import { IngressJobData } from '../queue/processors/ingress.processor';++export interface IngressRequest {+ pluginId: string;+ instanceId: string;+ route: string;+ method: string;+ headers: Record<string, string>; // lower-cased keys+ query: Record<string, string>;+ rawBody: string;+}++export interface ResolvedInstance {+ id: string;+ pluginId: string;+ instanceId: string;+ secret: string;+ enabled: boolean;+ sessionScope: string | null;+ verifyToken: string | null;+}++// The manifest route, possibly with the dedup header surfaced at the top level. On the real manifest+// dedupHeader lives under `signature`; the resolver may lift it, so read both (top level wins).+export type IngressRouteDescriptor = PluginIngressRoute & { dedupHeader?: string };++export interface IngressDeps {+ instances: { resolve(pluginId: string, instanceId: string): Promise<ResolvedInstance | null> };+ manifestRoute: (pluginId: string, route: string) => IngressRouteDescriptor | undefined;+ events: {+ recordOrSkip(input: {+ instanceId: string;+ pluginId: string;+ providerDeliveryId: string;+ route: string;+ payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+ sessionId: string | null;+ }): Promise<boolean>;+ };+ enqueue: (data: IngressJobData, jobId: string) => Promise<void>;+ now: () => number;+}++/**+ * The fast-ack ingress pipeline. Pure orchestration over injected deps so it is unit-testable without+ * Nest DI: resolve the instance → answer a GET challenge host-side → size cap → verify over the RAW+ * body → dedup (persist-before-ack) → best-effort conversation id → enqueue (or inline) → 202.+ */+export class IngressService {+ constructor(private readonly deps: IngressDeps) {}++ async handle(req: IngressRequest): Promise<{ status: number; body?: string }> {+ const instance = await this.deps.instances.resolve(req.pluginId, req.instanceId);+ if (!instance || !instance.enabled) return { status: 404, body: 'unknown instance' };++ const route = this.deps.manifestRoute(req.pluginId, req.route);+ if (!route) return { status: 404, body: 'unknown route' };++ // GET challenge handshake (e.g. Meta hub.challenge), answered host-side without the worker. The+ // token is compared against the instance's minted verifyToken.+ if (req.method === 'GET' && route.challenge) {+ const token = req.query[route.challenge.tokenParam];+ const echo = req.query[route.challenge.echoParam];+ if (token && instance.verifyToken && token === instance.verifyToken) return { status: 200, body: echo ?? '' };+ return { status: 403, body: 'challenge failed' };+ }++ if (Buffer.byteLength(req.rawBody, 'utf8') > route.maxBodyBytes) return { status: 413, body: 'payload too large' };++ const verdict = verifyIngressSignature(route.signature, {+ rawBody: req.rawBody,+ headers: req.headers,+ secret: instance.secret,+ now: this.deps.now(),+ });+ if (!verdict.ok) return { status: 401, body: verdict.reason ?? 'signature verification failed' };++ const dedupHeader = (route.dedupHeader ?? route.signature.dedupHeader ?? 'x-delivery').toLowerCase();+ const deliveryId = req.headers[dedupHeader] ?? randomUUID();+ const payload = { headers: req.headers, query: req.query, body: req.rawBody, rawBody: req.rawBody };+ const isNew = await this.deps.events.recordOrSkip({+ instanceId: req.instanceId,+ pluginId: req.pluginId,+ providerDeliveryId: deliveryId,+ route: req.route,+ payload,+ sessionId: instance.sessionScope,+ });+ if (!isNew) return { status: 200, body: 'duplicate' }; // already persisted/acked++ // Best-effort conversation id for P1 ordering. Never throws — a malformed body just yields undefined.+ const providerConversationId = extractConversationId(route.conversationId, req.headers, req.rawBody);++ await this.deps.enqueue(+ {+ pluginId: req.pluginId,+ instanceId: req.instanceId,+ route: req.route,+ deliveryId,+ sessionId: instance.sessionScope ?? undefined,+ providerConversationId,+ payload,+ },+ deliveryId,+ );+ return { status: 202, body: 'accepted' };+ }+}++/**+ * Extracts the provider conversation id from a declared header or a JSON pointer into the body.+ * Returns undefined when no pointer is declared or extraction fails — the P1 lock then keys per+ * instance. Pure and total: never throws on a malformed body.+ */+export function extractConversationId(+ spec: { header?: string; jsonPointer?: string } | undefined,+ headers: Record<string, string>,+ rawBody: string,+): string | undefined {+ if (!spec) return undefined;+ if (spec.header) {+ const v = headers[spec.header.toLowerCase()];+ if (v) return v;+ }+ if (spec.jsonPointer) {+ try {+ let node: unknown = JSON.parse(rawBody);+ for (const seg of spec.jsonPointer.split('/').filter(Boolean)) {+ node = (node as Record<string, unknown>)?.[seg];+ }+ // Only a scalar is a usable conversation key — an object/array would stringify to junk.+ if (typeof node === 'string') return node;+ if (typeof node === 'number' || typeof node === 'boolean') return String(node);+ } catch {+ return undefined; // malformed body → no key, per-instance ordering+ }+ }+ return undefined;+}diff --git a/src/modules/integration/integration.constants.ts b/src/modules/integration/integration.constants.tsnew file mode 100644index 000000000..5ca53ef3f--- /dev/null+++ b/src/modules/integration/integration.constants.ts@@ -0,0 +1,3 @@+export const INGRESS_MAX_BODY_BYTES_DEFAULT = 262144; // 256 KiB, matches the spec's per-route default+export const INGRESS_REPLAY_TOLERANCE_SEC_DEFAULT = 300;+export const INGRESS_DISPATCH_TIMEOUT_MS = 5000; // mirrors SANDBOX_HOOK_TIMEOUT_MSdiff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsnew file mode 100644index 000000000..0cc966216--- /dev/null+++ b/src/modules/integration/integration.module.ts@@ -0,0 +1,92 @@+import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';+import { ConfigService } from '@nestjs/config';+import { getQueueToken } from '@nestjs/bullmq';+import { Queue } from 'bullmq';+import { PluginInstance } from './entities/plugin-instance.entity';+import { IngressEvent } from './entities/ingress-event.entity';+import { PluginInstanceService } from './plugin-instance.service';+import { IngressEventService } from './ingress-event.service';+import { IngressService, IngressRouteDescriptor } from './ingress.service';+import { IngressController } from './ingress.controller';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { IngressJobData } from '../queue/processors/ingress.processor';+import { QUEUE_NAMES } from '../queue/queue-names';+import { createLogger } from '../../common/services/logger.service';++// The ingress queue token. The queue provider only exists when QueueModule is imported+// (QUEUE_ENABLED=true); otherwise this token has no value and the factory below falls back to inline+// dispatch — mirroring WebhookService's direct-delivery fallback.+const INGRESS_QUEUE_TOKEN = getQueueToken(QUEUE_NAMES.INGRESS);++/**+ * Wires the @Public ingress HTTP surface: instance/event persistence services and the fast-ack+ * IngressService, whose deps are built by a factory so the pure pipeline stays DI-free and testable.+ * The optional ingress queue is resolved by token — present only under QUEUE_ENABLED — and the+ * factory picks enqueue-vs-inline exactly like the webhook producer. PluginLoaderService is @Global+ * (PluginsModule), so it injects without importing that module.+ */+@Module({+ imports: [TypeOrmModule.forFeature([PluginInstance, IngressEvent], 'data')],+ controllers: [IngressController],+ providers: [+ PluginInstanceService,+ IngressEventService,+ {+ provide: IngressService,+ // The queue token is OPTIONAL: without QUEUE_ENABLED there is no provider for it, and a required+ // dependency would fail to resolve at boot. Optional → undefined, and the factory falls back to inline.+ inject: [+ PluginInstanceService,+ IngressEventService,+ PluginLoaderService,+ ConfigService,+ { token: INGRESS_QUEUE_TOKEN, optional: true },+ ],+ useFactory: (+ instances: PluginInstanceService,+ events: IngressEventService,+ loader: PluginLoaderService,+ config: ConfigService,+ ingressQueue?: Queue<IngressJobData>,+ ) => {+ const logger = createLogger('IngressService');+ const queueEnabled = config.get<boolean>('queue.enabled', false);+ const useQueue = queueEnabled && !!ingressQueue;++ return new IngressService({+ instances: { resolve: (pluginId, instanceId) => instances.resolve(pluginId, instanceId) },+ manifestRoute: (pluginId, route): IngressRouteDescriptor | undefined =>+ loader.getPlugin(pluginId)?.manifest.ingress?.find(r => r.route === route),+ events: { recordOrSkip: input => events.recordOrSkip(input) },+ enqueue: async (data, jobId) => {+ if (useQueue && ingressQueue) {+ // jobId = deliveryId gives BullMQ exactly-once enqueue semantics.+ await ingressQueue.add('ingress', data, { jobId });+ return;+ }+ // Queue disabled: dispatch inline AFTER the ingress_events row was persisted+ // (persist-before-dispatch still holds), mirroring the webhook direct-delivery fallback.+ try {+ await loader.dispatchWebhookForInstance(data);+ } catch (err) {+ // A duplicate delivery already 200s before this point, so a failure here is a real+ // dispatch error. Log and swallow: the row is durably persisted for a later redrive,+ // and the provider still gets its 202 (at-least-once, like the webhook fallback).+ logger.error('Inline ingress dispatch failed', err instanceof Error ? err.message : String(err), {+ pluginId: data.pluginId,+ instanceId: data.instanceId,+ route: data.route,+ deliveryId: data.deliveryId,+ action: 'ingress_inline_dispatch_failed',+ });+ }+ },+ now: () => Date.now(),+ });+ },+ },+ ],+ exports: [PluginInstanceService, IngressEventService],+})+export class IntegrationModule {}diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.tsnew file mode 100644index 000000000..2268149dd--- /dev/null+++ b/src/modules/integration/plugin-instance.service.spec.ts@@ -0,0 +1,37 @@+import { DataSource } from 'typeorm';+import { PluginInstance } from './entities/plugin-instance.entity';+import { PluginInstanceService } from './plugin-instance.service';+import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';++describe('PluginInstanceService', () => {+ let ds: DataSource;+ let service: PluginInstanceService;+ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [PluginInstance], migrations: [] });+ await ds.initialize();+ const runner = ds.createQueryRunner();+ await new AddIntegrationFabric1781900000000().up(runner);+ await runner.release();+ service = new PluginInstanceService(ds.getRepository(PluginInstance));+ });+ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ });++ it('mints a 64-hex-char secret and stores a composite id', async () => {+ const inst = await service.mint('chatwoot', 'acct1', { sessionScope: 'sess-1' });+ expect(inst.id).toBe('chatwoot:acct1');+ expect(inst.secret).toMatch(/^[0-9a-f]{64}$/);+ });++ it('masks the secret on the operator-facing view', async () => {+ const inst = await service.mint('chatwoot', 'acct1', {});+ expect(service.maskedView(inst).secret).toBe('***');+ });++ it('resolves an existing instance and returns null for an unknown one', async () => {+ await service.mint('chatwoot', 'acct1', {});+ expect((await service.resolve('chatwoot', 'acct1'))?.id).toBe('chatwoot:acct1');+ expect(await service.resolve('chatwoot', 'nope')).toBeNull();+ });+});diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.tsnew file mode 100644index 000000000..e748ad9f6--- /dev/null+++ b/src/modules/integration/plugin-instance.service.ts@@ -0,0 +1,42 @@+import { randomBytes } from 'node:crypto';+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { PluginInstance } from './entities/plugin-instance.entity';++const SECRET_MASK = '***';++@Injectable()+export class PluginInstanceService {+ constructor(@InjectRepository(PluginInstance, 'data') private readonly repo: Repository<PluginInstance>) {}++ async mint(+ pluginId: string,+ instanceId: string,+ opts: { sessionScope?: string; verifyToken?: string; config?: Record<string, unknown> },+ ): Promise<PluginInstance> {+ const id = `${pluginId}:${instanceId}`;+ const existing = await this.repo.findOne({ where: { id } });+ if (existing) return existing;+ const inst = this.repo.create({+ id,+ pluginId,+ instanceId,+ sessionScope: opts.sessionScope ?? null,+ secret: randomBytes(32).toString('hex'),+ verifyToken: opts.verifyToken ?? null,+ config: opts.config ?? null,+ enabled: true,+ });+ return this.repo.save(inst);+ }++ resolve(pluginId: string, instanceId: string): Promise<PluginInstance | null> {+ return this.repo.findOne({ where: { id: `${pluginId}:${instanceId}` } });+ }++ // Operator-facing view: never leak the raw secret. Reuses the redact-config sentinel convention.+ maskedView(instance: PluginInstance): PluginInstance {+ return { ...instance, secret: SECRET_MASK };+ }+}diff --git a/src/modules/queue/processors/ingress.processor.spec.ts b/src/modules/queue/processors/ingress.processor.spec.tsnew file mode 100644index 000000000..dc6c848e2--- /dev/null+++ b/src/modules/queue/processors/ingress.processor.spec.ts@@ -0,0 +1,39 @@+import { IngressProcessor } from './ingress.processor';++function job(overrides = {}) {+ return {+ data: {+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ deliveryId: 'd1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ },+ attemptsMade: 0,+ opts: { attempts: 3 },+ ...overrides,+ } as never;+}++describe('IngressProcessor', () => {+ it('dispatches the event into the worker via dispatchWebhook', async () => {+ const dispatchWebhook = jest.fn().mockResolvedValue({ ok: true, status: 200 });+ const loader = { dispatchWebhookForInstance: dispatchWebhook };+ const failures = { save: jest.fn() };+ const proc = new IngressProcessor(loader as never, failures as never, { execute: jest.fn() } as never);+ await proc.process(job());+ expect(dispatchWebhook).toHaveBeenCalled();+ });++ it('records a DLQ failure row and fires ingress:error on the final attempt', async () => {+ const loader = { dispatchWebhookForInstance: jest.fn().mockRejectedValue(new Error('boom')) };+ const failures = { save: jest.fn().mockResolvedValue(undefined) };+ const hooks = { execute: jest.fn().mockResolvedValue({ continue: true }) };+ const proc = new IngressProcessor(loader as never, failures as never, hooks as never);+ await expect(proc.process(job({ attemptsMade: 2, opts: { attempts: 3 } }))).rejects.toThrow('boom');+ expect(failures.save).toHaveBeenCalledWith(+ expect.objectContaining({ direction: 'inbound', deliveryId: 'd1', pluginId: 'chatwoot' }),+ );+ expect(hooks.execute).toHaveBeenCalledWith('ingress:error', expect.anything(), expect.anything());+ });+});diff --git a/src/modules/queue/processors/ingress.processor.ts b/src/modules/queue/processors/ingress.processor.tsnew file mode 100644index 000000000..ac20a30d2--- /dev/null+++ b/src/modules/queue/processors/ingress.processor.ts@@ -0,0 +1,83 @@+import { Processor, WorkerHost } from '@nestjs/bullmq';+import { Job } from 'bullmq';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { QUEUE_NAMES } from '../queue-names';+import { workerConnectionOptions } from '../redis-connection';+import { IntegrationDeliveryFailure } from '../../integration/entities/integration-delivery-failure.entity';+import { PluginLoaderService } from '../../../core/plugins/plugin-loader.service';+import { HookManager } from '../../../core/hooks';+import { createLogger } from '../../../common/services/logger.service';++export interface IngressJobData {+ pluginId: string;+ instanceId: string;+ route: string;+ deliveryId: string;+ sessionId?: string;+ // Best-effort provider conversation id, extracted host-side from the manifest's conversationId+ // pointer. Undefined when the route declares no pointer — the per-conversation ordering lock then+ // serializes per instance. Carried unused today (concurrency=1) so the scale phase needs no re-plumb.+ providerConversationId?: string;+ payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+}++// concurrency 1 by design: per-conversation FIFO ordering is refined to a keyed advisory lock in a+// later phase; a single worker keeps ordering correct-by-default until that lock exists.+@Processor(QUEUE_NAMES.INGRESS, { connection: workerConnectionOptions(), concurrency: 1 })+export class IngressProcessor extends WorkerHost {+ private readonly logger = createLogger('IngressProcessor');++ constructor(+ private readonly loader: PluginLoaderService,+ @InjectRepository(IntegrationDeliveryFailure, 'data')+ private readonly failures: Repository<IntegrationDeliveryFailure>,+ private readonly hooks: HookManager,+ ) {+ super();+ }++ async process(job: Job<IngressJobData>): Promise<void> {+ const d = job.data;+ try {+ await this.loader.dispatchWebhookForInstance(d);+ } catch (err) {+ const errorMessage = err instanceof Error ? err.message : String(err);+ const isFinalAttempt = job.attemptsMade + 1 >= (job.opts.attempts ?? 1);++ this.logger.error('Ingress dispatch failed', errorMessage, {+ pluginId: d.pluginId,+ instanceId: d.instanceId,+ route: d.route,+ deliveryId: d.deliveryId,+ attempt: job.attemptsMade + 1,+ isFinalAttempt,+ action: 'ingress_dispatch_failed',+ });++ if (isFinalAttempt) {+ await this.hooks.execute(+ 'ingress:error',+ { ...d, error: errorMessage },+ { sessionId: d.sessionId, source: 'IngressProcessor' },+ );+ await this.failures.save({+ direction: 'inbound',+ pluginId: d.pluginId,+ instanceId: d.instanceId,+ sessionId: d.sessionId ?? null,+ deliveryId: d.deliveryId,+ attempts: job.attemptsMade + 1,+ lastError: errorMessage,+ // Persist the FULL ingress payload (route + headers/rawBody) so P1 redrive is+ // self-contained and never has to re-read ingress_events.+ payload: { route: d.route, providerConversationId: d.providerConversationId, ingress: d.payload },+ redriven: false,+ });+ }++ // Re-throw to trigger BullMQ's exponential backoff / retry.+ throw err;+ }+ }+}diff --git a/src/modules/queue/queue-names.ts b/src/modules/queue/queue-names.tsindex 734b518d9..05f314baa 100644--- a/src/modules/queue/queue-names.ts+++ b/src/modules/queue/queue-names.ts@@ -2,4 +2,5 @@// Extracted to separate file to avoid circular dependency with processorsexport const QUEUE_NAMES = {WEBHOOK: 'webhook-queue',+ INGRESS: 'ingress-queue',} as const;diff --git a/src/modules/queue/queue.module.ts b/src/modules/queue/queue.module.tsindex f4da9ebad..e39eceff5 100644--- a/src/modules/queue/queue.module.ts+++ b/src/modules/queue/queue.module.ts@@ -6,20 +6,27 @@ import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';import { ExpressAdapter } from '@bull-board/express';import { TypeOrmModule } from '@nestjs/typeorm';import { WebhookProcessor } from './processors/webhook.processor';+import { IngressProcessor } from './processors/ingress.processor';import { QUEUE_NAMES } from './queue-names';import { Webhook } from '../webhook/entities/webhook.entity';import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';+import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';import { HooksModule } from '../../core/hooks/hooks.module';+import { PluginsModule } from '../../core/plugins/plugins.module';// Re-export for backward compatibilityexport { QUEUE_NAMES } from './queue-names';@Module({imports: [- // Required for WebhookProcessor to inject Repository<Webhook> + Repository<WebhookDeliveryFailure>- TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure], 'data'),- // Required for WebhookProcessor to inject HookManager+ // Required for WebhookProcessor to inject Repository<Webhook> + Repository<WebhookDeliveryFailure>;+ // IngressProcessor to inject Repository<IntegrationDeliveryFailure> (both on the 'data' connection).+ TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure, IntegrationDeliveryFailure], 'data'),+ // Required for WebhookProcessor/IngressProcessor to inject HookManagerHooksModule,+ // Required for IngressProcessor to inject PluginLoaderService (already @Global(), imported+ // explicitly for clarity, matching HooksModule above).+ PluginsModule,BullModule.forRootAsync({imports: [ConfigModule],inject: [ConfigService],@@ -42,6 +49,13 @@ export { QUEUE_NAMES } from './queue-names';removeOnFail: { age: 86400, count: 5000 },},}),+ BullModule.registerQueue({+ name: QUEUE_NAMES.INGRESS,+ defaultJobOptions: {+ removeOnComplete: { age: 3600, count: 1000 },+ removeOnFail: { age: 86400, count: 5000 },+ },+ }),BullBoardModule.forRoot({route: '/admin/queues',adapter: ExpressAdapter,@@ -51,7 +65,7 @@ export { QUEUE_NAMES } from './queue-names';adapter: BullMQAdapter,}),],- providers: [WebhookProcessor],+ providers: [WebhookProcessor, IngressProcessor],exports: [BullModule],})export class QueueModule {}diff --git a/test/integration-fabric.e2e-spec.ts b/test/integration-fabric.e2e-spec.tsnew file mode 100644index 000000000..c1a31a801--- /dev/null+++ b/test/integration-fabric.e2e-spec.ts@@ -0,0 +1,152 @@+// archiver v8 is ESM-only and is pulled in transitively via the @Global StorageModule when+// AppModule boots; stub it so ts-jest (CommonJS) can load the module graph.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++import { createHmac, randomBytes } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication, ValidationPipe } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { json, urlencoded, Request } from 'express';+import { AppModule } from './../src/app.module';+import { PluginLoaderService } from './../src/core/plugins/plugin-loader.service';+import { PluginInstance } from './../src/modules/integration/entities/plugin-instance.entity';++/**+ * Byte-exact HTTP coverage for the Integration SDK v1 ingress contract, over the seam the+ * service-level golden test (src/modules/integration/ingress-golden.spec.ts) can't reach: the real+ * @Public IngressController route, the real raw-body json({verify}) wiring mirrored from main.ts+ * (Nest's testing module does not replicate bootstrap()'s manual body-parser setup), and a real+ * TypeORM-persisted plugin instance. PluginLoaderService's engine-registration side effects are left+ * real (they run at module init regardless); only the two entry points the ingress pipeline calls+ * (getPlugin, dispatchWebhookForInstance) are spied so no live sandbox worker is required — the+ * contract under test is the wire path (verify -> dedup -> dispatch), not a real WhatsApp send.+ *+ * This is the production address, `app.setGlobalPrefix('api')` + `@Controller('ingress')` composing to+ * a single `/api/ingress/...` (matching the metrics.controller.ts @Public precedent), and the+ * `:pluginId/:instanceId/*path` wildcard reading `req.params.path` — the named-wildcard form Express 5+ * / path-to-regexp v8 requires (see ingress.controller.ts for the routing fix itself).+ */+describe('Integration Fabric ingress (e2e)', () => {+ let app: INestApplication<App>;+ let instanceRepo: Repository<PluginInstance>;+ let dispatchWebhookForInstance: jest.Mock;++ const secret = randomBytes(32).toString('hex');+ const raw = readFileSync(+ join(__dirname, '../src/modules/integration/__fixtures__/chatwoot-message_created.json'),+ 'utf8',+ );+ const sig = 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex');++ // The real production address: main.ts's setGlobalPrefix('api') + the controller's bare+ // @Controller('ingress') compose to a single /api/ingress/... path.+ const INGRESS_PATH = '/api/ingress/chatwoot/acct1/chatwoot';++ const ingressManifestRoute = {+ route: 'chatwoot',+ mode: 'async' as const,+ verify: 'core' as const,+ maxBodyBytes: 262144,+ signature: {+ scheme: 'hmac-sha256' as const,+ header: 'X-Chatwoot-Signature',+ contentTemplate: '{rawBody}',+ encoding: 'hex' as const,+ prefix: 'sha256=',+ },+ dedupHeader: 'x-chatwoot-delivery',+ };++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();++ app = moduleFixture.createNestApplication();+ app.setGlobalPrefix('api');+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ // Mirror main.ts's raw-body wiring: the ingress controller reads req.rawBody (stashed by this+ // verify callback) so the HMAC would be checked over the EXACT bytes the provider signed. Nest's+ // testing module does not install this on its own — it's manual bootstrap()-only wiring in main.ts.+ app.use(+ json({+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {+ req.rawBody = buf;+ },+ }),+ );+ app.use(urlencoded({ extended: true }));+ await app.init();++ instanceRepo = app.get(getRepositoryToken(PluginInstance, 'data'));++ // The real PluginLoaderService boots the built-in engine plugins (wwjs/Baileys) at onModuleInit,+ // so it can't be blanket-replaced with a useValue stub without reimplementing that bootstrap. Instead+ // spy on just the two entry points the ingress pipeline calls, leaving engine registration real.+ const loader = app.get(PluginLoaderService);+ const realGetPlugin = loader.getPlugin.bind(loader);+ jest.spyOn(loader, 'getPlugin').mockImplementation((pluginId: string) => {+ if (pluginId === 'chatwoot') {+ return { manifest: { ingress: [ingressManifestRoute] } } as unknown as ReturnType<typeof loader.getPlugin>;+ }+ return realGetPlugin(pluginId);+ });+ dispatchWebhookForInstance = jest.spyOn(loader, 'dispatchWebhookForInstance').mockResolvedValue(undefined) as never;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ beforeEach(async () => {+ dispatchWebhookForInstance.mockClear();+ await instanceRepo.save(+ instanceRepo.create({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ secret,+ enabled: true,+ sessionScope: 'sess-1',+ verifyToken: null,+ config: null,+ }),+ );+ });++ it('accepts a correctly signed Chatwoot delivery over the real /api/ingress path', async () => {+ // This is the request shape the SDK v1 design doc and the golden fixture describe, sent to the+ // real production address. QUEUE_ENABLED is unset in this test env, so IngressService's factory+ // wires the inline-dispatch fallback — dispatchWebhookForInstance runs synchronously before the 202.+ const res = await request(app.getHttpServer())+ .post(INGRESS_PATH)+ .set('X-Chatwoot-Signature', sig)+ .set('X-Chatwoot-Delivery', 'delivery-http-1')+ .set('Content-Type', 'application/json')+ .send(raw);++ expect(res.status).toBe(202);+ expect(dispatchWebhookForInstance).toHaveBeenCalledTimes(1);+ });++ it('rejects a tampered signature with 401 and never dispatches', async () => {+ const res = await request(app.getHttpServer())+ .post(INGRESS_PATH)+ .set('X-Chatwoot-Signature', 'sha256=' + '0'.repeat(64))+ .set('X-Chatwoot-Delivery', 'delivery-http-2')+ .set('Content-Type', 'application/json')+ .send(raw);++ expect(res.status).toBe(401);+ expect(dispatchWebhookForInstance).not.toHaveBeenCalled();+ });+});