Skip to content

feat(webhook): add excludeFields and includeFields payload filters (#2695) - #2802

Open
zanarellidev wants to merge 2 commits into
evolution-foundation:developfrom
zanarellidev:feat/webhook-payload-filters
Open

zanarellidev wants to merge 2 commits into
evolution-foundation:developfrom
zanarellidev:feat/webhook-payload-filters

Conversation

@zanarellidev

@zanarellidev zanarellidev commented Nov 22, 2026 •

Copy link
Copy Markdown

📋 Description

Adds optional excludeFields and includeFields payload filtering to local instance webhooks so users can omit heavy fields (e.g. base64) or restrict dispatched webhook payloads to specific fields.

Summary of Changes

  • Added filterWebhookPayload(data, { excludeFields, includeFields }) in src/api/integrations/event/webhook/webhook-payload-filter.ts:
    • Supports top-level keys and dot-notation nested paths (e.g. message.imageMessage).
    • Compacts sparse holes in root and nested arrays on includeFields and preserves indices across multi-index excludeFields removals.
    • Guards against prototype-pollution segments (__proto__, constructor, prototype).
    • Returns the original data reference unchanged when no filters are configured, and never mutates the shared internal event object used by global webhooks or other integrations.
  • Wired excludeFields and includeFields across WebhookController (set and emit), webhookSchema, EventDto/InstanceDto, EventManager.setInstance, InstanceController, and wa.LocalWebHook.
  • Added nullable excludeFields Json? and includeFields Json? columns to model Webhook in postgresql, psql_bouncer, and mysql Prisma schemas along with additive migrations.
  • Added 10 unit tests in src/api/integrations/event/webhook/webhook-payload-filter.test.ts.

🔗 Related Issue

Closes #2695

🧪 Type of Change

  • ✨ New feature (non-breaking change which adds functionality)

🧪 Testing

  • No breaking changes introduced
  • Ran npm run lint:check (0 errors, 0 warnings)
  • Ran npm run db:generate && npm run build (tsc --noEmit && tsup, 0 errors)
  • Ran npx tsx --test src/api/integrations/event/webhook/webhook-payload-filter.test.ts (10/10 tests passed)

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • My changes generate no new warnings

Summary by Sourcery

Add configurable payload field filtering to local webhooks so dispatched data can be reduced to selected fields or have unwanted fields omitted.

New Features:

  • Add configurable include and exclude field filters for local instance webhook payloads, including nested dot-notation paths and array payloads.

Enhancements:

  • Preserve shared event data and protect against prototype-pollution field paths while applying webhook filtering.

Tests:

  • Add comprehensive unit coverage for webhook field inclusion, exclusion, nested paths, arrays, invalid paths, and immutability.

Chores:

  • Add nullable webhook payload-filter configuration fields to supported Prisma schemas and migrations.
  • Propagate webhook filter settings through instance configuration, validation, DTOs, and event management.

Copilot AI balanced review requested due to automatic review settings November 22, 2026 18:48
@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Schema and migrations

Add nullable webhook filter columns and their migrations across the supported database schemas.

  • prisma/mysql-migrations/20261122000000_add_webhook_payload_filters/migration.sql L1-3
  • prisma/mysql-schema.prisma L210-211
  • prisma/postgresql-migrations/20261122000000_add_webhook_payload_filters/migration.sql L1-3
  • prisma/postgresql-schema.prisma L209-210
  • prisma/psql_bouncer-schema.prisma L208-209

Data structures

Extend webhook configuration types with include and exclude field settings used by event and instance payloads.

  • src/api/types/wa.types.ts L103-104

API

Expose includeFields and excludeFields as supported webhook configuration properties in the webhook and instance validation schemas.

  • src/api/integrations/event/webhook/webhook.schema.ts L37-52
  • src/validate/instance.schema.ts L54-86

Add filter settings to the event and instance DTO webhook shapes.

  • src/api/dto/instance.dto.ts L40-41
  • src/api/integrations/event/event.dto.ts L12-13, L61-62

Uses of the API

Propagate configured field filters when building and updating instance webhook settings.

  • src/api/controllers/instance.controller.ts L183-184, L279-280
  • src/api/integrations/event/event.manager.ts L183-184
  • src/api/integrations/event/webhook/webhook.controller.ts L45-46, L56-57

Filter local webhook data before logging and dispatch while retaining the original payload when no filters change it.

  • src/api/integrations/event/webhook/webhook.controller.ts L112-117, L155-161 (+2 small edits)

Implementation

Implement non-mutating include and exclude filtering for nested object and array payload paths, with invalid-path hardening.

  • src/api/integrations/event/webhook/webhook-payload-filter.ts L1-231

Tests

Add unit tests for filtering behavior, arrays, invalid paths, precedence, and input immutability.

  • src/api/integrations/event/webhook/webhook-payload-filter.test.ts L1-255

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/api/integrations/event/webhook/webhook-payload-filter.ts" line_range="179" />
<code_context>
+ */
+export function filterWebhookPayload<T>(data: T, options?: WebhookPayloadFilterOptions): T {
+  if (data === null || data === undefined || typeof data !== 'object') {
+    return data;
+  }
+
</code_context>
<issue_to_address>
**Invalid include paths expose full payload**

When `includeFields` is configured with only forbidden or otherwise ignored paths, such as `['constructor.prototype']`, `normalizeFieldPaths` drops forbidden or otherwise unusable paths, so an `includeFields` list containing only those paths leaves both normalized lists empty and this branch returns the original data. The local webhook sends fields the caller asked to exclude by using an include-only filter.

Distinguish an absent/empty include configuration from a nonempty configuration that normalizes to no usable paths, and return an empty payload for the latter.
</issue_to_address>

### Comment 2
<location path="src/api/dto/instance.dto.ts" line_range="40-41" />
<code_context>
     url?: string;
     byEvents?: boolean;
     base64?: boolean;
+    excludeFields?: string[];
+    includeFields?: string[];
   };
   chatwootAccountId?: string;
</code_context>
<issue_to_address>
**Malformed filters are silently ignored**

When a caller supplies a non-array `excludeFields` or `includeFields` value to instance creation, `instanceSchema` does not validate the nested `webhook` filters accepted by `InstanceDto`, so instance creation stores a non-array value; `normalizeFieldPaths` then ignores it and dispatches the webhook without the requested filtering.

Add nested webhook filter array definitions to `instanceSchema` so malformed values are rejected.
</issue_to_address>

### Comment 3
<location path="src/api/integrations/event/webhook/webhook-payload-filter.ts" line_range="52" />
<code_context>
+    }
+    return cloned as T;
+  }
+  return value;
+}
+
</code_context>
<issue_to_address>
**Filtering mutates shared event data**

