Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): length-hiding constant-time compare; document tunable env vars (#914)
Yudhi Armyndharis67d86512ac1f
diff --git a/.env.example b/.env.exampleindex 284f114f1..ee43b496d 100644--- a/.env.example+++ b/.env.example@@ -253,6 +253,10 @@ WEBHOOK_SSRF_PROTECT=true# and media — escape-hatch for trusted internal targets (e.g. a localhost media# store or a sidecar webhook receiver).# SSRF_ALLOWED_HOSTS=localhost,minio+# DNS resolution deadline (ms) inside the SSRF guard. The default (10000) is generous for healthy+# resolvers; lowering it shrinks the window a slow/hanging resolver can pin a worker, raising it+# widens that window — tune deliberately. A non-positive/garbage value falls back to the default.+# SSRF_DNS_TIMEOUT_MS=10000# Server-side media size/time limits:# MEDIA_DOWNLOAD_ENABLED=true # Set to false to skip downloading inbound media entirely# # (no decryption, no memory allocation, no storage).@@ -263,6 +267,16 @@ WEBHOOK_SSRF_PROTECT=true# # Default: true (backward compatible — store everything).# MEDIA_DOWNLOAD_MAX_BYTES=52428800 # cap remote-URL sends, inbound media, AND outbound base64 sends (default 50 MiB; oversized inbound media is dropped, message kept; oversized base64 is rejected with 400)# MEDIA_DOWNLOAD_TIMEOUT_MS=30000 # abort a slow media download (default 30s)+# Inbound media download parallelism (how many inbound media items download at once). Each concurrent+# download holds memory up to MEDIA_DOWNLOAD_MAX_BYTES; this bounds N. A non-positive/garbage value+# falls back to the default.+# INBOUND_MEDIA_CONCURRENCY=4 # default 4+# Per-file cap on status (Story) media persisted to disk/S3. A status whose media exceeds this is+# stored omitted (mediaOmitted=true) rather than rejected. A non-positive/garbage value falls back.+# STATUS_MEDIA_MAX_BYTES=10485760 # default 10 MiB+# Cap on concurrently-running bulk batches (POST .../messages/send-bulk). 0 = unlimited. A non-finite+# or negative value falls back to the default.+# BULK_MAX_CONCURRENT_BATCHES=50 # default 50# Storage import/export limits (ADMIN /infra/storage/* endpoints):# STORAGE_IMPORT_MAX_BYTES=209715200 # per-entry cap for a tar.gz import; aborts on overflow (default 200 MiB)# STORAGE_IMPORT_MAX_ENTRIES=100000 # max entries in an import archive; aborts beyond this (default 100000)@@ -286,6 +300,19 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# INGRESS_INSTANCE_LIMIT=120 # max requests per instance per window (default 120)# INGRESS_INSTANCE_TTL=60000 # window in ms (default 60000 = 60s)+# 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+# # compliance-sensitive deployments that manage retention upstream.++# 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,+# so raising these parallelizes unrelated conversations rather than reordering them.+# WEBHOOK_WORKER_CONCURRENCY=10 # webhook delivery workers (default 10)+# INGRESS_WORKER_CONCURRENCY=10 # integration ingress workers (default 10)+# =============================================================================# MCP (Model Context Protocol) — Agent / AI-assistant tool server# =============================================================================@@ -318,6 +345,9 @@ SEARCH_LIMIT_MAX=100 # hard cap on the `limit` query param# PLUGINS# =============================================================================PLUGINS_DIR=./data/plugins # Plugin directory+# Cap on a plugin .zip downloaded by install-from-URL (matches the 5 MB upload limit). A non-positive+# or non-numeric value falls back to the default.+# PLUGIN_DOWNLOAD_MAX_BYTES=5242880 # default 5 MiB# =============================================================================# SECURITYdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 22c07042c..a3955edb1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **Secret comparisons on the `/api/metrics` Bearer and ingress `shared-secret` auth surfaces no+ longer leak the expected token's byte-length.** Both `safeEqualStr` (ingress `shared-secret` verify)+ and `MetricsService.safeEqual` (`/api/metrics` Bearer) used the common `timingSafeEqual` idiom of+ early-returning on a buffer length mismatch — but that early return is itself a timing channel: a+ caller who can time the response learns whether their candidate matches the expected secret's+ length. Both now delegate to a shared `constantTimeEqual` helper that hashes both inputs with a+ per-process random key (fixed-length SHA-256 digests) and `timingSafeEqual`s those, so the value+ comparison stays constant-time and neither input's length affects control flow. The `hmac-sha256`+ and `standard-webhooks` schemes compare fixed-length digests and were not affected.+- **npm dependency vulnerabilities pinned via `overrides` (root + dashboard).**`brace-expansion` bumped to `^5.0.8` (CVE-2026-14257, ReDoS; was present atboth 2.1.2 and 5.0.7 in the root tree, and 5.0.6 in the dashboard tree) and@@ -26,6 +36,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Changed+- **Ten operator-tunable environment variables are now documented in `.env.example`.**+ `INGRESS_MAX_ATTEMPTS`, `INGRESS_RETRY_DELAY_MS`, `INGRESS_RETENTION_DAYS`, `SSRF_DNS_TIMEOUT_MS`,+ `INGRESS_WORKER_CONCURRENCY`, `WEBHOOK_WORKER_CONCURRENCY`, `INBOUND_MEDIA_CONCURRENCY`,+ `STATUS_MEDIA_MAX_BYTES`, `PLUGIN_DOWNLOAD_MAX_BYTES`, and `BULK_MAX_CONCURRENT_BATCHES` are read+ from the environment with sensible defaults but were absent from the configuration reference. Each+ is now documented next to its related block, with the exact default and the parse semantics+ (`INGRESS_RETENTION_DAYS <= 0` disables pruning, `BULK_MAX_CONCURRENT_BATCHES = 0` is unlimited, the+ DoS trade-off on `SSRF_DNS_TIMEOUT_MS`).+- **Dockerfile `apt-get install` invocations now use `--no-install-recommends`**(build-stage build deps and production-stage Chromium/Puppeteer deps).Smaller image; no behavior change for the explicitly-listed packages.diff --git a/src/common/security/constantTimeEqual.spec.ts b/src/common/security/constantTimeEqual.spec.tsnew file mode 100644index 000000000..f9eccf0e3--- /dev/null+++ b/src/common/security/constantTimeEqual.spec.ts@@ -0,0 +1,38 @@+import { constantTimeEqual } from './constantTimeEqual';++describe('constantTimeEqual', () => {+ it('returns true for identical strings', () => {+ expect(constantTimeEqual('abc', 'abc')).toBe(true);+ expect(constantTimeEqual('', '')).toBe(true);+ expect(constantTimeEqual('a-secret-token-1234567890', 'a-secret-token-1234567890')).toBe(true);+ });++ it('returns false for different content of the same length (the value compare still works)', () => {+ expect(constantTimeEqual('abc', 'abd')).toBe(false);+ expect(constantTimeEqual('secret-1', 'secret-2')).toBe(false);+ });++ it('returns false for different lengths (no early-return length leak — the digests are fixed-length)', () => {+ // The length-mismatch case must still resolve to false, just without branching on input length.+ expect(constantTimeEqual('a', 'ab')).toBe(false);+ expect(constantTimeEqual('short', 'a-much-longer-secret-value')).toBe(false);+ expect(constantTimeEqual('a-much-longer-secret-value', 'short')).toBe(false);+ expect(constantTimeEqual('', 'non-empty')).toBe(false);+ expect(constantTimeEqual('non-empty', '')).toBe(false);+ });++ it('handles multi-byte UTF-8 correctly (compares bytes, not chars)', () => {+ // 'é' is 2 UTF-8 bytes; 'e' is 1. Different bytes → not equal even though both "look like e".+ expect(constantTimeEqual('café', 'café')).toBe(true);+ expect(constantTimeEqual('café', 'cafe')).toBe(false);+ // Emoji are 4 bytes; equality must hold across them.+ expect(constantTimeEqual('🔑', '🔑')).toBe(true);+ expect(constantTimeEqual('🔑', '🔓')).toBe(false);+ });++ it('is reflexive and symmetric', () => {+ expect(constantTimeEqual('x', 'x')).toBe(true);+ expect(constantTimeEqual('x', 'y')).toBe(false);+ expect(constantTimeEqual('y', 'x')).toBe(false); // symmetric+ });+});diff --git a/src/common/security/constantTimeEqual.ts b/src/common/security/constantTimeEqual.tsnew file mode 100644index 000000000..4c5b0e1ed--- /dev/null+++ b/src/common/security/constantTimeEqual.ts@@ -0,0 +1,26 @@+import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';++// Per-process random key. Hashing both inputs with the same key before comparing fixes the digest+// length, so timingSafeEqual never sees unequal lengths and there is no early length-mismatch return+// that would leak the expected secret's byte-length through a fast vs slow response. The key is+// random per process so pre-computed digests from outside the process are useless.+const EQ_KEY = randomBytes(32);++/**+ * Constant-time string equality that does NOT leak the expected value's length.+ *+ * `timingSafeEqual` throws on unequal buffer lengths, so the common idiom is to early-return on a+ * length mismatch — but that early return is itself a timing channel: an attacker who can time the+ * call learns whether their candidate matches the expected length. On `@Public` auth surfaces+ * (`/api/metrics` Bearer, ingress `shared-secret`) that turns into "learn the byte-length of the+ * operator's token/secret" in a handful of probes.+ *+ * Hash both inputs with a per-process random key (fixed-length SHA-256 digests) and compare those.+ * The result is the same boolean equality, the value comparison stays constant-time, and the length+ * of either input no longer affects control flow.+ */+export function constantTimeEqual(a: string, b: string): boolean {+ const ha = createHash('sha256').update(EQ_KEY).update(a).digest();+ const hb = createHash('sha256').update(EQ_KEY).update(b).digest();+ return timingSafeEqual(ha, hb);+}diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.tsindex ebbf48636..511039fb2 100644--- a/src/modules/integration/ingress-signature.ts+++ b/src/modules/integration/ingress-signature.ts@@ -1,5 +1,6 @@-import { createHmac, timingSafeEqual } from 'node:crypto';+import { createHmac } from 'node:crypto';import { IngressSignatureSpec } from '../../core/plugins/plugin.interfaces';+import { constantTimeEqual } from '../../common/security/constantTimeEqual';export interface VerifyInput {rawBody: string;@@ -123,9 +124,11 @@ export function verifyIngressSignature(return safeEqualStr(provided, expected) ? { ok: true } : { ok: false, reason: 'hmac mismatch' };}+/**+ * Constant-time string equality that does not leak the expected value's length.+ * Kept as a named export for the ingress call sites; delegates to the shared helper so the metrics+ * token compare and the ingress signature compares stay in lockstep.+ */export function safeEqualStr(a: string, b: string): boolean {- const ba = Buffer.from(a);- const bb = Buffer.from(b);- if (ba.length !== bb.length) return false;- return timingSafeEqual(ba, bb);+ return constantTimeEqual(a, b);}diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.tsindex a58ab6939..b15784290 100644--- a/src/modules/metrics/metrics.service.ts+++ b/src/modules/metrics/metrics.service.ts@@ -1,6 +1,6 @@import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';-import { timingSafeEqual } from 'crypto';+import { constantTimeEqual } from '../../common/security/constantTimeEqual';import { StatsService } from '../stats/stats.service';import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';import {@@ -54,12 +54,10 @@ export class MetricsService {}private safeEqual(a: string, b: string): boolean {- const ab = Buffer.from(a);- const bb = Buffer.from(b);- // timingSafeEqual requires equal lengths; compare to a fixed digest of `b` to avoid- // leaking the expected length through an early return.- if (ab.length !== bb.length) return false;- return timingSafeEqual(ab, bb);+ // Length-hiding constant-time compare: hash both inputs with a per-process key (fixed-length+ // digests) then timingSafeEqual, so the expected token's byte-length is not leaked through a+ // fast length-mismatch return. This `/api/metrics` endpoint is @Public and timed by callers.+ return constantTimeEqual(a, b);}/** Render the current metrics in Prometheus text exposition format (memoized for a short TTL). */