Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): webhook secret entropy floor, text/plain reflections, and payload redaction

Yudhi Armyndharis54ff310c3b11
diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.ts
index 94b4f0254..9f54d4e69 100644
--- a/src/common/security/ssrf-guard.spec.ts
+++ b/src/common/security/ssrf-guard.spec.ts
@@ -836,3 +836,23 @@ describe('withSafeFetch followRedirects validates every hop over real sockets',
}
});
});
+
+// OS connect errors name the receiver's host:port — internal topology that must not ride a
+// delivery-failure row out to API consumers. The code stays (actionable), the address goes.
+describe('redactSsrfError redacts network topology', () => {
+ it('strips host:port from connect errors', () => {
+ const out = redactSsrfError(new Error('connect ECONNREFUSED 10.0.0.1:443'));
+ expect(out).toContain('ECONNREFUSED');
+ expect(out).not.toContain('10.0.0.1');
+ });
+
+ it('strips host:port from DNS failures too', () => {
+ const out = redactSsrfError(new Error('getaddrinfo ENOTFOUND internal.receiver.svc.local'));
+ expect(out).toContain('ENOTFOUND');
+ expect(out).not.toContain('internal.receiver.svc.local');
+ });
+
+ it('leaves ordinary operator-actionable messages untouched', () => {
+ expect(redactSsrfError(new Error('socket hang up'))).toBe('socket hang up');
+ });
+});
diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.ts
index 409100fbc..8ddd19389 100644
--- a/src/common/security/ssrf-guard.ts
+++ b/src/common/security/ssrf-guard.ts
@@ -32,7 +32,13 @@ export function redactSsrfError(error: unknown, logger?: { warn: (message: strin
logger?.warn(`SSRF guard blocked ${site ?? 'an outbound fetch'}: ${error.message}`);
return SSRF_BLOCKED_CLIENT_MESSAGE;
}
- return error instanceof Error ? error.message : String(error);
+ // OS-level connect errors name the receiver's host:port (connect ECONNREFUSED 10.0.0.1:443) —
+ // internal topology an API consumer has no business reading out of a delivery-failure row.
+ // The error code stays (actionable), the address goes.
+ return (error instanceof Error ? error.message : String(error)).replace(
+ /\b(ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|ECONNRESET|EAI_AGAIN)\s+[\w.-]+(?::\d+)?(?=\s|$)/g,
+ '$1 [redacted]',
+ );
}
/**
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 859ed3bfd..f73a5afd8 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2140,7 +2140,7 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
// the finished flags AFTER the await — so a late encode does not resurrect a finished adapter to
// QR_READY, does not overwrite qrCode with a stale value, and does not re-fire the publish/webhook
// callback. A native 'disconnected' emitted mid-encode latches disconnectReported synchronously (via
- // setStatus(DISCONNECTED)) and is exactly the post-await-unsafe window F-06 names.
+ // setStatus(DISCONNECTED)) and is exactly the post-await-unsafe window the reconnect latch exists to close.
it('drops a QR whose encode finishes after the source client disconnects', async () => {
let resolveEncode!: (value: string) => void;
const encodePending = new Promise<string>(resolve => {
diff --git a/src/modules/integration/ingress.controller.spec.ts b/src/modules/integration/ingress.controller.spec.ts
index e0e8cb33c..2592e831d 100644
--- a/src/modules/integration/ingress.controller.spec.ts
+++ b/src/modules/integration/ingress.controller.spec.ts
@@ -7,8 +7,13 @@ import { IngressService } from './ingress.service';
const RAW = '{\n "event": "message_created",\n "id": 42\n}\n';
function fakeRes() {
- const captured: { status?: number; body?: string; headers?: Record<string, string> } = {};
+ const captured: { status?: number; body?: string; headers?: Record<string, string>; contentType?: string } = {};
+ const type = jest.fn((contentType: string) => {
+ captured.contentType = contentType;
+ return res;
+ });
const res = {
+ type,
status: jest.fn((code: number) => {
captured.status = code;
return res;
@@ -25,6 +30,26 @@ function fakeRes() {
return { res, captured };
}
+// Both reflections echo provider-controlled strings; Express types a bare send() as text/html,
+// which would make the echo XSS material on this origin. The route must force text/plain.
+describe('reflection content type', () => {
+ it('answers with Content-Type text/plain, never the Express default text/html', async () => {
+ const handle = jest.fn().mockResolvedValue({ status: 200, body: '<script>alert(1)</script>' });
+ const controller = new IngressController({ handle } as unknown as IngressService);
+ const { res, captured } = fakeRes();
+ const req = {
+ method: 'POST',
+ params: { path: ['chatwoot'] },
+ headers: { 'x-delivery': 'd1', 'content-type': 'application/json' },
+ rawBody: Buffer.from('{}', 'utf8'),
+ } as unknown as Request & { rawBody?: Buffer };
+
+ await controller.receive('chatwoot', 'acct1', {}, req, res);
+
+ expect(captured.contentType).toBe('text/plain');
+ });
+});
+
describe('IngressController', () => {
it('forwards the RAW request bytes byte-identically to the pipeline', async () => {
const handle = jest.fn().mockResolvedValue({ status: 202, body: 'accepted' });
diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.ts
index 331aeed70..859a3a620 100644
--- a/src/modules/integration/ingress.controller.ts
+++ b/src/modules/integration/ingress.controller.ts
@@ -78,6 +78,10 @@ export class IngressController {
rawBody,
});
if (result.headers) res.set(result.headers);
+ // Both reflections echo provider-controlled strings (hub.challenge, the ack template). Express
+ // types a bare send() as text/html, which turns a reflection into XSS material on this origin —
+ // force text/plain so the browser refuses to parse it.
+ res.type('text/plain');
res.status(result.status).send(result.body ?? '');
}
}
diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.ts
index abdf6dc2d..d7e7a4e3e 100644
--- a/src/modules/integration/ingress.service.spec.ts
+++ b/src/modules/integration/ingress.service.spec.ts
@@ -1,4 +1,4 @@
-import { IngressService, extractConversationId } from './ingress.service';
+import { IngressService, extractConversationId, redactSensitiveHeaders } from './ingress.service';
import { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';
import { createHmac } from 'node:crypto';
@@ -30,6 +30,45 @@ function deps(overrides: Record<string, unknown> = {}) {
};
}
+describe('redactSensitiveHeaders (persisted ingress payloads)', () => {
+ it('redacts credential and signature headers, keeps the rest verbatim', () => {
+ const out = redactSensitiveHeaders({
+ authorization: 'Bearer eyJhbGciOi',
+ 'x-hub-signature-256': 'sha256=abc',
+ cookie: 'session=secret',
+ 'x-delivery': 'd1',
+ 'content-type': 'application/json',
+ });
+ expect(out.authorization).toBe('[redacted]');
+ expect(out['x-hub-signature-256']).toBe('[redacted]');
+ expect(out.cookie).toBe('[redacted]');
+ expect(out['x-delivery']).toBe('d1');
+ expect(out['content-type']).toBe('application/json');
+ });
+
+ it('the persisted payload carries redacted headers (wiring, not just the helper)', async () => {
+ const recordOrSkip = jest.fn().mockResolvedValue(true);
+ const d = deps();
+ d.events.recordOrSkip = recordOrSkip;
+ const svc = new IngressService(d);
+ await svc.handle({
+ pluginId: 'chatwoot',
+ instanceId: 'acct1',
+ route: 'chatwoot',
+ method: 'POST',
+ headers: { 'x-delivery': 'd1', authorization: 'Bearer tok' },
+ query: {},
+ rawBody: '{}',
+ });
+ // jest's mock.calls typing erodes through the deps() override — one explicit cast at the
+ // boundary beats a chain of eslint suppressions.
+ const calls = recordOrSkip.mock.calls as unknown as [[{ payload: { headers: Record<string, string> } }]];
+ const recorded = calls[0][0];
+ expect(recorded.payload.headers.authorization).toBe('[redacted]');
+ expect(recorded.payload.headers['x-delivery']).toBe('d1');
+ });
+});
+
describe('IngressService.handle', () => {
const req = {
pluginId: 'chatwoot',
diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.ts
index d1fa9b9e7..8a0fd2bff 100644
--- a/src/modules/integration/ingress.service.ts
+++ b/src/modules/integration/ingress.service.ts
@@ -163,7 +163,14 @@ export class IngressService {
const defaultDedupHeader = route.signature.scheme === 'standard-webhooks' ? 'webhook-id' : 'x-delivery';
const dedupHeader = (route.dedupHeader ?? route.signature.dedupHeader ?? defaultDedupHeader).toLowerCase();
const deliveryId = req.headers[dedupHeader] ?? deriveDeliveryId(req);
- const payload = { headers: req.headers, query: req.query, body: req.rawBody, rawBody: req.rawBody };
+ // Provider request headers persist with the event (redrive/debugging); credentials must not.
+ // Signature headers are re-derivable, auth material is not — redact before the first write.
+ const payload = {
+ headers: redactSensitiveHeaders(req.headers),
+ query: req.query,
+ body: req.rawBody,
+ rawBody: req.rawBody,
+ };
const isNew = await this.deps.events.recordOrSkip({
instanceId: req.instanceId,
pluginId: req.pluginId,
@@ -258,3 +265,28 @@ export function extractConversationId(
}
return undefined;
}
+
+/**
+ * Header names whose VALUES must never reach the persisted event payload: bearer/basic
+ * credentials, cookies, and the provider signature headers (recomputable from the raw body, and
+ * useless for redrive — the retry re-signs). The names survive so operators can still see WHICH
+ * scheme the provider used.
+ */
+const SENSITIVE_INGRESS_HEADERS = new Set([
+ 'authorization',
+ 'proxy-authorization',
+ 'cookie',
+ 'x-hub-signature',
+ 'x-hub-signature-256',
+ 'x-signature',
+ 'x-signature-ed25519',
+ 'x-webhook-signature',
+]);
+
+export function redactSensitiveHeaders(headers: Record<string, string>): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [name, value] of Object.entries(headers)) {
+ out[name] = SENSITIVE_INGRESS_HEADERS.has(name.toLowerCase()) ? '[redacted]' : value;
+ }
+ return out;
+}
diff --git a/src/modules/webhook/dto/webhook-secret-entropy.spec.ts b/src/modules/webhook/dto/webhook-secret-entropy.spec.ts
new file mode 100644
index 000000000..88e4f4cfb
--- /dev/null
+++ b/src/modules/webhook/dto/webhook-secret-entropy.spec.ts
@@ -0,0 +1,37 @@
+import { validate } from 'class-validator';
+import { CreateWebhookDto } from './webhook.dto';
+
+/**
+ * the HMAC secret signs every delivery this webhook fires. A short secret is recoverable
+ * from one observed signature, which turns the signature from an integrity check into a forging
+ * tool — 16 characters is the floor, not a recommendation.
+ */
+describe('CreateWebhookDto secret entropy', () => {
+ const dtoWithSecret = (secret: string) => {
+ const dto = new CreateWebhookDto();
+ dto.url = 'https://receiver.example.com/hook';
+ dto.events = ['message.received'];
+ dto.secret = secret;
+ return dto;
+ };
+
+ it('rejects a secret shorter than 16 characters', async () => {
+ const errors = await validate(dtoWithSecret('short'));
+ expect(errors.some(e => e.property === 'secret')).toBe(true);
+ });
+
+ it('accepts a 16+ character secret', async () => {
+ const errors = await validate(dtoWithSecret('a-fully-entropic-secret'));
+ expect(errors.some(e => e.property === 'secret')).toBe(false);
+ });
+
+ it('still allows omitting the secret entirely (unsigned webhooks are a valid choice)', async () => {
+ const dto = new CreateWebhookDto();
+ dto.url = 'https://receiver.example.com/hook';
+ dto.events = ['message.received'];
+ expect(errorsOf(await validate(dto))).toBe(0);
+ function errorsOf(errs: { property: string }[]): number {
+ return errs.filter(e => e.property === 'secret').length;
+ }
+ });
+});
diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.ts
index 07e23d63e..ec8bf7fbf 100644
--- a/src/modules/webhook/dto/webhook.dto.ts
+++ b/src/modules/webhook/dto/webhook.dto.ts
@@ -1,16 +1,17 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
- IsString,
- IsUrl,
+ ArrayMinSize,
IsArray,
- IsOptional,
IsBoolean,
+ IsIn,
IsInt,
- Min,
+ IsOptional,
+ IsString,
+ IsUrl,
Max,
MaxLength,
- ArrayMinSize,
- IsIn,
+ Min,
+ MinLength,
} from 'class-validator';
import { Expose, plainToInstance } from 'class-transformer';
import { Webhook } from '../entities/webhook.entity';
@@ -127,6 +128,9 @@ export class CreateWebhookDto {
})
@IsOptional()
@IsString()
+ // A short secret signs webhooks badly: HMAC-SHA256 over a 4-char key is brute-forcible from one
+ // observed signature. 16 is the floor, not a recommendation.
+ @MinLength(16)
@MaxLength(255)
secret?: string;
diff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.ts
index d9ca68935..a05b440ad 100644
--- a/test/webhooks.e2e-spec.ts
+++ b/test/webhooks.e2e-spec.ts
@@ -134,7 +134,7 @@ describe('Webhooks (e2e)', () => {
it('creates a webhook and never leaks the secret or headers in the response', async () => {
const session = await nextSession();
const dto = await createWebhook(session, {
- secret: 'top-secret',
+ secret: 'top-secret-0123456789',
headers: { 'X-Custom': 'v' },
filters: { conditions: [{ field: 'sender', operator: 'is', value: ['[email protected]'] }] },
});
@@ -288,7 +288,7 @@ describe('Webhooks (e2e)', () => {
describe('dispatch over real HTTP', () => {
it('delivers a correctly HMAC-signed POST when a filter matches', async () => {
const session = await nextSession();
- const secret = 'sig-secret';
+ const secret = 'sig-secret-0123456789';
await createWebhook(session, {
secret,
filters: { conditions: [{ field: 'sender', operator: 'is', value: ['[email protected]'] }] },
@@ -362,7 +362,7 @@ describe('Webhooks (e2e)', () => {
it('keeps server identity fields on the signed body when a webhook:before hook tampers with them', async () => {
const session = await nextSession();
- const secret = 'sig-secret';
+ const secret = 'sig-secret-0123456789';
await createWebhook(session, { secret });
const hookManager = app.get(HookManager);
@@ -424,7 +424,7 @@ describe('Webhooks (e2e)', () => {
it('delivers over-threshold media as an omitted marker, signed over the exact shed bytes', async () => {
const session = await nextSession();
- const secret = 'media-secret';
+ const secret = 'media-secret-0123456789';
await createWebhook(session, { secret });
const base64 = Buffer.alloc(2048, 11).toString('base64'); // 2048 decoded bytes > 1024 inline cap