Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): bound ingress replay and dedup-row storage growth (#941)
Yudhi Armyndharis3800dbebd524
diff --git a/.env.example b/.env.exampleindex d386f89a5..190cfc44c 100644--- a/.env.example+++ b/.env.example@@ -334,9 +334,17 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# Integration Fabric delivery retry + retention (the queued path taken when QUEUE_ENABLED=true).# INGRESS_MAX_ATTEMPTS=3 # delivery attempts before an event is dead-lettered (min 1)# INGRESS_RETRY_DELAY_MS=5000 # base for exponential backoff between attempts (ms)-# INGRESS_RETENTION_DAYS=90 # days to keep ingress_events + delivery_failures rows. <=0 disables-# # pruning (rows accumulate indefinitely) — set deliberately for+# INGRESS_DEDUP_RETENTION_DAYS=7 # days to keep ingress_events dedup rows (default 7). Dedup rows+# # are a delivery-id oracle, not an audit log — their payloads are+# # retired on dispatch. <=0 does NOT disable this prune (an+# # unpruned dedup table grows without bound); it falls back to 7.+# INGRESS_RETENTION_DAYS=90 # days to keep integration_delivery_failures (DLQ) rows. <=0+# # disables that prune only — set deliberately for# # compliance-sensitive deployments that manage retention upstream.+# INGRESS_TIMESTAMP_TOLERANCE_SEC=300 # replay window for a declared ingress timestampHeader when the+# # manifest sets no toleranceSec (also the standard-webhooks+# # fallback). Must be a positive integer; invalid values fall back+# # to 300.# Concurrency of the BullMQ workers that process queued webhooks and ingress events. Only meaningful# when QUEUE_ENABLED=true. Ordering within one conversation is preserved by a per-conversation lock,diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex e00daba13..6b4471f40 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -134,7 +134,15 @@ Four tables live on the data connection, each created by a hand-authored dual-dimarkers the reconciler sweeps on: `dispatchState` (`pending | dispatched | failed`, `NULL` on rowsthat predate the columns on a synchronize-bootstrapped DB — "not watched"), `dispatchAttempts`, and`lastDispatchAt`. New rows are `pending`; a recorded enqueue outcome flips them to `dispatched`;- `failed` is terminal (recovery continues via the DLQ row + redrive).+ `failed` is terminal (recovery continues via the DLQ row + redrive). The row carries the **full+ request payload only while it is the sole durability handle** — from the persist until the dispatch+ outcome is recorded. Once the dispatch tier owns the delivery (the BullMQ job data, or the DLQ row+ on failure), the payload is retired to `NULL` and the row slims to its dedup marker plus+ `payloadHash` (a sha256 of the raw body kept for operator correlation). This keeps steady-state+ growth at a few hundred bytes per delivery instead of up to 2× `maxBodyBytes`; dedup rows are+ pruned on their own short window (`INGRESS_DEDUP_RETENTION_DAYS`, default 7 — a dedup oracle is not+ an audit log, and `<= 0` falls back to the default rather than disabling the prune into unbounded+ growth).- **`integration_delivery_failures`** — a dead-letter record of last resort for both directions, with aredrive path (added in P1).@@ -150,7 +158,17 @@ Four tables live on the data connection, each created by a hand-authored dual-di`(instanceId, providerDeliveryId)` deduplication plus a queue job id keyed on the delivery id providesbest-effort de-duplication when the provider supplies a stable delivery id. Standard Webhooks defaultsto its signed `webhook-id`; other handlers must remain idempotent because arbitrary provider headers- are not authenticated by every scheme.+ are not authenticated by every scheme. Freshness is enforced whenever a route declares+ `signature.timestampHeader`: the declared `toleranceSec` wins, and otherwise the host default+ (`INGRESS_TIMESTAMP_TOLERANCE_SEC`, default 300) applies — a declared timestamp is never accepted+ without a freshness check. Freshness alone is not replay protection, though: an **unsigned**+ timestamp can simply be re-minted by whoever replays a captured (body, signature) pair with a new+ delivery id. hmac-sha256 routes should therefore bind the timestamp into the signed bytes by+ including `{timestamp}` in the `contentTemplate` (e.g. `{timestamp}.{rawBody}`, the Chatwoot shape)+ so the signature itself expires with the window; the loader warns when a route declares the header+ without signing it (or signs the token without declaring the header). `standard-webhooks` binds+ id + timestamp by spec. A provider that sends no timestamp header at all stays outside the replay+ window by construction — dedup and handler idempotency are its only protections.- **Tenancy scoping.** Every durable ingress artifact — secret, dedup store, and dead-letter row — ispartitioned by instance, and downstream capability calls carry the instance's resolved session scope, soa cross-tenant send is blocked host-side.@@ -183,12 +201,23 @@ with the provider already acknowledged. The **ingress reconciler** closes that w(`INGRESS_RECONCILE_BATCH_SIZE`, default 50) of `pending` rows whose last activity is older than agrace period (`INGRESS_RECONCILE_GRACE_MS`, default 60s), through the same queue-or-inline enqueue thelive path uses and with the original delivery id as job id, so a replay is idempotent against a job-the crashed live path may have enqueued. The stored row is sufficient for re-dispatch — it is the full-verified request (headers/query/body/rawBody) plus the route and session provenance; the conversation-lane is re-derived from the current manifest. After `INGRESS_RECONCILE_MAX_ATTEMPTS` (default 5) the-row goes `failed` (terminal) and a dead-letter row is guaranteed to exist, so recovery continues-through the bounded redrive path instead of an infinite replay loop; a successful replay retires any-live-path dead-letter row for the same delivery so a later redrive never double-delivers.+the crashed live path may have enqueued. The stored row is sufficient for re-dispatch — while+`pending` it is the full verified request (headers/query/body/rawBody) plus the route and session+provenance; the conversation lane is re-derived from the current manifest. After+`INGRESS_RECONCILE_MAX_ATTEMPTS` (default 5) the row goes `failed` (terminal) and a dead-letter row+is guaranteed to exist **before** the row's payload is retired, so recovery continues through the+bounded redrive path instead of an infinite replay loop; a successful replay likewise retires the+row's payload with the `dispatched` mark and retires any live-path dead-letter row for the same+delivery so a later redrive never double-delivers. A `pending` row found without a payload (only+possible for imported/corrupt history — payloads are retired only with a recorded outcome) is+skipped loudly, never replayed empty.++Table growth is bounded by construction rather than by operator hygiene: the per-instance ingress+throttle caps the row-creation rate, dispatched rows slim to a marker + hash, and the two retention+windows prune what remains — `INGRESS_DEDUP_RETENTION_DAYS` (default 7) for the dedup oracle and+`INGRESS_RETENTION_DAYS` (default 90, `<= 0` disables) for the DLQ. There is deliberately no+per-instance row-count cap: eviction under a flood of forged delivery ids would silently drop legit+dedup rows and re-admit their replays, which is worse than the bounded growth it would prevent.## 25.8 The Integration SDK (v1)@@ -205,13 +234,16 @@ The `signature.scheme` field enumerates `hmac-sha256` (HMAC over a `contentTempl`standard-webhooks` scheme verifies a [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks)payload host-side — Supabase Auth's Send-SMS hook and any Svix-routed provider speak it natively. Its wireformat is fixed by the spec (the `webhook-id` / `webhook-timestamp` / `webhook-signature` header triple,-signed over `${id}.${timestamp}.${rawBody}`), so only `toleranceSec` (default 300) and `dedupHeader`-apply; `header`, `contentTemplate`, `encoding`, `prefix`, and `timestampHeader` are ignored, and the+signed over `${id}.${timestamp}.${rawBody}`), so only `toleranceSec` (falling back to the host+`INGRESS_TIMESTAMP_TOLERANCE_SEC`, default 300) and `dedupHeader` apply; `header`, `contentTemplate`,+`encoding`, `prefix`, and `timestampHeader` are ignored, and theoperator pastes the provider's Svix secret (`v1,whsec_<base64>`) as the instance secret. It is therecommended scheme for Standard-Webhooks providers: because the `session-alive` preflight (§25.4) runs*after* signature verification, an unauthenticated caller can no longer use that preflight as a livenessoracle on a route that previously declared `scheme: "none"`. The existing `hmac-sha256`/`shared-secret`/-`none` behavior is unchanged.+`none` behavior is unchanged. For `hmac-sha256`, declaring `timestampHeader` always activates the replay+window (§25.6) — declare it together with a `contentTemplate` that includes `{timestamp}` so the checked+timestamp is also signed.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`/diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 663dcb441..114450e00 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -27,6 +27,7 @@ import {PluginConfigSchema,validateIngressManifest,warnUnauthenticatedIngressRoutes,+ warnUnsignedTimestampRoutes,} from './plugin.interfaces';import { validatePluginManifest } from './plugin-manifest';import { effectiveNetAllow, isNetHostAllowed, performPluginFetch } from './plugin-net';@@ -413,6 +414,10 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap// reminds them to front the URL with a network/reverse-proxy ACL.warnUnauthenticatedIngressRoutes(manifest, this.logger);+ // Same loud-warning treatment for an hmac route whose declared timestamp is not bound into the+ // signature: freshness is enforced, but an unsigned timestamp lets a replay mint a fresh one.+ warnUnsignedTimestampRoutes(manifest, this.logger);+// Check if plugin already loadedif (this.plugins.has(manifest.id)) {throw new Error(`Plugin ${manifest.id} is already loaded`);diff --git a/src/core/plugins/plugin-manifest-ingress.spec.ts b/src/core/plugins/plugin-manifest-ingress.spec.tsindex 4a8113bcb..0af28f0b6 100644--- a/src/core/plugins/plugin-manifest-ingress.spec.ts+++ b/src/core/plugins/plugin-manifest-ingress.spec.ts@@ -1,4 +1,9 @@-import { validateIngressManifest, SUPPORTED_SDK_MAJOR, warnUnauthenticatedIngressRoutes } from './plugin.interfaces';+import {+ validateIngressManifest,+ SUPPORTED_SDK_MAJOR,+ warnUnauthenticatedIngressRoutes,+ warnUnsignedTimestampRoutes,+} from './plugin.interfaces';const baseManifest = () => ({id: 'chatwoot',@@ -116,6 +121,83 @@ describe('warnUnauthenticatedIngressRoutes', () => {});});+describe('warnUnsignedTimestampRoutes', () => {+ const hmacRoute = (signature: Record<string, unknown>) => ({+ id: 'p',+ name: 'p',+ version: '1.0.0',+ main: 'index.js',+ sdkVersion: '1',+ permissions: ['webhook:ingress'],+ ingress: [{ route: 'r', mode: 'async', verify: 'core', maxBodyBytes: 1024, signature }],+ });++ it('warns when a timestampHeader is declared but the contentTemplate does not sign it', () => {+ const logger = { warn: jest.fn() };+ warnUnsignedTimestampRoutes(+ hmacRoute({+ scheme: 'hmac-sha256',+ header: 'X-Sig',+ contentTemplate: '{rawBody}',+ timestampHeader: 'X-Ts',+ }) as never,+ logger,+ );+ expect(logger.warn).toHaveBeenCalledTimes(1);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringMatching(/UNSIGNED/i),+ expect.objectContaining({ pluginId: 'p', route: 'r', action: 'ingress_unsigned_timestamp' }),+ );+ });++ it('warns when the contentTemplate signs {timestamp} but no timestampHeader is declared', () => {+ const logger = { warn: jest.fn() };+ warnUnsignedTimestampRoutes(+ hmacRoute({ scheme: 'hmac-sha256', header: 'X-Sig', contentTemplate: '{timestamp}.{rawBody}' }) as never,+ logger,+ );+ expect(logger.warn).toHaveBeenCalledTimes(1);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringMatching(/no timestampHeader/i),+ expect.objectContaining({ pluginId: 'p', route: 'r', action: 'ingress_unsigned_timestamp' }),+ );+ });++ it('stays silent when the declared timestamp is signed (the bound form)', () => {+ const logger = { warn: jest.fn() };+ warnUnsignedTimestampRoutes(+ hmacRoute({+ scheme: 'hmac-sha256',+ header: 'X-Sig',+ contentTemplate: '{timestamp}.{rawBody}',+ timestampHeader: 'X-Ts',+ toleranceSec: 300,+ }) as never,+ logger,+ );+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it('stays silent when no timestamp is involved at all', () => {+ const logger = { warn: jest.fn() };+ warnUnsignedTimestampRoutes(+ hmacRoute({ scheme: 'hmac-sha256', header: 'X-Sig', contentTemplate: '{rawBody}' }) as never,+ logger,+ );+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it('ignores non-hmac schemes (their wire format is not templatable)', () => {+ const logger = { warn: jest.fn() };+ warnUnsignedTimestampRoutes(hmacRoute({ scheme: 'standard-webhooks', dedupHeader: 'webhook-id' }) as never, logger);+ warnUnsignedTimestampRoutes(+ hmacRoute({ scheme: 'shared-secret', header: 'X-Token', timestampHeader: 'X-Ts' }) as never,+ logger,+ );+ expect(logger.warn).not.toHaveBeenCalled();+ });+});+function manifestWithRoute(overrides: Record<string, unknown> = {}) {return {id: 'p',diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 2f1d4af9a..9f4352e05 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -187,8 +187,8 @@ export interface IngressSignatureSpec {* `webhook-signature`, signed content `${webhook-id}.${webhook-timestamp}.${rawBody}`, base64* HMAC-SHA256 with the base64-decoded Svix key, `v1,` prefix, space-separated candidate list), so* `header`/`contentTemplate`/`encoding`/`prefix`/`timestampHeader` are IGNORED — only- * `toleranceSec` (default 300) and `dedupHeader` apply. The operator pastes the Svix secret- * (`v1,whsec_<base64>`) as `instance.secret`.+ * `toleranceSec` (falling back to the host default, itself 300) and `dedupHeader` apply. The+ * operator pastes the Svix secret (`v1,whsec_<base64>`) as `instance.secret`.*/scheme: 'hmac-sha256' | 'shared-secret' | 'standard-webhooks' | 'none';header?: string;@@ -197,7 +197,10 @@ export interface IngressSignatureSpec {encoding?: 'hex' | 'base64';prefix?: string;timestampHeader?: string;- toleranceSec?: number; // when present, must be > 0 (see validateIngressManifest)+ // Replay window for the declared timestampHeader. When absent, the host default applies+ // (INGRESS_TIMESTAMP_TOLERANCE_SEC, default 300) — freshness is enforced either way; an explicit+ // value only narrows/widens the window. When present, must be > 0 (see validateIngressManifest).+ toleranceSec?: number;dedupHeader?: string;}@@ -366,6 +369,43 @@ export function warnUnauthenticatedIngressRoutes(}}+/**+ * Warns about hmac-sha256 ingress routes whose declared timestamp is not actually bound into the+ * signature. Declaring `timestampHeader` makes the host enforce timestamp freshness, but freshness+ * alone does not stop a replay: if the provider's `contentTemplate` omits `{timestamp}`, the+ * timestamp is UNSIGNED, so a captured (body, signature) pair can be re-sent with a freshly-minted+ * timestamp and a new delivery id forever. Binding the timestamp (`contentTemplate` containing+ * `{timestamp}`, e.g. `{timestamp}.{rawBody}`) makes the signed bytes expire with the window. The+ * inverse declaration — a `{timestamp}` token with no `timestampHeader` — signs the empty string,+ * which is equally inert. Warn-only (SDK v1 is additive within a major; a load-time rejection would+ * break already-installed manifests). Called from PluginLoaderService.loadPlugin.+ */+export function warnUnsignedTimestampRoutes(+ manifest: PluginManifest,+ logger: { warn: (message: string, context?: Record<string, unknown>) => void },+): void {+ for (const r of manifest.ingress ?? []) {+ if (r.signature.scheme !== 'hmac-sha256') continue; // only hmac templates can bind a timestamp+ const signsTimestamp = (r.signature.contentTemplate ?? '{rawBody}').includes('{timestamp}');+ if (r.signature.timestampHeader && !signsTimestamp) {+ logger.warn(+ `Ingress route '${r.route}' of plugin '${manifest.id}' declares timestampHeader ` ++ `'${r.signature.timestampHeader}' but its contentTemplate does not sign it — the timestamp is ` ++ `freshness-checked but UNSIGNED, so a replayed body can mint a fresh timestamp. Include ` ++ `{timestamp} in the contentTemplate (e.g. '{timestamp}.{rawBody}') to bind it.`,+ { pluginId: manifest.id, route: r.route, action: 'ingress_unsigned_timestamp' },+ );+ } else if (!r.signature.timestampHeader && signsTimestamp) {+ logger.warn(+ `Ingress route '${r.route}' of plugin '${manifest.id}' signs a {timestamp} token but declares no ` ++ `timestampHeader — the token binds the empty string and no freshness check runs. Declare the ` ++ `provider's timestamp header (and optionally toleranceSec) to activate the replay window.`,+ { pluginId: manifest.id, route: r.route, action: 'ingress_unsigned_timestamp' },+ );+ }+ }+}+/*** 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.diff --git a/src/database/migrations/1785600000000-SlimIngressEventPayload.ts b/src/database/migrations/1785600000000-SlimIngressEventPayload.tsnew file mode 100644index 000000000..0226fd8a2--- /dev/null+++ b/src/database/migrations/1785600000000-SlimIngressEventPayload.ts@@ -0,0 +1,134 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Slims the ingress_events dedup row: `payload` becomes nullable (retired to NULL once the dispatch+ * outcome is recorded — the dispatch tier owns it from there) and a permanent `payloadHash` column+ * keeps the content fingerprint.+ *+ * The same pass also RETIRES the payloads of every existing non-'pending' row (NULL/'dispatched'/+ * 'failed' dispatchState): those rows are never replayed — NULL-state rows are unwatched history,+ * 'dispatched' rows are the dispatch tier's concern, 'failed' rows live on through their DLQ row —+ * so their stored payload is dead weight (up to 2x maxBodyBytes per row) and is dropped here rather+ * than left for retention to drain. 'pending' rows keep their payload: the reconciler replays from+ * it. payloadHash is NOT backfilled (SQLite has no portable sha256); legacy rows keep it NULL.+ *+ * Dual-dialect, idempotent: PostgreSQL alters the column in place; SQLite rebuilds the table+ * (mirrors AddMessageStatus) because SQLite cannot drop a NOT NULL constraint. A synchronize-+ * bootstrapped DB already has the new shape, so the payloadHash probe skips the whole migration.+ */+export class SlimIngressEventPayload1785600000000 implements MigrationInterface {+ name = 'SlimIngressEventPayload1785600000000';++ private async hasColumn(queryRunner: QueryRunner, name: string): Promise<boolean> {+ if (queryRunner.connection.options.type === 'postgres') {+ const rows = (await queryRunner.query(+ `SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'ingress_events' AND column_name = '${name}'`,+ )) as unknown[];+ return rows.length > 0;+ }+ const rows = (await queryRunner.query(`PRAGMA table_info("ingress_events")`)) as Array<{ name: string }>;+ return rows.some(r => r.name === name);+ }++ private async isPayloadNullable(queryRunner: QueryRunner): Promise<boolean> {+ if (queryRunner.connection.options.type === 'postgres') {+ const rows = (await queryRunner.query(+ `SELECT is_nullable FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'ingress_events' AND column_name = 'payload'`,+ )) as Array<{ is_nullable: string }>;+ return rows[0]?.is_nullable === 'YES';+ }+ const rows = (await queryRunner.query(`PRAGMA table_info("ingress_events")`)) as Array<{+ name: string;+ notnull: number;+ }>;+ const payload = rows.find(r => r.name === 'payload');+ return payload ? payload.notnull === 0 : true;+ }++ // Retire the payload of every row the reconciler can never replay. Idempotent by nature.+ private async retireNonPendingPayloads(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(+ `UPDATE "ingress_events" SET "payload" = NULL WHERE "dispatchState" IS NULL OR "dispatchState" <> 'pending'`,+ );+ }++ public async up(queryRunner: QueryRunner): Promise<void> {+ const isPostgres = queryRunner.connection.options.type === 'postgres';+ if (await this.hasColumn(queryRunner, 'payloadHash')) return; // already applied (or sync-built)++ if (isPostgres) {+ await queryRunner.query(`ALTER TABLE "ingress_events" ADD COLUMN "payloadHash" varchar NULL`);+ if (!(await this.isPayloadNullable(queryRunner))) {+ await queryRunner.query(`ALTER TABLE "ingress_events" ALTER COLUMN "payload" DROP NOT NULL`);+ }+ await this.retireNonPendingPayloads(queryRunner);+ return;+ }++ // SQLite: rebuild the table with the slim shape (payload nullable + payloadHash), purging+ // non-pending payloads during the copy. No foreign keys reference ingress_events.+ await queryRunner.query(+ `CREATE TABLE "ingress_events_new" (` ++ `"id" varchar PRIMARY KEY NOT NULL, "instanceId" varchar NOT NULL, "pluginId" varchar NOT NULL, ` ++ `"providerDeliveryId" varchar NOT NULL, "route" varchar NOT NULL, "payload" text NULL, ` ++ `"payloadHash" varchar NULL, "sessionId" varchar NULL, ` ++ `"dispatchState" varchar NULL, "dispatchAttempts" integer NOT NULL DEFAULT 0, "lastDispatchAt" datetime NULL, ` ++ `"createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,+ );+ await queryRunner.query(+ `INSERT INTO "ingress_events_new" ("id","instanceId","pluginId","providerDeliveryId","route","payload","payloadHash","sessionId","dispatchState","dispatchAttempts","lastDispatchAt","createdAt") ` ++ `SELECT "id","instanceId","pluginId","providerDeliveryId","route",` ++ ` CASE WHEN "dispatchState" = 'pending' THEN "payload" ELSE NULL END,` ++ ` NULL,"sessionId","dispatchState","dispatchAttempts","lastDispatchAt","createdAt" FROM "ingress_events"`,+ );+ await queryRunner.query(`DROP TABLE "ingress_events"`);+ await queryRunner.query(`ALTER TABLE "ingress_events_new" RENAME TO "ingress_events"`);+ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_ingress_events_instance_delivery" ON "ingress_events" ("pluginId", "instanceId", "providerDeliveryId")`,+ );+ await queryRunner.query(`CREATE INDEX "IDX_ingress_events_createdAt" ON "ingress_events" ("createdAt")`);+ await queryRunner.query(+ `CREATE INDEX "IDX_ingress_events_dispatchState" ON "ingress_events" ("dispatchState", "createdAt")`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ const isPostgres = queryRunner.connection.options.type === 'postgres';+ if (!(await this.hasColumn(queryRunner, 'payloadHash'))) return; // nothing to reverse++ // Rows whose payload was retired get an empty-payload tombstone so NOT NULL can be restored.+ const tombstone = '{"headers":{},"query":{},"body":"","rawBody":""}';+ if (isPostgres) {+ await queryRunner.query(`UPDATE "ingress_events" SET "payload" = '${tombstone}' WHERE "payload" IS NULL`);+ await queryRunner.query(`ALTER TABLE "ingress_events" ALTER COLUMN "payload" SET NOT NULL`);+ await queryRunner.query(`ALTER TABLE "ingress_events" DROP COLUMN "payloadHash"`);+ return;+ }++ await queryRunner.query(+ `CREATE TABLE "ingress_events_old" (` ++ `"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 NULL, ` ++ `"dispatchState" varchar NULL, "dispatchAttempts" integer NOT NULL DEFAULT 0, "lastDispatchAt" datetime NULL, ` ++ `"createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,+ );+ await queryRunner.query(+ `INSERT INTO "ingress_events_old" ("id","instanceId","pluginId","providerDeliveryId","route","payload","sessionId","dispatchState","dispatchAttempts","lastDispatchAt","createdAt") ` ++ `SELECT "id","instanceId","pluginId","providerDeliveryId","route",` ++ ` COALESCE("payload", '${tombstone}'),` ++ ` "sessionId","dispatchState","dispatchAttempts","lastDispatchAt","createdAt" FROM "ingress_events"`,+ );+ await queryRunner.query(`DROP TABLE "ingress_events"`);+ await queryRunner.query(`ALTER TABLE "ingress_events_old" RENAME TO "ingress_events"`);+ await queryRunner.query(+ `CREATE UNIQUE INDEX "UQ_ingress_events_instance_delivery" ON "ingress_events" ("pluginId", "instanceId", "providerDeliveryId")`,+ );+ await queryRunner.query(`CREATE INDEX "IDX_ingress_events_createdAt" ON "ingress_events" ("createdAt")`);+ await queryRunner.query(+ `CREATE INDEX "IDX_ingress_events_dispatchState" ON "ingress_events" ("dispatchState", "createdAt")`,+ );+ }+}diff --git a/src/database/migrations/__tests__/1785600000000-SlimIngressEventPayload.spec.ts b/src/database/migrations/__tests__/1785600000000-SlimIngressEventPayload.spec.tsnew file mode 100644index 000000000..52c050e8c--- /dev/null+++ b/src/database/migrations/__tests__/1785600000000-SlimIngressEventPayload.spec.ts@@ -0,0 +1,115 @@+import { DataSource, QueryRunner } from 'typeorm';+import { AddIntegrationFabric1781900000000 } from '../1781900000000-AddIntegrationFabric';+import { WidenIngressDedupKey1782100000000 } from '../1782100000000-WidenIngressDedupKey';+import { AddIngressEventDispatchState1785112230000 } from '../1785112230000-AddIngressEventDispatchState';+import { SlimIngressEventPayload1785600000000 } from '../1785600000000-SlimIngressEventPayload';++describe('SlimIngressEventPayload migration (sqlite)', () => {+ let ds: DataSource;+ let runner: QueryRunner;++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [], migrations: [] });+ await ds.initialize();+ runner = ds.createQueryRunner();+ await new AddIntegrationFabric1781900000000().up(runner);+ await new WidenIngressDedupKey1782100000000().up(runner);+ await new AddIngressEventDispatchState1785112230000().up(runner);+ });++ afterEach(async () => {+ await runner.release();+ if (ds.isInitialized) await ds.destroy();+ });++ const columns = async (): Promise<Array<{ name: string; notnull: number }>> =>+ (await runner.query(`PRAGMA table_info("ingress_events")`)) as Array<{ name: string; notnull: number }>;++ const insertEvent = (id: string, dispatchState: string | null, payload = '{"rawBody":"x"}') =>+ runner.query(+ `INSERT INTO "ingress_events" ("id","instanceId","pluginId","providerDeliveryId","route","payload","dispatchState","createdAt") ` ++ `VALUES ('${id}','inst','plug','${id}','chatwoot','${payload}',${dispatchState === null ? 'NULL' : `'${dispatchState}'`},datetime('now'))`,+ );++ const payloadOf = async (id: string): Promise<string | null> => {+ const rows = (await runner.query(`SELECT "payload" FROM "ingress_events" WHERE "id" = '${id}'`)) as Array<{+ payload: string | null;+ }>;+ return rows[0].payload;+ };++ it('makes payload nullable, adds payloadHash, retires non-pending payloads, and keeps pending ones', async () => {+ await insertEvent('pending-1', 'pending');+ await insertEvent('dispatched-1', 'dispatched');+ await insertEvent('legacy-1', null); // unwatched history — never replayed+ await insertEvent('failed-1', 'failed');++ await new SlimIngressEventPayload1785600000000().up(runner);++ const cols = await columns();+ expect(cols.map(c => c.name)).toContain('payloadHash');+ expect(cols.find(c => c.name === 'payload')?.notnull).toBe(0);++ // Only 'pending' rows still need their payload (the reconciler replays from it); every other+ // row's stored payload was dead weight.+ expect(await payloadOf('pending-1')).toBe('{"rawBody":"x"}');+ expect(await payloadOf('dispatched-1')).toBeNull();+ expect(await payloadOf('legacy-1')).toBeNull();+ expect(await payloadOf('failed-1')).toBeNull();++ const count = (await runner.query(`SELECT COUNT(*) AS n FROM "ingress_events"`)) as Array<{ n: number }>;+ expect(count[0].n).toBe(4);++ // The rebuild recreates all three indexes (the sqlite_autoindex_* entries come from the+ // varchar PRIMARY KEY itself, on both the old and the rebuilt table — excluded here).+ const indexes = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='ingress_events' AND name NOT LIKE 'sqlite_autoindex%' ORDER BY name`,+ )) as Array<{ name: string }>;+ expect(indexes.map(i => i.name)).toEqual([+ 'IDX_ingress_events_createdAt',+ 'IDX_ingress_events_dispatchState',+ 'UQ_ingress_events_instance_delivery',+ ]);+ });++ it('is idempotent on re-run (payloadHash probe) and never re-purges a live pending row', async () => {+ const mig = new SlimIngressEventPayload1785600000000();+ await mig.up(runner);+ await runner.query(+ `INSERT INTO "ingress_events" ("id","instanceId","pluginId","providerDeliveryId","route","payload","payloadHash","dispatchState","createdAt") ` ++ `VALUES ('live-1','inst','plug','live-1','chatwoot','{"rawBody":"y"}','hash-y','pending',datetime('now'))`,+ );++ await mig.up(runner); // no-op++ expect(await payloadOf('live-1')).toBe('{"rawBody":"y"}');+ const rows = (await runner.query(`SELECT "payloadHash" FROM "ingress_events" WHERE "id" = 'live-1'`)) as Array<{+ payloadHash: string | null;+ }>;+ expect(rows[0].payloadHash).toBe('hash-y');+ });++ it('down() restores payload NOT NULL (tombstoning retired rows) and drops payloadHash', async () => {+ const mig = new SlimIngressEventPayload1785600000000();+ await insertEvent('pending-1', 'pending');+ await mig.up(runner);+ await mig.down(runner);++ const cols = await columns();+ expect(cols.map(c => c.name)).not.toContain('payloadHash');+ expect(cols.find(c => c.name === 'payload')?.notnull).toBe(1);+ expect(await payloadOf('pending-1')).toBe('{"rawBody":"x"}');++ const indexes = (await runner.query(+ `SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='ingress_events' AND name NOT LIKE 'sqlite_autoindex%' ORDER BY name`,+ )) as Array<{ name: string }>;+ expect(indexes.map(i => i.name)).toEqual([+ 'IDX_ingress_events_createdAt',+ 'IDX_ingress_events_dispatchState',+ 'UQ_ingress_events_instance_delivery',+ ]);++ // Tolerates a DB where the migration never ran.+ await expect(mig.down(runner)).resolves.toBeUndefined();+ });+});diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 2813438b9..b2b3fe0a2 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -403,7 +403,9 @@ interface IngressEventRow {pluginId: string;providerDeliveryId: string;route: string;- payload: string | Record<string, unknown>;+ // Retired to NULL once the dispatch outcome is recorded; only 'pending' rows still carry one.+ payload: string | Record<string, unknown> | null;+ payloadHash?: string | null;sessionId: string | null;createdAt: string;}diff --git a/src/modules/integration/entities/ingress-event.entity.ts b/src/modules/integration/entities/ingress-event.entity.tsindex d82b58d91..06faac1bf 100644--- a/src/modules/integration/entities/ingress-event.entity.ts+++ b/src/modules/integration/entities/ingress-event.entity.ts@@ -18,6 +18,12 @@ export type IngressDispatchState = 'pending' | 'dispatched' | 'failed';// Persist-before-ack durable row + inbound dedup oracle. UNIQUE(pluginId, instanceId, providerDeliveryId):// instanceId is only unique within a plugin, so pluginId must be part of the key or two plugins sharing an// instanceId string would drop each other's deliveries as false duplicates.+//+// Storage shape: the FULL payload is carried only while the row is the sole durability handle — from+// recordOrSkip until the dispatch outcome is recorded ('dispatched') or the reconciler dead-letters it+// ('failed'). At that point the dispatch tier owns the payload (the BullMQ job, or the DLQ row on+// failure) and the row's payload is retired to NULL, leaving a slim dedup marker (~hundreds of bytes+// instead of up to 2× maxBodyBytes). payloadHash is kept permanently as the content fingerprint.@Entity('ingress_events')@Index('UQ_ingress_events_instance_delivery', ['pluginId', 'instanceId', 'providerDeliveryId'], { unique: true })@Index('IDX_ingress_events_createdAt', ['createdAt'])@@ -40,8 +46,17 @@ export class IngressEvent {@Column()route: string;- @Column({ type: jsonColumnType() })- payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+ // NULL once the dispatch outcome is recorded (see the storage-shape comment above). The reconciler+ // only replays 'pending' rows, which always still carry the payload. NULL on a 'pending' row is+ // unreadable history (e.g. imported without one) — the reconciler skips it loudly.+ @Column({ type: jsonColumnType(), nullable: true })+ payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string } | null;++ // sha256 hex of the rawBody, written at recordOrSkip. Survives payload retirement so operators can+ // still correlate a dedup row with a provider delivery without storing the payload. NULL on rows+ // that predate the column (no backfill — their payloads are retired anyway).+ @Column({ type: 'varchar', nullable: true })+ payloadHash: string | null;@Column({ type: 'varchar', nullable: true })sessionId: string | null;diff --git a/src/modules/integration/ingress-event.service.spec.ts b/src/modules/integration/ingress-event.service.spec.tsindex c5308c2b0..154cf63d5 100644--- a/src/modules/integration/ingress-event.service.spec.ts+++ b/src/modules/integration/ingress-event.service.spec.ts@@ -4,6 +4,7 @@ import { IngressEventService } from './ingress-event.service';import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';import { WidenIngressDedupKey1782100000000 } from '../../database/migrations/1782100000000-WidenIngressDedupKey';import { AddIngressEventDispatchState1785112230000 } from '../../database/migrations/1785112230000-AddIngressEventDispatchState';+import { SlimIngressEventPayload1785600000000 } from '../../database/migrations/1785600000000-SlimIngressEventPayload';describe('IngressEventService.recordOrSkip', () => {let ds: DataSource;@@ -15,6 +16,7 @@ describe('IngressEventService.recordOrSkip', () => {await new AddIntegrationFabric1781900000000().up(runner);await new WidenIngressDedupKey1782100000000().up(runner);await new AddIngressEventDispatchState1785112230000().up(runner);+ await new SlimIngressEventPayload1785600000000().up(runner);await runner.release();service = new IngressEventService(ds.getRepository(IngressEvent));});@@ -28,6 +30,7 @@ describe('IngressEventService.recordOrSkip', () => {providerDeliveryId: 'd1',route: 'chatwoot',payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ payloadHash: 'hash-of-{}',sessionId: null,});const key = { pluginId: 'plug', instanceId: 'inst', providerDeliveryId: 'd1' };@@ -57,6 +60,13 @@ describe('IngressEventService.recordOrSkip', () => {expect(event.lastDispatchAt).toBeNull();});+ it('keeps the full payload (the reconciler replay source) plus its hash while pending', async () => {+ await service.recordOrSkip(row());+ const event = await stored();+ expect(event.payload).toEqual({ headers: {}, query: {}, body: '{}', rawBody: '{}' });+ expect(event.payloadHash).toBe('hash-of-{}');+ });+it.each(['queued', 'dispatched'] as const)('marks outcome %s as dispatched with a dispatch timestamp',async outcome => {@@ -69,13 +79,28 @@ describe('IngressEventService.recordOrSkip', () => {},);- it('marks outcome failed as still-pending with the attempt counted (reconciler sweeps it)', async () => {+ it.each(['queued', 'dispatched'] as const)(+ 'retires the full payload on outcome %s but keeps the hash and the dedup oracle',+ async outcome => {+ await service.recordOrSkip(row());+ await service.markDispatchOutcome(key, outcome);+ const event = await stored();+ // The dispatch tier owns the payload now — the dedup row slims to its marker + fingerprint.+ expect(event.payload).toBeNull();+ expect(event.payloadHash).toBe('hash-of-{}');+ // Dedup is keyed on (pluginId, instanceId, providerDeliveryId), never on the payload.+ expect(await service.recordOrSkip(row())).toBe(false);+ },+ );++ it('marks outcome failed as still-pending with the attempt counted AND the payload kept (reconciler replays from it)', async () => {await service.recordOrSkip(row());await service.markDispatchOutcome(key, 'failed');const event = await stored();expect(event.dispatchState).toBe('pending');expect(event.dispatchAttempts).toBe(1);expect(event.lastDispatchAt).toBeInstanceOf(Date);+ expect(event.payload).not.toBeNull();// Repeated failures accumulate against the reconciler's replay budget.await service.markDispatchOutcome(key, 'failed');diff --git a/src/modules/integration/ingress-event.service.ts b/src/modules/integration/ingress-event.service.tsindex 92c4fab55..5fe3085e4 100644--- a/src/modules/integration/ingress-event.service.ts+++ b/src/modules/integration/ingress-event.service.ts@@ -12,6 +12,8 @@ export interface IngressEventInput {providerDeliveryId: string;route: string;payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+ // sha256 hex of payload.rawBody — the slim content fingerprint that survives payload retirement.+ payloadHash: string;sessionId: string | null;}@@ -43,8 +45,10 @@ export class IngressEventService {/*** Record the enqueue outcome on the persisted event. 'queued'/'dispatched' mean the event reached* the dispatch tier → 'dispatched' (a later in-tier failure dead-letters via the processor/DLQ, not- * this row). 'failed' (the swallowed inline-dispatch failure) bumps the attempt counter and leaves- * the row 'pending' so the reconciler sweeps it — the live path's own retry signal.+ * this row) — and the full payload is retired to NULL: the dispatch tier now owns it (the BullMQ job+ * data, or the DLQ row on failure), so the dedup row slims down to its hash + metadata. 'failed'+ * (the swallowed inline-dispatch failure) bumps the attempt counter and leaves the row 'pending'+ * WITH its payload so the reconciler can still replay from it — the live path's own retry signal.*/async markDispatchOutcome(key: IngressEventKey, outcome: EnqueueOutcome['outcome']): Promise<void> {if (outcome === 'failed') {@@ -52,6 +56,6 @@ export class IngressEventService {await this.repo.update(key, { lastDispatchAt: new Date() });return;}- await this.repo.update(key, { dispatchState: 'dispatched', lastDispatchAt: new Date() });+ await this.repo.update(key, { dispatchState: 'dispatched', lastDispatchAt: new Date(), payload: null });}}diff --git a/src/modules/integration/ingress-reconciler.service.spec.ts b/src/modules/integration/ingress-reconciler.service.spec.tsindex ddc36cc78..eabe2ee94 100644--- a/src/modules/integration/ingress-reconciler.service.spec.ts+++ b/src/modules/integration/ingress-reconciler.service.spec.ts@@ -94,6 +94,29 @@ describe('IngressReconcilerService.sweep', () => {expect(event.lastDispatchAt).toBeInstanceOf(Date);});+ it('retires the row payload once the replay is dispatched (the job data already carried it)', async () => {+ const id = await insertEvent();++ await service.sweep(OPTS);++ // The replay itself was built from the full stored payload…+ expect(enqueuedJobs()[0][0].payload).toEqual({ headers: {}, query: {}, body: '{}', rawBody: '{}' });+ // …and the dedup row then slimmed down — the dispatch tier owns the payload from here.+ expect((await stored(id)).payload).toBeNull();+ });++ it('skips a pending row whose payload is gone (nothing to replay from) without burning its budget', async () => {+ const id = await insertEvent({ payload: null });++ const stats = await service.sweep(OPTS);++ expect(stats).toMatchObject({ scanned: 0, skipped: 1 });+ expect(enqueue).not.toHaveBeenCalled();+ const event = await stored(id);+ expect(event.dispatchState).toBe('pending');+ expect(event.dispatchAttempts).toBe(0);+ });+it('re-derives the conversation lane from the manifest route instead of degrading per-instance', async () => {getPlugin.mockReturnValue({manifest: { ingress: [{ route: 'chatwoot', conversationId: { jsonPointer: '/conversation/id' } }] },@@ -154,6 +177,7 @@ describe('IngressReconcilerService.sweep', () => {const event = await stored(id);expect(event.dispatchState).toBe('pending');expect(event.dispatchAttempts).toBe(1);+ expect(event.payload).not.toBeNull(); // the next sweep replays from itexpect(await failures.count()).toBe(0);});@@ -166,6 +190,7 @@ describe('IngressReconcilerService.sweep', () => {const event = await stored(id);expect(event.dispatchState).toBe('failed');expect(event.dispatchAttempts).toBe(5);+ expect(event.payload).toBeNull(); // retired — the DLQ row is the payload's new homeconst dlq = await failures.find({ where: { deliveryId: 'd-1' } });expect(dlq).toHaveLength(1);expect(dlq[0]).toMatchObject({@@ -186,6 +211,21 @@ describe('IngressReconcilerService.sweep', () => {expect(enqueue).not.toHaveBeenCalled();});+ it('writes the DLQ row BEFORE retiring the payload on terminal failure (redrive never loses the payload)', async () => {+ await insertEvent({ dispatchAttempts: 4 });+ enqueue.mockResolvedValue({ outcome: 'failed', error: 'sandbox 5xx' });+ const saveSpy = jest.spyOn(failures, 'save');+ const updateSpy = jest.spyOn(events, 'update');++ await service.sweep(OPTS);++ expect(saveSpy).toHaveBeenCalledTimes(1);+ expect(updateSpy).toHaveBeenCalledTimes(1);+ expect(saveSpy.mock.invocationCallOrder[0]).toBeLessThan(updateSpy.mock.invocationCallOrder[0]);+ saveSpy.mockRestore();+ updateSpy.mockRestore();+ });+it('does not write a second DLQ row when the live path already dead-lettered the delivery', async () => {await insertEvent({ dispatchAttempts: 4 });await failures.save(diff --git a/src/modules/integration/ingress-reconciler.service.ts b/src/modules/integration/ingress-reconciler.service.tsindex 9aaee362e..ffe3e7746 100644--- a/src/modules/integration/ingress-reconciler.service.ts+++ b/src/modules/integration/ingress-reconciler.service.ts@@ -49,11 +49,13 @@ export interface IngressReconcileStats {** The reconciler sweeps small batches of stale 'pending' rows and re-dispatches them through the* exact same IngressEnqueueService the live path uses (same deliveryId as BullMQ jobId, so a replay- * is idempotent against a job that did get enqueued). Re-dispatch from the row is sound because the- * row IS the full verified request: payload carries headers/query/body/rawBody, providerDeliveryId is- * the delivery id, and the manifest route re-derives the conversation lane. 'failed'/'dispatched'- * rows are never re-queued: a terminal failure lives in the DLQ (RedriveService), a dispatched event- * is the dispatch tier's concern.+ * is idempotent against a job that did get enqueued). Re-dispatch from the row is sound because a+ * 'pending' row IS the full verified request: payload carries headers/query/body/rawBody,+ * providerDeliveryId is the delivery id, and the manifest route re-derives the conversation lane.+ * (The payload is retired to NULL the moment an outcome is recorded — 'dispatched' rows and DLQ'd+ * 'failed' rows no longer need it — so only 'pending' rows, which always carry it, are replayable.)+ * 'failed'/'dispatched' rows are never re-queued: a terminal failure lives in the DLQ+ * (RedriveService), a dispatched event is the dispatch tier's concern.** Mirrors IntegrationRetentionService's lifecycle: a raw unref'd setInterval started on module init* (first sweep after one interval, so plugin sandboxes have time to boot), cleared on destroy.@@ -112,6 +114,19 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {stats.skipped++;continue;}+ // A 'pending' row without a payload cannot be replayed (payloads are retired only once an+ // outcome is recorded, so this means an imported/corrupt row). Skip it loudly rather than+ // dispatching an empty delivery or spinning the attempt budget on a row that can never fire.+ if (!hasPayload(row)) {+ this.logger.error('Ingress event is pending without a payload; cannot replay', undefined, {+ pluginId: row.pluginId,+ instanceId: row.instanceId,+ deliveryId: row.providerDeliveryId,+ action: 'ingress_reconcile_missing_payload',+ });+ stats.skipped++;+ continue;+ }stats.scanned++;try {const outcome = await this.reconcileRow(row, opts.maxAttempts, now);@@ -135,13 +150,19 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {}}- private async reconcileRow(row: IngressEvent, maxAttempts: number, now: Date): Promise<'replayed' | 'failed'> {+ private async reconcileRow(+ row: IngressEvent & { payload: NonNullable<IngressEvent['payload']> },+ maxAttempts: number,+ now: Date,+ ): Promise<'replayed' | 'failed'> {const jobData = this.jobDataFor(row);// jobId = the ORIGINAL deliveryId: BullMQ dedups a replay against a job that did get enqueued// before the crash, so re-dispatch never double-delivers on the queue path.const { outcome, error } = await this.ingressEnqueue.enqueue(jobData, row.providerDeliveryId);if (outcome !== 'failed') {- await this.events.update({ id: row.id }, { dispatchState: 'dispatched', lastDispatchAt: now });+ // Retire the payload with the outcome: the dispatch tier owns the delivery from here (the+ // BullMQ job data, or a DLQ row on an in-tier failure), so the dedup row slims to its marker.+ await this.events.update({ id: row.id }, { dispatchState: 'dispatched', lastDispatchAt: now, payload: null });// Retire any dead-letter row the live path already wrote for this delivery (the inline-failure// case) — the replay just delivered it, so a later manual redrive must not deliver it again.await this.failures.update(@@ -166,16 +187,15 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {const attempts = (row.dispatchAttempts ?? 0) + 1;const terminal = attempts >= maxAttempts;- await this.events.update(- { id: row.id },- {- dispatchAttempts: attempts,- lastDispatchAt: now,- ...(terminal ? { dispatchState: 'failed' as const } : {}),- },- );if (terminal) {+ // DLQ BEFORE the terminal mark + payload retirement: the dead-letter row is the payload's new+ // home, so it must exist first. ensureDeadLetterRow is idempotent (count-guarded), so a crash+ // between the two writes just makes the next sweep re-take this path and finish the mark.await this.ensureDeadLetterRow(jobData, attempts, error);+ await this.events.update(+ { id: row.id },+ { dispatchAttempts: attempts, lastDispatchAt: now, dispatchState: 'failed', payload: null },+ );this.logger.warn('Ingress event replay budget exhausted; event is dead-lettered', {pluginId: row.pluginId,instanceId: row.instanceId,@@ -183,7 +203,10 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {attempts,action: 'ingress_event_reconcile_exhausted',});+ return 'failed';}+ // Non-terminal: keep the payload — the next sweep replays from it.+ await this.events.update({ id: row.id }, { dispatchAttempts: attempts, lastDispatchAt: now });return 'failed';}@@ -194,7 +217,7 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {* so the replay joins the same per-conversation ordering lane as live deliveries instead of* degrading to the per-instance lane; a hot-swapped/missing route just yields no key.*/- private jobDataFor(row: IngressEvent): IngressJobData {+ private jobDataFor(row: IngressEvent & { payload: NonNullable<IngressEvent['payload']> }): IngressJobData {const route = this.loader.getPlugin(row.pluginId)?.manifest.ingress?.find(candidate => candidate.route === row.route);@@ -224,3 +247,10 @@ export class IngressReconcilerService implements OnModuleInit, OnModuleDestroy {await this.failures.save({ ...buildIngressDeadLetterRow(data, error), attempts });}}++// Narrows a swept row to one that still carries its payload (every replayable 'pending' row does —+// the payload is retired only when an outcome is recorded). Lets the sweep skip a payload-less row+// loudly instead of dispatching an empty delivery.+function hasPayload(row: IngressEvent): row is IngressEvent & { payload: NonNullable<IngressEvent['payload']> } {+ return row.payload !== null;+}diff --git a/src/modules/integration/ingress-signature.spec.ts b/src/modules/integration/ingress-signature.spec.tsindex 78f6429a1..ef497ea12 100644--- a/src/modules/integration/ingress-signature.spec.ts+++ b/src/modules/integration/ingress-signature.spec.ts@@ -60,6 +60,138 @@ describe('verifyIngressSignature', () => {expect(r.ok).toBe(true);});+ // --- default replay window (declared timestampHeader, no toleranceSec) ---+ describe('declared timestampHeader without toleranceSec (host default window)', () => {+ const original = process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC;+ afterEach(() => {+ if (original === undefined) delete process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC;+ else process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC = original;+ });++ const tsSpec = { ...spec, timestampHeader: 'X-Ts', contentTemplate: '{timestamp}.{rawBody}' };+ const signAt = (t: number) => 'sha256=' + createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');++ it('rejects a stale timestamp against the 300s default (previously an always-401 trap)', () => {+ delete process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC;+ const t = 1000;+ const r = verifyIngressSignature(tsSpec, {+ rawBody,+ headers: { 'x-sig': signAt(t), 'x-ts': String(t) },+ secret,+ now: (t + 301) * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/replay|tolerance/i);+ });++ it('accepts a fresh timestamp within the 300s default', () => {+ delete process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC;+ const t = 1000;+ const r = verifyIngressSignature(tsSpec, {+ rawBody,+ headers: { 'x-sig': signAt(t), 'x-ts': String(t) },+ secret,+ now: (t + 10) * 1000,+ instanceId,+ });+ expect(r.ok).toBe(true);+ });++ it('honors INGRESS_TIMESTAMP_TOLERANCE_SEC when the manifest declares no toleranceSec', () => {+ process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC = '10';+ const t = 1000;+ const stale = verifyIngressSignature(tsSpec, {+ rawBody,+ headers: { 'x-sig': signAt(t), 'x-ts': String(t) },+ secret,+ now: (t + 11) * 1000,+ instanceId,+ });+ expect(stale.ok).toBe(false);+ const fresh = verifyIngressSignature(tsSpec, {+ rawBody,+ headers: { 'x-sig': signAt(t), 'x-ts': String(t) },+ secret,+ now: (t + 10) * 1000,+ instanceId,+ });+ expect(fresh.ok).toBe(true);+ });++ it('lets a declared toleranceSec win over the env default', () => {+ process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC = '10';+ const declared = { ...tsSpec, toleranceSec: 300 };+ const t = 1000;+ const r = verifyIngressSignature(declared, {+ rawBody,+ headers: { 'x-sig': signAt(t), 'x-ts': String(t) },+ secret,+ now: (t + 60) * 1000,+ instanceId,+ });+ expect(r.ok).toBe(true);+ });++ it('falls back to the 300s default when the env value is invalid', () => {+ process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC = '0'; // a zero window would reject every delivery+ const t = 1000;+ const r = verifyIngressSignature(tsSpec, {+ rawBody,+ headers: { 'x-sig': signAt(t), 'x-ts': String(t) },+ secret,+ now: (t + 60) * 1000,+ instanceId,+ });+ expect(r.ok).toBe(true);+ });++ it('enforces freshness for shared-secret routes that declare a timestampHeader', () => {+ delete process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC;+ const sharedSpec = { scheme: 'shared-secret' as const, header: 'X-Token', timestampHeader: 'X-Ts' };+ const t = 1000;+ const fresh = verifyIngressSignature(sharedSpec, {+ rawBody,+ headers: { 'x-token': secret, 'x-ts': String(t) },+ secret,+ now: (t + 10) * 1000,+ instanceId,+ });+ expect(fresh.ok).toBe(true);+ const stale = verifyIngressSignature(sharedSpec, {+ rawBody,+ headers: { 'x-token': secret, 'x-ts': String(t) },+ secret,+ now: (t + 301) * 1000,+ instanceId,+ });+ expect(stale.ok).toBe(false);+ });++ it('applies the env default to standard-webhooks when toleranceSec is undeclared', () => {+ process.env.INGRESS_TIMESTAMP_TOLERANCE_SEC = '10';+ const key = Buffer.from('0123456789abcdef0123456789abcdef', 'hex');+ const swSecretLocal = 'v1,whsec_' + key.toString('base64');+ const signSw = (id: string, t: number, body: string) =>+ 'v1,' + createHmac('sha256', key).update(`${id}.${t}.${body}`).digest('base64');+ const r = verifyIngressSignature(+ { scheme: 'standard-webhooks' as const },+ {+ rawBody,+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': signSw('msg_1', 1000, rawBody),+ },+ secret: swSecretLocal,+ now: (1000 + 11) * 1000,+ instanceId,+ },+ );+ expect(r.ok).toBe(false);+ });+ });+it('rejects a missing signature header', () => {const r = verifyIngressSignature(spec, { rawBody, headers: {}, secret, now: 0, instanceId });expect(r.ok).toBe(false);diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.tsindex 511039fb2..8fc6d9051 100644--- a/src/modules/integration/ingress-signature.ts+++ b/src/modules/integration/ingress-signature.ts@@ -13,6 +13,18 @@ export interface VerifyInput {instanceId: string;}+/**+ * The replay window applied when a route declares a timestamp but no explicit `toleranceSec`+ * (standard-webhooks included — the spec fixes the wire format, not the window). Default 300s,+ * matching the Standard Webhooks convention; INGRESS_TIMESTAMP_TOLERANCE_SEC tunes it host-wide.+ * An invalid value (non-integer or <= 0 — a zero window would reject every delivery) falls back+ * to the default, mirroring the other INGRESS_* option resolvers.+ */+export function resolveIngressTimestampToleranceSec(env: NodeJS.ProcessEnv = process.env): number {+ const parsed = Number(env.INGRESS_TIMESTAMP_TOLERANCE_SEC);+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 300;+}+function header(headers: Record<string, string>, name?: string): string | undefined {if (!name) return undefined;return headers[name.toLowerCase()];@@ -33,7 +45,8 @@ function parseWebhookSecret(secret: string): string | undefined {/*** Verify a Standard Webhooks signature. The wire format is fixed by the spec, so only `toleranceSec`- * (default 300) applies — header/contentTemplate/encoding/prefix/timestampHeader are ignored. The+ * (falling back to resolveIngressTimestampToleranceSec, default 300) applies —+ * header/contentTemplate/encoding/prefix/timestampHeader are ignored. The* signature header may carry multiple space-separated `v1,` candidates (key rotation); any match passes.* Pure and total: never throws. Ported from supabase-otp-hook/verify.ts; idiomatic changes: reuse the* existing safeEqualStr (identical to the reference's safeEqual) and the lowercasing `header()` helper@@ -56,7 +69,7 @@ function verifyStandardWebhooks(spec: IngressSignatureSpec, input: VerifyInput):const ts = Number.parseInt(tsRaw, 10);if (!Number.isFinite(ts)) return { ok: false, reason: 'invalid webhook-timestamp' };- const tolerance = spec.toleranceSec ?? 300;+ const tolerance = spec.toleranceSec ?? resolveIngressTimestampToleranceSec();const skewSec = Math.abs(input.now / 1000 - ts);if (skewSec > tolerance) return { ok: false, reason: 'replay: timestamp outside tolerance' };@@ -92,8 +105,14 @@ export function verifyIngressSignature(const tsRaw = header(input.headers, spec.timestampHeader);const ts = Number.parseInt(tsRaw ?? '', 10);if (!Number.isFinite(ts)) return { ok: false, reason: 'missing/invalid timestamp' };+ // Freshness is ALWAYS enforced once a timestamp header is declared: a declared header with no+ // toleranceSec falls back to the host default (previously such a route rejected every delivery —+ // an undeclarable trap). Declaring the header without signing it (`{timestamp}` absent from the+ // contentTemplate) still lets a replay mint a fresh unsigned timestamp, so the loader warns on+ // that combination (see warnUnsignedTimestampRoutes).+ const toleranceSec = spec.toleranceSec ?? resolveIngressTimestampToleranceSec();const skewSec = Math.abs(input.now / 1000 - ts);- if (!(spec.toleranceSec && skewSec <= spec.toleranceSec)) {+ if (skewSec > toleranceSec) {return { ok: false, reason: 'replay: timestamp outside tolerance' };}}diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex f8706e4e6..4550fae28 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -40,6 +40,7 @@ export interface IngressDeps {providerDeliveryId: string;route: string;payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };+ payloadHash: string;sessionId: string | null;}): Promise<boolean>;};@@ -123,6 +124,8 @@ export class IngressService {providerDeliveryId: deliveryId,route: req.route,payload,+ // The slim content fingerprint kept after the payload is retired on dispatch (see the entity).+ payloadHash: createHash('sha256').update(req.rawBody).digest('hex'),sessionId: instance.sessionScope,});if (!isNew) return { status: 200, body: 'duplicate' }; // already persisted/ackeddiff --git a/src/modules/integration/integration-retention.service.spec.ts b/src/modules/integration/integration-retention.service.spec.tsindex b966ebf64..9161dc1b4 100644--- a/src/modules/integration/integration-retention.service.spec.ts+++ b/src/modules/integration/integration-retention.service.spec.ts@@ -132,6 +132,22 @@ describe('IntegrationRetentionService.pruneOlderThan', () => {expect(remainingFailures.every(f => f.createdAt > daysAgo(10))).toBe(true);});+ it('applies independent windows per table (dedup short, failures long)', async () => {+ // Events older than 2d: 30d/15d/3d (3 rows). Failures older than 10d: 40d/20d (2 rows).+ const result = await service.pruneOlderThan(2, 10);++ expect(result).toEqual({ events: 3, failures: 2 });+ expect((await ds.getRepository(IngressEvent).find({ order: { id: 'ASC' } })).map(e => e.id)).toEqual(['ev-new-2']);+ expect(await ds.getRepository(IntegrationDeliveryFailure).count()).toBe(2);+ });++ it('skips the failures prune entirely when the failures window is null', async () => {+ const result = await service.pruneOlderThan(2, null);++ expect(result).toEqual({ events: 3, failures: 0 });+ expect(await ds.getRepository(IntegrationDeliveryFailure).count()).toBe(4);+ });+it('deletes nothing when the window exceeds every row age', async () => {const result = await service.pruneOlderThan(365);expect(result).toEqual({ events: 0, failures: 0 });@@ -140,8 +156,9 @@ describe('IntegrationRetentionService.pruneOlderThan', () => {});it('deletes everything when the window is 0 days', async () => {- // A 0-day cutoff = everything strictly older than "now" is pruned. (onModuleInit treats <=0 as a- // disabled opt-out and never calls this; here we confirm the method itself is bounded by age.)+ // A 0-day cutoff = everything strictly older than "now" is pruned. (onModuleInit never passes a+ // 0-day events window — INGRESS_DEDUP_RETENTION_DAYS <= 0 clamps to the default; here we confirm+ // the method itself is bounded by age.)const result = await service.pruneOlderThan(0);expect(result.events + result.failures).toBe(8);});@@ -152,6 +169,7 @@ describe('IntegrationRetentionService.pruneOlderThan', () => {describe('IntegrationRetentionService.onModuleInit (retention scheduling)', () => {const original = process.env.INGRESS_RETENTION_DAYS;+ const originalDedup = process.env.INGRESS_DEDUP_RETENTION_DAYS;const mockRepos = () => {const eventsDelete = jest.fn().mockResolvedValue({ affected: 0 });@@ -167,21 +185,28 @@ describe('IntegrationRetentionService.onModuleInit (retention scheduling)', () =afterEach(() => {if (original === undefined) delete process.env.INGRESS_RETENTION_DAYS;else process.env.INGRESS_RETENTION_DAYS = original;+ if (originalDedup === undefined) delete process.env.INGRESS_DEDUP_RETENTION_DAYS;+ else process.env.INGRESS_DEDUP_RETENTION_DAYS = originalDedup;});- it('disables pruning (no startup prune, no timer) when INGRESS_RETENTION_DAYS <= 0', () => {+ it('disables only the failures prune when INGRESS_RETENTION_DAYS <= 0 — dedup pruning still applies', async () => {process.env.INGRESS_RETENTION_DAYS = '0';+ delete process.env.INGRESS_DEDUP_RETENTION_DAYS;const repos = mockRepos();const svc = new IntegrationRetentionService(repos.events, repos.failures);- expect(() => svc.onModuleInit()).not.toThrow();- expect(repos.eventsDelete).not.toHaveBeenCalled();+ svc.onModuleInit();+ // Let the startup prune promise settle (the method runs before the log .then()).+ await Promise.resolve();+ // Dedup rows are never an audit log — their prune cannot be disabled to infinity.+ expect(repos.eventsDelete).toHaveBeenCalled();expect(repos.failuresDelete).not.toHaveBeenCalled();svc.onModuleDestroy();});- it('defaults to 90 days when unset, prunes once at startup, and schedules a daily timer', () => {+ it('defaults to 7-day dedup + 90-day failures windows, prunes once at startup, and schedules daily', () => {delete process.env.INGRESS_RETENTION_DAYS;+ delete process.env.INGRESS_DEDUP_RETENTION_DAYS;const repos = mockRepos();const svc = new IntegrationRetentionService(repos.events, repos.failures);@@ -189,12 +214,12 @@ describe('IntegrationRetentionService.onModuleInit (retention scheduling)', () =try {const pruneSpy = jest.spyOn(svc, 'pruneOlderThan');svc.onModuleInit();- // Startup prune fires immediately (90-day default).- expect(pruneSpy).toHaveBeenCalledWith(90);+ // Startup prune fires immediately (7-day dedup + 90-day failures defaults).+ expect(pruneSpy).toHaveBeenCalledWith(7, 90);pruneSpy.mockClear();// The recurring timer fires daily thereafter.jest.advanceTimersByTime(24 * 60 * 60 * 1000);- expect(pruneSpy).toHaveBeenCalledWith(90);+ expect(pruneSpy).toHaveBeenCalledWith(7, 90);svc.onModuleDestroy();// After destroy, advancing the timer must NOT trigger further prunes.pruneSpy.mockClear();@@ -204,4 +229,29 @@ describe('IntegrationRetentionService.onModuleInit (retention scheduling)', () =jest.useRealTimers();}});++ it('honors an explicit INGRESS_DEDUP_RETENTION_DAYS window', () => {+ delete process.env.INGRESS_RETENTION_DAYS;+ process.env.INGRESS_DEDUP_RETENTION_DAYS = '21';+ const repos = mockRepos();+ const svc = new IntegrationRetentionService(repos.events, repos.failures);++ const pruneSpy = jest.spyOn(svc, 'pruneOlderThan');+ svc.onModuleInit();+ expect(pruneSpy).toHaveBeenCalledWith(21, 90);+ svc.onModuleDestroy();+ });++ it('clamps INGRESS_DEDUP_RETENTION_DAYS <= 0 to the default instead of disabling dedup pruning', () => {+ delete process.env.INGRESS_RETENTION_DAYS;+ process.env.INGRESS_DEDUP_RETENTION_DAYS = '0';+ const repos = mockRepos();+ const svc = new IntegrationRetentionService(repos.events, repos.failures);++ const pruneSpy = jest.spyOn(svc, 'pruneOlderThan');+ svc.onModuleInit();+ // <=0 would mean an unbounded dedup table — the trap this knob exists to avoid.+ expect(pruneSpy).toHaveBeenCalledWith(7, 90);+ svc.onModuleDestroy();+ });});diff --git a/src/modules/integration/integration-retention.service.ts b/src/modules/integration/integration-retention.service.tsindex 00ca69b0b..1f841e570 100644--- a/src/modules/integration/integration-retention.service.ts+++ b/src/modules/integration/integration-retention.service.ts@@ -5,14 +5,28 @@ import { IngressEvent } from './entities/ingress-event.entity';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { createLogger } from '../../common/services/logger.service';+// Dedup rows are a delivery-id oracle, not an audit log: provider retries arrive within minutes, so+// a short window (default 7 days) bounds the table without weakening dedup. Failure rows carry the+// redrive payload and have audit value, so they keep the longer INGRESS_RETENTION_DAYS window.+const DEFAULT_DEDUP_RETENTION_DAYS = 7;+const DEFAULT_FAILURE_RETENTION_DAYS = 90;+/*** Bounds the growth of two append-only integration-fabric tables that otherwise grow without bound:* `ingress_events` (the inbound dedup/event log) and `integration_delivery_failures` (the DLQ).** Mirrors the AuditService / WebhookService retention: runs once at startup then daily via a raw- * `setInterval` (unref'd), gated by INGRESS_RETENTION_DAYS (default 90; set <= 0 to disable). Both- * tables carry a `createdAt` column (ingress_events is indexed on it), so the prune is an indexed- * `createdAt < cutoff` delete — the same shape as the sibling prunes.+ * `setInterval` (unref'd). Both tables carry a `createdAt` column (ingress_events is indexed on it),+ * so the prune is an indexed `createdAt < cutoff` delete — the same shape as the sibling prunes.+ *+ * Two independent windows:+ * - `INGRESS_DEDUP_RETENTION_DAYS` (default 7) prunes `ingress_events`. <= 0 does NOT disable it —+ * an unpruned dedup table grows without bound for zero functional gain (its payloads are retired+ * on dispatch and its audit value is nil), so a non-positive value falls back to the default with+ * a warning instead of silently opting into unbounded growth.+ * - `INGRESS_RETENTION_DAYS` (default 90) prunes `integration_delivery_failures` — the redrive+ * payload store, where long retention can be a deliberate operator choice. <= 0 disables that+ * prune (and only that prune).*/@Injectable()export class IntegrationRetentionService implements OnModuleInit, OnModuleDestroy {@@ -26,16 +40,30 @@ export class IntegrationRetentionService implements OnModuleInit, OnModuleDestro) {}onModuleInit(): void {- const parsed = Number.parseInt(process.env.INGRESS_RETENTION_DAYS ?? '', 10);- const retentionDays = Number.isInteger(parsed) ? Math.max(0, parsed) : 90;+ const parsedRetention = Number.parseInt(process.env.INGRESS_RETENTION_DAYS ?? '', 10);+ const retentionDays = Number.isInteger(parsedRetention)+ ? Math.max(0, parsedRetention)+ : DEFAULT_FAILURE_RETENTION_DAYS;++ const parsedDedup = Number.parseInt(process.env.INGRESS_DEDUP_RETENTION_DAYS ?? '', 10);+ let dedupDays = Number.isInteger(parsedDedup) ? parsedDedup : DEFAULT_DEDUP_RETENTION_DAYS;+ if (dedupDays <= 0) {+ this.logger.warn(+ `INGRESS_DEDUP_RETENTION_DAYS <= 0 does not disable dedup pruning (an unpruned ingress_events ` ++ `table grows without bound); falling back to the ${DEFAULT_DEDUP_RETENTION_DAYS}-day default`,+ { action: 'ingress_dedup_retention_clamped' },+ );+ dedupDays = DEFAULT_DEDUP_RETENTION_DAYS;+ }if (retentionDays <= 0) {- this.logger.log('Integration ingress retention disabled (INGRESS_RETENTION_DAYS <= 0)');- return;+ this.logger.log(+ 'Integration delivery-failure retention disabled (INGRESS_RETENTION_DAYS <= 0); dedup retention still applies',+ );}const runPrune = (): void => {- this.pruneOlderThan(retentionDays)+ this.pruneOlderThan(dedupDays, retentionDays > 0 ? retentionDays : null).then(({ events, failures }) => {- if (events > 0) this.logger.log(`Pruned ${events} ingress event(s) older than ${retentionDays} day(s)`);+ if (events > 0) this.logger.log(`Pruned ${events} ingress event(s) older than ${dedupDays} day(s)`);if (failures > 0) {this.logger.log(`Pruned ${failures} integration delivery-failure(s) older than ${retentionDays} day(s)`);}@@ -56,15 +84,23 @@ export class IntegrationRetentionService implements OnModuleInit, OnModuleDestro}/**- * Delete ingress_events + integration_delivery_failures rows older than the retention window.- * Returns the number removed from each table.+ * Delete ingress_events rows older than `eventsDays` and integration_delivery_failures rows older+ * than `failuresDays` (null skips the failures prune; omitted = same window as events). Returns+ * the number removed from each table.*/- async pruneOlderThan(olderThanDays: number): Promise<{ events: number; failures: number }> {- const cutoff = new Date();- cutoff.setDate(cutoff.getDate() - olderThanDays);+ async pruneOlderThan(+ eventsDays: number,+ failuresDays: number | null = eventsDays,+ ): Promise<{ events: number; failures: number }> {+ const eventsCutoff = new Date();+ eventsCutoff.setDate(eventsCutoff.getDate() - eventsDays);+ const failuresCutoff = new Date();+ if (failuresDays !== null) failuresCutoff.setDate(failuresCutoff.getDate() - failuresDays);const [eventsResult, failuresResult] = await Promise.all([- this.eventRepository.delete({ createdAt: LessThan(cutoff) }),- this.failureRepository.delete({ createdAt: LessThan(cutoff) }),+ this.eventRepository.delete({ createdAt: LessThan(eventsCutoff) }),+ failuresDays === null+ ? Promise.resolve({ affected: 0 })+ : this.failureRepository.delete({ createdAt: LessThan(failuresCutoff) }),]);return { events: eventsResult.affected || 0, failures: failuresResult.affected || 0 };}diff --git a/test/integration-fabric.e2e-spec.ts b/test/integration-fabric.e2e-spec.tsindex 639c29401..cf55c08a3 100644--- a/test/integration-fabric.e2e-spec.ts+++ b/test/integration-fabric.e2e-spec.ts@@ -2,7 +2,7 @@// 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 { createHash, createHmac, randomBytes } from 'node:crypto';import { readFileSync } from 'node:fs';import { join } from 'node:path';import { Test, TestingModule } from '@nestjs/testing';@@ -188,6 +188,10 @@ describe('Integration Fabric ingress (e2e)', () => {const row = await eventRepo.findOneByOrFail({ providerDeliveryId: 'delivery-marked-1' });expect(row.dispatchState).toBe('dispatched');expect(row.lastDispatchAt).not.toBeNull();+ // With the outcome recorded, the dispatch tier owns the payload: the dedup row retires it to+ // NULL and keeps only the slim content fingerprint for operator correlation.+ expect(row.payload).toBeNull();+ expect(row.payloadHash).toBe(createHash('sha256').update(raw).digest('hex'));});it('persists a redrivable dead-letter row (still 202) when inline dispatch fails', async () => {@@ -219,9 +223,12 @@ describe('Integration Fabric ingress (e2e)', () => {});// The event row itself stays 'pending' with the failure counted, so the reconciler retries the- // dispatch on its next sweep instead of waiting for a manual redrive alone.+ // dispatch on its next sweep instead of waiting for a manual redrive alone. Its payload is KEPT+ // — it is the reconciler's replay source (the DLQ row carries the copy redrive uses).const event = await eventRepo.findOneByOrFail({ providerDeliveryId: 'delivery-dlq-1' });expect(event.dispatchState).toBe('pending');expect(event.dispatchAttempts).toBe(1);+ expect(event.payload).not.toBeNull();+ expect(event.payloadHash).toBe(createHash('sha256').update(raw).digest('hex'));});});