Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(integration): declarative sync-response contract for ingress routes (#699)
Yudhi Armyndharis91c065cdf0aa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e37a618d..3d007c036 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Integration SDK v1 `response` contract for inbound routes.** A route may now declare a host-side+ `preflight` (today: `session-alive`, returning 503 for a definitively-dead WhatsApp session) and a+ declarative `ack` (status/body/headers) returned synchronously to the provider. The plugin ALWAYS runs+ async (enqueued, full DLQ/retry); for routes declaring `response`, the ack is returned without awaiting+ enqueue so a queue-disabled deployment cannot block the provider's deadline. A dead session (no live+ engine or `FAILED`) on a concrete-scoped route now fails fast with 503 instead of being swallowed into+ 202; recoverable statuses still 202+enqueue and let the worker fail fast. The inert `mode: 'sync-reply'`+ value is deprecated in favor of `response` (kept for SDK v1 additive-only compatibility). Routes with no+ `response` are byte-identical to today's default fast-ack.+## [0.8.15] - 2026-07-11- **WhatsApp Web sessions no longer wedge silently in `INITIALIZING` forever.** `engine.initialize()` was awaited with no timeout, and neither whatsapp-web.js nor Puppeteer bounds the initial browser launch/navigation (`page.goto` is called with `timeout: 0` and the web-version-cache fetch carries no timeout). If Chromium stalled under container memory pressure — realistic at the documented 2 GB Standard profile — the await never resolved or rejected: the session sat in `INITIALIZING` indefinitely, `GET /sessions/:id/qr` 400'd forever, and nothing was logged. The #635 abandoned-engine reaper is reactive (terminal `onError` / rejected re-init only), so nothing recovered it. `initializeEngine()` now races `engine.initialize()` against a deadline derived from the configured auth wait (floor 60 s, or `WWEBJS_AUTH_TIMEOUT_MS` + 30 s when an operator has raised that for slow first boots) so a legitimate slow init is never cut short; on timeout it force-kills the wedged browser, marks the session `DISCONNECTED` (retryable, so the existing reconnect backoff picks it up), and rethrows — surfacing the failure to a manual `POST /start` caller instead of hanging. The race's catch is scoped to the timeout only (`EngineInitTimeoutError`): a real init rejection (e.g. Chromium can't launch) propagates untouched so `start()`'s existing `FAILED`+reason diagnostics are preserved — handling both in one catch would downgrade real failures to `DISCONNECTED` and hide their reason. Thanks @INAPA-desarrolloTIC. [#667]diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 94b6ba51c..85b071e0d 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -84,6 +84,11 @@ controller: authenticate → normalize → persist → enqueue → fast `202`) da **dispatch tier** (the processor that runs the plugin). A provider spike, a slow adapter, or a wedgedplugin never loses events; the tiers scale independently with backpressure.+Alongside this async pipeline, a route may additionally declare a `response` contract — host-side+`preflight` checks and a declarative `ack` — that shapes the synchronous HTTP response the provider sees+**without** altering the dispatch model. The plugin still always runs async (enqueued, full DLQ/retry);+`response` only controls what the provider receives back on the request socket. See §25.4 and §25.8.+## 25.4 Core components- **Ingress RPC** — the one new primitive. Delivers a verified inbound request into the worker and returns@@ -91,7 +96,16 @@ plugin never loses events; the tiers scale independently with backpressure.- **Ingress controller** — a `@Public` endpoint (`POST|GET /api/ingress/:pluginId/:instanceId/:route`).It is public to the API-key guard because an external provider cannot present the gateway's API key, soit self-validates (see §25.6). It never runs the plugin inline — providers enforce short acknowledgement- deadlines, so the controller fast-acks and defers the work to the queue.+ deadlines, so the controller fast-acks and defers the work to the queue. A route may additionally+ declare a host-side `response` contract that shapes that synchronous reply without making the plugin+ inline. Its `preflight` checks (today: `session-alive`) run **after** signature verification and+ **before** the dedup persist — returning `503` only for a definitively-dead concrete-scoped WhatsApp+ session (no live engine or `FAILED`); recoverable statuses and `READY` pass through to a normal+ `202`+enqueue so the worker can still fail fast and the dedup row still holds the delivery. A declared+ `ack` (`status`/`body`/`headers`) replaces the default `202 accepted`. For a route declaring `response`,+ the ack is returned without awaiting enqueue so a queue-disabled deployment cannot block the provider's+ deadline; the dedup row already persisted is the durability handle. A route with no `response` is+ byte-identical to today's default fast-ack.- **Plugin instance** — a first-class `instanceId` namespaced under a `pluginId`. One adapter can backmany instances (for example, one external account per WhatsApp number). Each instance owns a host-mintedingress secret, a resolved session scope, and a config slice. It is a serializable field threaded@@ -162,6 +176,16 @@ major, and the surface is **additive-only** within a major. The worker-facing AP`ctx.registerWebhook(...)` (claim an inbound route), `ctx.conversations.send(...)` (normalized reply), andper-instance mapping and handover helpers.+Within major 1 the surface grows additively. A route's optional `response` contract — `preflight[]`+(host-side checks such as `session-alive`, evaluated after signature verify), `ack{}` (`status`/`body`/+`headers`, rendered host-side with `{rawBody}`/`{timestamp}`/`{id}` templates from the verified request),+and an advisory `deadlineMs` — lets an adapter shape the synchronous HTTP response the provider sees; the+plugin still always runs async, and a route with no `response` is byte-identical to today's default+fast-ack. The `mode: 'sync-reply'` value is **deprecated** in favor of `response`: it was inert dead code+that was never wired to the HTTP response (the pipeline is always async + fast-ack), and it is kept in the+`mode` union only to preserve SDK v1 additive-only compatibility — do not remove it within major 1, and do+not rely on it at runtime.+The full SDK reference — every manifest field, the envelope schema, the lifecycle, and the goldencompatibility fixtures — is published alongside the first adapter, so it documents a contract that canactually be exercised end to end. Until then this document and the manifest types are the source of truth.diff --git a/src/core/plugins/plugin-manifest-ingress.spec.ts b/src/core/plugins/plugin-manifest-ingress.spec.tsindex d78f12d79..d6df0d85b 100644--- a/src/core/plugins/plugin-manifest-ingress.spec.ts+++ b/src/core/plugins/plugin-manifest-ingress.spec.ts@@ -81,3 +81,60 @@ describe('warnUnauthenticatedIngressRoutes', () => {expect(logger.warn).not.toHaveBeenCalled();});});++function manifestWithRoute(overrides: Record<string, unknown> = {}) {+ return {+ id: 'p',+ name: 'p',+ version: '1.0.0',+ type: 'extension',+ main: 'index.js',+ sdkVersion: '1',+ permissions: ['webhook:ingress'],+ ingress: [+ { route: 'r', mode: 'async', verify: 'core', maxBodyBytes: 1024, signature: { scheme: 'none' }, ...overrides },+ ],+ } as never;+}++describe('validateIngressManifest: response contract', () => {+ it('accepts a route with no response (default fast-ack)', () => {+ expect(() => validateIngressManifest(manifestWithRoute())).not.toThrow();+ });++ it('accepts a valid response contract', () => {+ expect(() =>+ validateIngressManifest(+ manifestWithRoute({+ response: {+ preflight: [{ type: 'session-alive' }],+ ack: { status: 200, body: '{"ok":true}', headers: { 'content-type': 'application/json' } },+ },+ }),+ ),+ ).not.toThrow();+ });++ it('rejects an out-of-range ack.status', () => {+ expect(() => validateIngressManifest(manifestWithRoute({ response: { ack: { status: 99 } } }))).toThrow(+ /ack\.status/,+ );+ expect(() => validateIngressManifest(manifestWithRoute({ response: { ack: { status: 600 } } }))).toThrow(+ /ack\.status/,+ );+ });++ it('rejects a CR/LF in an ack header value (injection guard)', () => {+ expect(() =>+ validateIngressManifest(+ manifestWithRoute({ response: { ack: { headers: { 'content-type': 'text/plain\r\nX-Injected: yes' } } } }),+ ),+ ).toThrow(/invalid characters/);+ });++ it('rejects a non-token ack header name', () => {+ expect(() =>+ validateIngressManifest(manifestWithRoute({ response: { ack: { headers: { 'bad header': 'x' } } } })),+ ).toThrow(/'bad header'/);+ });+});diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex aec44c42d..4bd2a405f 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -197,9 +197,38 @@ export interface IngressChallengeSpec {echoParam: string;}+/** A host-side preflight check on an inbound route, evaluated AFTER signature verify and BEFORE the+ * dedup persist. First failure short-circuits to its mapped HTTP status. O(1), never initializes the+ * engine, never mutates state. */+export type IngressPreflightCheck = {+ // Reject (503) when the route's concrete-scoped WhatsApp session is not alive (no live engine, or+ // EngineStatus.FAILED). Recoverable statuses (INITIALIZING/QR_READY/AUTHENTICATING/DISCONNECTED) and+ // READY pass through to a normal 202+enqueue so the worker can fail fast and the dedup row holds the+ // delivery. Skipped for wildcard (sessionScope null/'*') scopes — there is no single session to probe.+ type: 'session-alive';+};++/** Declares the synchronous HTTP response an inbound route returns to the provider, computed entirely+ * host-side. The plugin ALWAYS runs async (enqueued, full DLQ/retry) regardless of this contract. */+export interface IngressResponseContract {+ preflight?: IngressPreflightCheck[];+ ack?: {+ status?: number; // default 202+ body?: string; // literal, or a '{rawBody}'/'{timestamp}'/'{id}' template rendered host-side+ headers?: Record<string, string>; // static; validated at load (HTTP-token name, no CR/LF value)+ };+ deadlineMs?: number; // documented provider ack budget (advisory; not enforced)+}+/** 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+ /**+ * @deprecated 'sync-reply' is inert dead code since the P0 substrate (#568) and is NOT wired to the+ * HTTP response — the pipeline is always async + fast-ack. Declare synchronous response behavior via+ * `response` instead. Kept in the union only to preserve SDK v1 additive-only compatibility; do not+ * remove within major 1, and do not rely on either value at runtime.+ */mode: 'async' | 'sync-reply';signature: IngressSignatureSpec;challenge?: IngressChallengeSpec;@@ -209,6 +238,9 @@ export interface PluginIngressRoute {// 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 };+ /** Optional synchronous-response contract (host-side preflight + ack). Additive; absent = today's+ * default 202 fast-ack, byte-identical. Validated by validateIngressManifest. */+ response?: IngressResponseContract;}// Normalized outbound envelope for ctx.conversations.send (POJO across the wire).@@ -226,6 +258,11 @@ export interface ConversationSendEnvelope {/** Integration SDK major version this host supports. A plugin whose `sdkVersion` major differs is refused. */export const SUPPORTED_SDK_MAJOR = 1;+// ack header guards: name must be an RFC 7230 token (no spaces/separators), value must contain no+// CR/LF (header-injection guard). The header source is the static manifest, validated once at load.+const HTTP_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;+const HTTP_HEADER_VALUE_NO_CRLF = /^[^\r\n]*$/;+/*** 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@@ -255,6 +292,28 @@ export function validateIngressManifest(manifest: PluginManifest): void {`Plugin ${manifest.id}: route '${r.route}' toleranceSec must be > 0 (a replay guard would be a no-op)`,);}+ if (r.response) {+ const ackStatus = r.response.ack?.status;+ if (ackStatus !== undefined && (!Number.isInteger(ackStatus) || ackStatus < 100 || ackStatus > 599)) {+ throw new Error(+ `Plugin ${manifest.id}: route '${r.route}' response.ack.status must be a valid HTTP status (100-599)`,+ );+ }+ if (r.response.ack?.headers) {+ for (const [name, value] of Object.entries(r.response.ack.headers)) {+ if (!HTTP_HEADER_NAME.test(name)) {+ throw new Error(+ `Plugin ${manifest.id}: route '${r.route}' response.ack header name '${name}' is not a valid HTTP token`,+ );+ }+ if (!HTTP_HEADER_VALUE_NO_CRLF.test(value)) {+ throw new Error(+ `Plugin ${manifest.id}: route '${r.route}' response.ack header '${name}' has invalid characters (CR/LF forbidden)`,+ );+ }+ }+ }+ }}}diff --git a/src/modules/integration/ingress-ack.spec.ts b/src/modules/integration/ingress-ack.spec.tsnew file mode 100644index 000000000..e190ace4a--- /dev/null+++ b/src/modules/integration/ingress-ack.spec.ts@@ -0,0 +1,31 @@+import { renderAck } from './ingress-ack';++const ctx = { rawBody: '{"a":1}', timestamp: '1700000000', id: 'd1' };++describe('renderAck', () => {+ it('returns the default 202 ack when no spec is declared', () => {+ expect(renderAck(undefined, ctx)).toEqual({ status: 202, body: 'accepted' });+ });++ it('renders a declared status and body verbatim', () => {+ expect(renderAck({ status: 200, body: '{"ok":true}' }, ctx)).toEqual({ status: 200, body: '{"ok":true}' });+ });++ it('substitutes {rawBody}/{timestamp}/{id} templates', () => {+ expect(renderAck({ body: 'echo:{rawBody}:{id}:{timestamp}' }, ctx).body).toBe('echo:{"a":1}:d1:1700000000');+ });++ it('passes through declared headers', () => {+ expect(renderAck({ headers: { 'content-type': 'application/json' } }, ctx).headers).toEqual({+ 'content-type': 'application/json',+ });+ });++ it('substitutes literally even when rawBody contains $ characters (no regex/$ semantics)', () => {+ expect(renderAck({ body: '{rawBody}' }, { ...ctx, rawBody: '$&$`$1' }).body).toBe('$&$`$1');+ });++ it('omits body and headers when not declared', () => {+ expect(renderAck({ status: 204 }, ctx)).toEqual({ status: 204 });+ });+});diff --git a/src/modules/integration/ingress-ack.ts b/src/modules/integration/ingress-ack.tsnew file mode 100644index 000000000..c897bb02a--- /dev/null+++ b/src/modules/integration/ingress-ack.ts@@ -0,0 +1,37 @@+import type { IngressResponseContract } from '../../core/plugins/plugin.interfaces';++export interface AckRenderCtx {+ rawBody: string;+ timestamp: string; // epoch seconds, as a string for substitution+ id: string; // delivery id+}++export type AckResult = { status: number; body?: string; headers?: Record<string, string> };++/**+ * Renders the synchronous ack for an inbound route, computed entirely host-side. `spec` is the route's+ * `response.ack` (undefined → the default 202 'accepted'). The body may interpolate `{rawBody}`,+ * `{timestamp}`, `{id}` from the VERIFIED request. Uses split/join (never String.replace with a string+ * pattern, which would interpret `$&`/`$1` in provider-controlled bytes). Total: never throws — on any+ * unexpected input it falls back to the declared literal.+ */+export function renderAck(spec: IngressResponseContract['ack'] | undefined, ctx: AckRenderCtx): AckResult {+ if (!spec) return { status: 202, body: 'accepted' };+ const result: AckResult = { status: spec.status ?? 202 };+ if (spec.body !== undefined) {+ result.body = substitute(spec.body, ctx);+ }+ if (spec.headers) result.headers = { ...spec.headers };+ return result;+}++function substitute(template: string, ctx: AckRenderCtx): string {+ // split/join avoids `$`-interpretation that String.replace applies to the replacement string.+ return template+ .split('{rawBody}')+ .join(ctx.rawBody)+ .split('{timestamp}')+ .join(ctx.timestamp)+ .split('{id}')+ .join(ctx.id);+}diff --git a/src/modules/integration/ingress-preflight.spec.ts b/src/modules/integration/ingress-preflight.spec.tsnew file mode 100644index 000000000..a480c29f7--- /dev/null+++ b/src/modules/integration/ingress-preflight.spec.ts@@ -0,0 +1,66 @@+import { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import { evaluatePreflight } from './ingress-preflight';+import type { IngressRouteDescriptor } from './ingress.service';++function route(response?: { preflight?: any[] }): IngressRouteDescriptor {+ return {+ route: 'r',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ response,+ } as unknown as IngressRouteDescriptor;+}++describe('evaluatePreflight', () => {+ it('passes (null) when no preflight is declared', () => {+ expect(evaluatePreflight(route(), 'sess-1', () => EngineStatus.READY)).toBeNull();+ });++ it('passes when the concrete session is READY', () => {+ expect(+ evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), 'sess-1', () => EngineStatus.READY),+ ).toBeNull();+ });++ it('passes (accept-and-defer) for a recoverable status', () => {+ for (const s of [+ EngineStatus.INITIALIZING,+ EngineStatus.QR_READY,+ EngineStatus.AUTHENTICATING,+ EngineStatus.DISCONNECTED,+ ]) {+ expect(evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), 'sess-1', () => s)).toBeNull();+ }+ });++ it('rejects with 503 when the concrete session is FAILED', () => {+ expect(+ evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), 'sess-1', () => EngineStatus.FAILED),+ ).toEqual({+ status: 503,+ body: 'session not ready',+ });+ });++ it('rejects with 503 when there is no live engine (stopped/deleted)', () => {+ expect(evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), 'sess-1', () => undefined)).toEqual({+ status: 503,+ body: 'session not ready',+ });+ });++ it('skips (passes) for a wildcard scope — no single session to probe', () => {+ expect(+ evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), '*', () => EngineStatus.FAILED),+ ).toBeNull();+ expect(+ evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), null, () => EngineStatus.FAILED),+ ).toBeNull();+ });++ it('skips (passes) when sessionStatus is unwired — pure tests must not false-reject', () => {+ expect(evaluatePreflight(route({ preflight: [{ type: 'session-alive' }] }), 'sess-1', undefined)).toBeNull();+ });+});diff --git a/src/modules/integration/ingress-preflight.ts b/src/modules/integration/ingress-preflight.tsnew file mode 100644index 000000000..2c3fd1061--- /dev/null+++ b/src/modules/integration/ingress-preflight.ts@@ -0,0 +1,34 @@+import { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import type { IngressRouteDescriptor } from './ingress.service';++export type PreflightRejection = { status: number; body: string };++/**+ * Evaluates a route's host-side preflight checks. Returns null to PASS (proceed to dedup + ack + enqueue),+ * or a `{status, body}` to REJECT synchronously. Runs AFTER signature verify and BEFORE the dedup persist+ * (see IngressService.handle) — a rejection therefore writes no dedup row, so a provider retry on the 5xx+ * is treated as new (this is what avoids the dedup trap).+ *+ * `session-alive`: skipped for wildcard (null/'*') scopes and when sessionStatus is unwired; rejects 503+ * only when the concrete session has no live engine or is EngineStatus.FAILED. Recoverable statuses and+ * READY pass through to the normal 202+enqueue path so the worker can fail fast and the delivery stays durable.+ */+export function evaluatePreflight(+ route: IngressRouteDescriptor,+ sessionScope: string | null,+ sessionStatus: ((scope: string) => EngineStatus | undefined) | undefined,+): PreflightRejection | null {+ const checks = route.response?.preflight;+ if (!checks?.length) return null;+ for (const check of checks) {+ if (check.type === 'session-alive') {+ if (!sessionScope || sessionScope === '*') continue; // wildcard: no single session to probe+ if (!sessionStatus) continue; // unwired (pure unit mode): skip rather than false-reject+ const status = sessionStatus(sessionScope);+ if (status === undefined || status === EngineStatus.FAILED) {+ return { status: 503, body: 'session not ready' };+ }+ }+ }+ return null;+}diff --git a/src/modules/integration/ingress.controller.spec.ts b/src/modules/integration/ingress.controller.spec.tsindex da2076bb3..e0e8cb33c 100644--- a/src/modules/integration/ingress.controller.spec.ts+++ b/src/modules/integration/ingress.controller.spec.ts@@ -7,7 +7,7 @@ import { IngressService } from './ingress.service';const RAW = '{\n "event": "message_created",\n "id": 42\n}\n';function fakeRes() {- const captured: { status?: number; body?: string } = {};+ const captured: { status?: number; body?: string; headers?: Record<string, string> } = {};const res = {status: jest.fn((code: number) => {captured.status = code;@@ -17,6 +17,10 @@ function fakeRes() {captured.body = body;return res;}),+ set: jest.fn((headers: Record<string, string>) => {+ captured.headers = headers;+ return res;+ }),} as unknown as Response;return { res, captured };}@@ -65,4 +69,24 @@ describe('IngressController', () => {expect(arg.route).toBe('meta');expect(arg.rawBody).toBe('');});++ it('forwards response headers from the pipeline', async () => {+ const handle = jest.fn().mockResolvedValue({+ status: 200,+ body: '{"ok":true}',+ headers: { 'content-type': 'application/json' },+ });+ const controller = new IngressController({ handle } as unknown as IngressService);+ const { res, captured } = fakeRes();+ const req = {+ method: 'POST',+ params: { path: ['send-sms'] },+ headers: { 'x-delivery': 'd1' },+ rawBody: Buffer.from('{}'),+ } as unknown as Request & { rawBody?: Buffer };+ await controller.receive('p', 'i1', {}, req, res);+ expect(captured.status).toBe(200);+ expect(captured.body).toBe('{"ok":true}');+ expect(captured.headers).toEqual({ 'content-type': 'application/json' });+ });});diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.tsindex 6f2901a95..61329fb7b 100644--- a/src/modules/integration/ingress.controller.ts+++ b/src/modules/integration/ingress.controller.ts@@ -68,6 +68,7 @@ export class IngressController {query,rawBody,});+ if (result.headers) res.set(result.headers);res.status(result.status).send(result.body ?? '');}}diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.tsindex 3cb2f98df..a80edadf1 100644--- a/src/modules/integration/ingress.service.spec.ts+++ b/src/modules/integration/ingress.service.spec.ts@@ -1,4 +1,5 @@import { IngressService, extractConversationId } from './ingress.service';+import { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';function deps(overrides: Record<string, unknown> = {}) {return {@@ -269,3 +270,170 @@ describe('extractConversationId', () => {expect(extractConversationId({ jsonPointer: '/a/b' }, {}, 'not json')).toBeUndefined();});});++describe('IngressService.handle — response contract', () => {+ const baseReq = {+ pluginId: 'p',+ instanceId: 'i1',+ route: 'send-sms',+ method: 'POST',+ headers: { 'x-delivery': 'd1' },+ query: {} as Record<string, string>,+ rawBody: '{}',+ };++ function depsWith(overrides: Record<string, unknown> = {}) {+ return {+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'p:i1',+ pluginId: 'p',+ instanceId: 'i1',+ secret: 's',+ enabled: true,+ sessionScope: 'sess-1',+ verifyToken: null,+ }),+ },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ }),+ events: { recordOrSkip: jest.fn().mockResolvedValue(true) },+ enqueue: jest.fn().mockResolvedValue(undefined),+ log: jest.fn(),+ now: () => 0,+ ...overrides,+ };+ }++ it('rejects 503 on a dead session BEFORE dedup or enqueue (no dedup trap)', async () => {+ const d = depsWith({+ sessionStatus: jest.fn().mockReturnValue(undefined),+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ response: { preflight: [{ type: 'session-alive' }] },+ }),+ });+ const res = await new IngressService(d).handle(baseReq);+ expect(res.status).toBe(503);+ expect(d.events.recordOrSkip).not.toHaveBeenCalled();+ expect(d.enqueue).not.toHaveBeenCalled();+ expect(d.log).toHaveBeenCalledWith(+ 'ingress_preflight_rejected',+ expect.objectContaining({ status: 503, route: 'send-sms' }),+ );+ });++ it('passes a READY session through to ack + enqueue', async () => {+ const d = depsWith({+ sessionStatus: jest.fn().mockReturnValue(EngineStatus.READY),+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ response: { preflight: [{ type: 'session-alive' }] },+ }),+ });+ const res = await new IngressService(d).handle(baseReq);+ expect(res.status).toBe(202);+ expect(d.enqueue).toHaveBeenCalled();+ });++ it('renders a declared ack status/body/headers', async () => {+ const d = depsWith({+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ response: { ack: { status: 200, body: '{"ok":true}', headers: { 'content-type': 'application/json' } } },+ }),+ });+ const res = await new IngressService(d).handle(baseReq);+ expect(res.status).toBe(200);+ expect(res.body).toBe('{"ok":true}');+ expect(res.headers).toEqual({ 'content-type': 'application/json' });+ });++ it('returns the ack for a response route WITHOUT awaiting a slow enqueue', async () => {+ let resolveEnqueue: () => void;+ const enqueuePromise = new Promise<unknown>(resolve => {+ // Promise resolve requires an argument; wrap it so resolveEnqueue stays a 0-arg () => void.+ resolveEnqueue = () => resolve(undefined);+ });+ const d = depsWith({+ enqueue: jest.fn().mockReturnValue(enqueuePromise),+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ response: { ack: { status: 200 } },+ }),+ });+ const res = await new IngressService(d).handle(baseReq);+ expect(res.status).toBe(200); // ack returned before enqueue resolved+ expect(d.enqueue).toHaveBeenCalled();+ resolveEnqueue!();+ });++ it('survives a rejecting enqueue on a response route (defensive .catch, no unhandled rejection)', async () => {+ const d = depsWith({+ log: jest.fn(),+ enqueue: jest.fn().mockRejectedValue(new Error('boom')),+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ response: { ack: { status: 200 } },+ }),+ });+ const res = await new IngressService(d).handle(baseReq);+ expect(res.status).toBe(200); // ack returned despite the rejected enqueue+ // The rejected enqueue is caught + logged, not thrown. Flush microtasks so the .catch handler runs.+ await new Promise(resolve => setImmediate(resolve));+ expect(d.log).toHaveBeenCalledWith(+ 'ingress_enqueue_unhandled',+ expect.objectContaining({ deliveryId: 'd1', error: 'boom' }),+ );+ });++ it('keeps the duplicate path as 200 "duplicate" regardless of a declared ack', async () => {+ const d = depsWith({+ events: { recordOrSkip: jest.fn().mockResolvedValue(false) },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'send-sms',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'none' },+ dedupHeader: 'x-delivery',+ response: { ack: { status: 200, body: '{"ok":true}' } },+ }),+ });+ const res = await new IngressService(d).handle(baseReq);+ expect(res.status).toBe(200);+ expect(res.body).toBe('duplicate');+ expect(d.enqueue).not.toHaveBeenCalled();+ });+});diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex ad9ddc2f1..521b8fca7 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -2,6 +2,9 @@ import { createHash } from 'node:crypto';import { safeEqualStr, verifyIngressSignature } from './ingress-signature';import { PluginIngressRoute } from '../../core/plugins/plugin.interfaces';import { IngressJobData } from '../queue/processors/ingress.processor';+import type { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import { evaluatePreflight } from './ingress-preflight';+import { renderAck } from './ingress-ack';export interface IngressRequest {pluginId: string;@@ -43,6 +46,14 @@ export interface IngressDeps {// Returns an enqueue outcome (queued/dispatched/failed); handle() ignores it — only durability// follow-up paths like redrive act on it. Typed as unknown here to keep this pure module decoupled.enqueue: (data: IngressJobData, jobId: string) => Promise<unknown>;+ // Optional host-side session-liveness probe for the `session-alive` preflight: returns the in-memory+ // EngineStatus for a concrete session scope, or undefined when no engine is live. O(1) (a Map read ++ // field read); MUST NOT call engine.initialize() or any blocking call. Absent (pure unit tests) → the+ // session-alive check skips (passes) rather than false-rejecting.+ sessionStatus?: (scope: string) => EngineStatus | undefined;+ // Optional structured sink for preflight rejections, so operators can audit deliveries that were+ // rejected host-side (and therefore leave no dedup/DLQ row). Absent in pure unit tests.+ log?: (event: string, meta: Record<string, unknown>) => void;now: () => number;}@@ -54,7 +65,7 @@ export interface IngressDeps {export class IngressService {constructor(private readonly deps: IngressDeps) {}- async handle(req: IngressRequest): Promise<{ status: number; body?: string }> {+ async handle(req: IngressRequest): Promise<{ status: number; body?: string; headers?: Record<string, string> }> {const instance = await this.deps.instances.resolve(req.pluginId, req.instanceId);if (!instance || !instance.enabled) return { status: 404, body: 'unknown instance' };@@ -84,6 +95,22 @@ export class IngressService {});if (!verdict.ok) return { status: 401, body: verdict.reason ?? 'signature verification failed' };+ // Host-side preflight (e.g. session-alive). AFTER signature verify (so an unauthenticated caller+ // cannot probe liveness) and BEFORE the dedup persist (so a 5xx-rejected delivery never writes a+ // dedup row that would swallow the provider's retry as a 200 'duplicate' — the dedup trap). A+ // rejection leaves no dedup/DLQ row, so log it for operator audit.+ const preflight = evaluatePreflight(route, instance.sessionScope, this.deps.sessionStatus);+ if (preflight) {+ this.deps.log?.('ingress_preflight_rejected', {+ pluginId: req.pluginId,+ instanceId: req.instanceId,+ route: req.route,+ status: preflight.status,+ sessionScope: instance.sessionScope,+ });+ return { status: preflight.status, body: preflight.body };+ }+const dedupHeader = (route.dedupHeader ?? route.signature.dedupHeader ?? 'x-delivery').toLowerCase();const deliveryId = req.headers[dedupHeader] ?? deriveDeliveryId(req);const payload = { headers: req.headers, query: req.query, body: req.rawBody, rawBody: req.rawBody };@@ -100,19 +127,41 @@ export class IngressService {// 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,- },+ const jobData: IngressJobData = {+ pluginId: req.pluginId,+ instanceId: req.instanceId,+ route: req.route,deliveryId,- );- return { status: 202, body: 'accepted' };+ sessionId: instance.sessionScope ?? undefined,+ providerConversationId,+ payload,+ };++ const ack = renderAck(route.response?.ack, {+ rawBody: req.rawBody,+ timestamp: String(Math.floor(this.deps.now() / 1000)),+ id: deliveryId,+ });++ if (route.response) {+ // Sync-response route: the ack is host-side and final; enqueue (queued or inline) must NOT block+ // it — a queue-disabled deployment otherwise holds the HTTP response for up to the inline dispatch+ // timeout. enqueue() is not awaited; the dedup row already persisted is the durability handle. The+ // .catch() is a defensive guard: enqueue() never rejects today (it swallows inline failures and the+ // factory wrapper writes a DLQ row on 'failed'), but a future regression must not become an unhandled+ // rejection that crashes the process on the ingress hot path.+ void this.deps.enqueue(jobData, deliveryId).catch(err => {+ this.deps.log?.('ingress_enqueue_unhandled', {+ pluginId: req.pluginId,+ instanceId: req.instanceId,+ deliveryId,+ error: err instanceof Error ? err.message : String(err),+ });+ });+ } else {+ await this.deps.enqueue(jobData, deliveryId);+ }+ return ack;}}diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsindex 347a26618..102aef248 100644--- a/src/modules/integration/integration.module.ts+++ b/src/modules/integration/integration.module.ts@@ -15,6 +15,8 @@ import { IntegrationRetentionService } from './integration-retention.service';import { IntegrationInstanceController } from './integration-instance.controller';import { ScopeBindingService } from './scope-binding.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { SessionModule } from '../session/session.module';+import { SessionService } from '../session/session.service';import { createLogger } from '../../common/services/logger.service';/**@@ -25,7 +27,10 @@ import { createLogger } from '../../common/services/logger.service';* PluginLoaderService is @Global (PluginsModule), so it injects without importing that module.*/@Module({- imports: [TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure], 'data')],+ imports: [+ SessionModule,+ TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure], 'data'),+ ],controllers: [IngressController, RedriveController, IntegrationInstanceController],providers: [PluginInstanceService,@@ -42,6 +47,7 @@ import { createLogger } from '../../common/services/logger.service';PluginLoaderService,IngressEnqueueService,getRepositoryToken(IntegrationDeliveryFailure, 'data'),+ SessionService,],useFactory: (instances: PluginInstanceService,@@ -49,13 +55,22 @@ import { createLogger } from '../../common/services/logger.service';loader: PluginLoaderService,ingressEnqueue: IngressEnqueueService,failures: Repository<IntegrationDeliveryFailure>,+ sessions: SessionService,) => {const dlqLogger = createLogger('IngressEnqueue');+ const ingressLogger = createLogger('Ingress');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) },+ // O(1) in-memory liveness probe for the `session-alive` preflight: a Map read + a field read.+ // MUST stay cheap — never call engine.initialize() here (that is the slow/blocking path bounded+ // separately by the #667/#696 init-timeout). Undefined = no live engine (stopped/deleted).+ sessionStatus: (scope: string) => sessions.getEngine(scope)?.getStatus(),+ // Audit sink for preflight rejections (they leave no dedup/DLQ row). The Prometheus counter is+ // a separate follow-up (see plan notes); the structured log is the MVP audit surface.+ log: (event, meta) => ingressLogger.warn(event, meta),// Live ingress delivery: on a swallowed inline-dispatch failure, persist a dead-letter row so// RedriveService can replay it — IngressService.handle() ignores the outcome and always 202s, so// nothing else would. RedriveService calls enqueue() directly (it is already replaying a DLQ