When the payload contains a non-plain object with an own property targeted by `excludeFields`, `cloneValue` returns non-plain objects by reference, then `omitPath` can delete a nested field from that same object. The filter mutates the original event payload, affecting other consumers of the shared data.

Clone supported non-plain payload objects before applying exclusions, or reject/skip exclusions within values that cannot be safely copied.
</issue_to_address>

### Comment 4
<location path="src/api/integrations/event/webhook/webhook-payload-filter.ts" line_range="170" />
<code_context>
+ *
+ * When no filters are configured, the original `data` reference is returned unchanged.
+ */
+export function filterWebhookPayload<T>(data: T, options?: WebhookPayloadFilterOptions): T {
+  if (data === null || data === undefined || typeof data !== 'object') {
+    return data;
</code_context>
<issue_to_address>
**Filtered results retain full type**

When a caller uses `includeFields` and then relies on a property required by `T`, `includeFields` removes properties from the result, but the exported function still promises `T`; callers can therefore access omitted required properties without a TypeScript error and receive `undefined` at runtime.

Return a type that reflects filtering (or an explicitly unknown/partial result) instead of promising the original `T`.
</issue_to_address>

### Comment 5
<location path="src/api/integrations/event/webhook/webhook-payload-filter.ts" line_range="33-39" />
<code_context>
+  return paths;
+}
+
+function isPlainObject(value: unknown): value is Record<string, any> {
+  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+    return false;
+  }
+  const proto = Object.getPrototypeOf(value);
+  return proto === Object.prototype || proto === null;
</code_context>
<issue_to_address>
**Payload filtering loses type safety**

The filter implementation uses `any` for payloads, intermediate results, and container types across its helpers, so TypeScript cannot check property access or mutations on this path. The new utility therefore does not meet the repository's requirement to avoid `any` and use proper typing.

Replace `any` with suitable `unknown`, JSON-value, and typed container/result types, narrowing values before accessing or mutating them.

Also at `src/api/integrations/event/webhook/webhook-payload-filter.ts:46-51`, `src/api/integrations/event/webhook/webhook-payload-filter.ts:55-162`, `src/api/integrations/event/webhook/webhook-payload-filter.ts:183-212`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and the filters change the data sent in webhook requests to external endpoints; an incorrect filter can send an incomplete or otherwise wrong payload that a recipient may retain or act on. Reverting restores future payloads but cannot retract requests already delivered.

Blocking findings: src/api/integrations/event/webhook/webhook-payload-filter.ts:179, src/api/dto/instance.dto.ts:41, src/api/integrations/event/webhook/webhook-payload-filter.ts:52, src/api/integrations/event/webhook/webhook-payload-filter.ts:170


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/api/dto/instance.dto.ts Resolved
@zanarellidev

Copy link
Copy Markdown
Author

Addressed the review findings in 6918aed:

  • Made includeFields fail closed ({} / []) when a non-empty array contains only invalid/blocked paths instead of returning the full payload.
  • Added excludeFields / includeFields validation to instanceSchema.properties.webhook.
  • Guarded omitPath against non-plain objects and replaced any with unknown / Record<string, unknown> across webhook-payload-filter.ts.
  • Added regression tests for invalid includeFields and non-plain object preservation (12/12 passing, npm run lint:check and npm run build green).

@sourcery-ai review

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants