Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(infra): exclude webhook credentials from export-data backups
Yudhi Armyndharis5e9f154f32f0
diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 8667a6022..e4f7d72e3 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -175,7 +175,7 @@ OpenWA serves plain HTTP on its port; terminate **TLS at your reverse proxy / lo| ----------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ || API keys | **Hashed** — SHA-256 with an optional `API_KEY_PEPPER` HMAC; never reversible | A database leak alone cannot recover the keys; with a pepper set, hashes can't be precomputed offline. See §4.2. || Session auth state (WhatsApp credentials) | Plaintext on disk (the engine's auth store under the data volume) | Filesystem permissions on the data volume — keep it private. |-| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by the webhook read DTOs (write-only) — except `GET /api/infra/export-data`, which dumps the row in cleartext. |+| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by the webhook read DTOs (write-only) and omitted from `GET /api/infra/export-data` webhook rows. || Proxy credentials | Plaintext — `sessions.proxyUrl` may embed `user:pass` | Database access control; never returned by the session read DTOs. || Generated config (`data/.env.generated`) | Plaintext file, written `0600` | Owner-only file permissions. || Message content | Plaintext in the `messages` table | Database access control. |@@ -522,7 +522,7 @@ flowchart TB| Redis password | Environment variable | 90 days || API master key (`API_MASTER_KEY`) | Environment variable | 180 days || API key pepper (`API_KEY_PEPPER`) | Environment variable | Rotating it invalidates all existing key hashes |-| Webhook secrets | Database — **plaintext**; not in the webhook read DTOs, but `GET /api/infra/export-data` returns it in cleartext | Per webhook |+| Webhook secrets | Database — **plaintext**; not in the webhook read DTOs, and omitted from `GET /api/infra/export-data` webhook rows | Per webhook || Session auth state | File system (data volume) — **not encrypted** | Never (tied to the WA session) |> There is no application `ENCRYPTION_KEY` — OpenWA does not encrypt data at rest (see §4.4). The rotation cadences above are operational recommendations, not enforced by the app.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex b4b1a9b23..e20a6c308 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4314,7 +4314,7 @@ The service returns `void`; the controller returns a fixed success object. DELETWebhooks are configured per session and managed under `/api/sessions/:sessionId/webhooks` (handled by `WebhookController`). Two cross-session endpoints live on `WebhooksListController`: `GET /api/webhooks` (list, **OPERATOR**) and `GET /api/webhooks/delivery-failures` (dead-letter log, **ADMIN**). Every other route requires an API key with **OPERATOR** role or higher.-Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are never returned by any webhook route (the response DTO has no `@Expose` for them, so `fromEntity` drops them). The one exception is `GET /api/infra/export-data`, which dumps the `webhooks` rows verbatim and so carries both in cleartext. The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.+Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are never returned by any webhook route (the response DTO has no `@Expose` for them, so `fromEntity` drops them). `GET /api/infra/export-data` also omits both from its `webhooks` rows, so a backup no longer carries webhook credentials — a restored webhook comes back unsigned (`secret` null, `headers` `{}`) until you set them again. The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `group.join_request`, `call.received`, `status.received`. All of them are actively dispatched by at least one engine — none is a reserved placeholder. Four are **Baileys only**, because whatsapp-web.js produces no callback behind them: `presence.update` (its prerequisite `POST .../presence/subscribe` answers `501` there, so this one announces itself) and `call.accepted` / `call.rejected` / `call.missed` (whatsapp-web.js sees a call ring but never its outcome, so these three are accepted on subscribe and then simply never fire). See the per-event catalog below for engine scope.@@ -4477,8 +4477,8 @@ Create a webhook for the session.| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. || events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |-| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (`GET /api/infra/export-data` does return it). Used for `X-OpenWA-Signature`. Defaults to `null`. |-| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (`GET /api/infra/export-data` does return it). At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |+| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |+| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. || filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload cannot match, so it suppresses the event entirely (a field with no definition for the family is skipped instead, and does not suppress) — `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` filter silently drops all three. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. || retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |@@ -5492,7 +5492,7 @@ The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `web}```-Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns: `batch_id`, `session_id`, `current_index`, `created_at`, …). **`webhooks` rows include `secret` in cleartext**, and `pluginInstances` rows carry integration secrets — treat the payload as a credential dump. On Postgres the generated `body_ts` FTS column is stripped from `messages` so archives stay dialect-neutral.+Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns: `batch_id`, `session_id`, `current_index`, `created_at`, …). **`webhooks` rows omit `secret` and `headers`** (webhook credentials are excluded from backups; they restore as `null`/`{}`), while `pluginInstances` rows still carry integration secrets — treat the payload as a credential dump. On Postgres the generated `body_ts` FTS column is stripped from `messages` so archives stay dialect-neutral.`sessions`/`webhooks` are queried directly, so a hard DB error there yields `500`. The other 12 are queried tolerantly: a _genuinely missing_ table (an older DB that has not run the migration) exports as `[]` and its name is listed in `skippedTables`; any other error (lock, I/O, timeout) fails the export rather than reporting the table as empty. Check `skippedTables` before restoring — a skipped table is "not migrated yet", not "exported empty".@@ -5514,7 +5514,7 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction| ----------------------------- | ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `tables` | object | Yes | Container of per-table row arrays, keyed exactly as the export's `tables`. Absent, `null` or not an object is rejected `400` before the restore runs || `tables.sessions` | `SessionRow[]` | No | Inserted first; a row whose `name` is not a safe directory name is skipped with a warning (which then rolls the whole restore back) |-| `tables.webhooks` | `WebhookRow[]` | No | Includes `secret` |+| `tables.webhooks` | `WebhookRow[]` | No | Export rows omit `secret`/`headers`; an absent key restores as `null`/`{}` || `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns || `tables.*` (the remaining 11) | `Row[]` | No | Same keys as the export; an omitted table restores **zero** rows into an emptied table || `stopOrphans` | boolean | No | Stop the running engines for sessions the backup does not contain, inside this request and before the replace (best-effort, time-bounded per engine). Preferred over `force` |diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 61af20535..08bef3f0a 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -1093,7 +1093,7 @@ curl -X DELETE "$BASE/api/sessions/$SESSION_ID/status/false_status@broadcast_3A1### 07.10 Webhooks (management)-All routes require an API key with OPERATOR role or higher. `secret` and `headers` are write-only (never returned by these routes; `GET /api/infra/export-data` does return them in cleartext). The per-session routes live under `/api/sessions/:sessionId/webhooks`; the cross-session list is `/api/webhooks`.+All routes require an API key with OPERATOR role or higher. `secret` and `headers` are write-only (never returned by these routes; `GET /api/infra/export-data` omits them from webhook rows too). The per-session routes live under `/api/sessions/:sessionId/webhooks`; the cross-session list is `/api/webhooks`.#### GET /api/sessions/:sessionId/webhooksdiff --git a/src/modules/infra/infra-access-control.spec.ts b/src/modules/infra/infra-access-control.spec.tsindex 3d0e2ca5c..5eb708c04 100644--- a/src/modules/infra/infra-access-control.spec.ts+++ b/src/modules/infra/infra-access-control.spec.ts@@ -39,7 +39,7 @@ describe('Infra controllers access control (Vuln 2)', () => {[InfraConfigController, 'getConfig'], // GET /infra/config (returns saved config; secrets omitted but still ADMIN-only)[InfraConfigController, 'saveConfig'], // PUT /infra/config[InfraConfigController, 'requestRestart'], // POST /infra/restart- [InfraDataController, 'exportData'], // GET /infra/export-data (exposes webhook secrets)+ [InfraDataController, 'exportData'], // GET /infra/export-data (dumps every data-DB table)[InfraDataController, 'importData'], // POST /infra/import-data (DELETEs all rows)[InfraStorageController, 'exportStorage'], // GET /infra/storage/export[InfraStorageController, 'importStorage'], // POST /infra/storage/importdiff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex e8032f7b4..064cb78d0 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -1379,6 +1379,37 @@ describe('InfraDataController.import/export preserves every data-DB table', () =// The active flag (exported as integer 1 from SQLite) must round-trip as a real boolean.expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).active).toBe(true);});++ it('omits webhook credentials (secret, headers) from the export but keeps the row restorable', async () => {+ await seedSession('s1');+ await ds.getRepository(Webhook).save(+ ds.getRepository(Webhook).create({+ id: 'w1',+ sessionId: 's1',+ url: 'https://example.com/hook',+ events: ['message'],+ secret: 'hmac-secret',+ headers: { Authorization: 'Bearer receiver-token' },+ active: true,+ retryCount: 3,+ }),+ );++ const dump = await controller.exportData();+ expect(dump.tables.webhooks).toHaveLength(1);+ const exported = dump.tables.webhooks[0] as unknown as Record<string, unknown>;+ expect(exported).not.toHaveProperty('secret');+ expect(exported).not.toHaveProperty('headers');+ expect(exported.url).toBe('https://example.com/hook');++ // The redacted archive still restores: the webhook comes back unsigned, with no custom headers.+ const res = await controller.importData({ tables: dump.tables });+ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ const restored = await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' });+ expect(restored.secret).toBeNull();+ expect(restored.headers).toEqual({});+ });});describe('InfraDataController C002 audit trail — import emits only on a committed restore', () => {diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex b5fae3271..3637ef816 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -372,6 +372,13 @@ export class InfraDataController {// Get all entities from Data DBconst sessions = await this.dataDataSource.query<SessionRow[]>('SELECT * FROM sessions');const webhooks = await this.dataDataSource.query<WebhookRow[]>('SELECT * FROM webhooks');+ // Webhook credentials (the HMAC secret and custom headers, which may carry receiver tokens) do+ // not belong in a backup payload — omit them from the export. The importer restores the row+ // with secret null and headers {} when they are absent.+ for (const row of webhooks) {+ delete row.secret;+ delete row.headers;+ }// The tables below may legitimately not exist yet (created by migrations an older DB has not run).// Only a GENUINE missing-table error (isMissingTableError) may be tolerated — anything else (lock,@@ -448,7 +455,7 @@ export class InfraDataController {automationRules: automationRules.length,};- // Audit the full-DB export: this payload carries webhook + plugin-instance secrets, so WHO pulled+ // Audit the full-DB export: this payload carries plugin-instance secrets, so WHO pulled// a dump (and the per-table row counts) is exactly the trail C002 was missing. Data itself is never// logged — only counts.await this.auditService?.logInfo(AuditAction.INFRA_DATA_EXPORTED, { metadata: { counts } });diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsindex c3d3b9c37..10e6635e2 100644--- a/src/modules/infra/migration-tables.types.ts+++ b/src/modules/infra/migration-tables.types.ts@@ -19,8 +19,10 @@ export interface WebhookRow {sessionId: string;url: string;events: string | string[];- secret: string | null;- headers: string | Record<string, string>;+ // Credentials. export-data omits both (see exportData), so an exported row may not carry them;+ // the importer restores them as null/{} in that case.+ secret?: string | null;+ headers?: string | Record<string, string>;filters: string | Record<string, unknown> | null;active: boolean | number;retryCount: number;diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex 12f14f439..cb93328f4 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -98,7 +98,9 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [webhook.sessionId,webhook.url,typeof webhook.events === 'string' ? webhook.events : JSON.stringify(webhook.events || []),- webhook.secret,+ // Rows exported after credential redaction (and hand-trimmed archives) carry no secret at+ // all — restore those as unsigned rather than failing the row on a missing key.+ webhook.secret ?? null,typeof webhook.headers === 'string' ? webhook.headers : JSON.stringify(webhook.headers || {}),webhook.filters == null? nulldiff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex e7a5ed8f6..fec309f3b 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -188,8 +188,8 @@ export class UpdateWebhookDto {/*** Public response shape for a webhook. Deliberately omits `secret` (the HMAC* signing key) and `headers` (which may carry receiver credentials) — these are- * write-only and must never appear in a response built from this DTO. They are not secret from- * every route: GET /api/infra/export-data dumps the webhooks rows verbatim, secret included.+ * write-only and never appear in a response built from this DTO. The backup route+ * (`GET /api/infra/export-data`) also omits both from its webhook rows.** `@Expose()` is required on every field: `fromEntity` maps with* `excludeExtraneousValues: true`, so only exposed fields are serialized and anydiff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.tsindex af440ff3c..d9ca68935 100644--- a/test/webhooks.e2e-spec.ts+++ b/test/webhooks.e2e-spec.ts@@ -142,8 +142,8 @@ describe('Webhooks (e2e)', () => {expect(dto.id).toBeDefined();expect(dto.sessionId).toBe(session);expect(dto.active).toBe(true);- // Write-only fields must never appear in a webhook-route response. (The infra export route- // does return them — that is deliberate and covered by its own ADMIN + unscoped-key fence.)+ // Write-only fields must never appear in a webhook-route response (nor in the infra+ // export, which omits them from webhook rows — covered in infra-data.controller.spec.ts).expect(dto.secret).toBeUndefined();expect(dto.headers).toBeUndefined();});