Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(proxy): reach an IPv6 SOCKS proxy, and keep its password out of the log
Yudhi Armyndharisf6ed0e9939c2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ddc3b1cff..68a25b9f5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `POST /api/sessions/:sessionId/automation-rules` answers `404` for a session that does not exist, instead of letting the foreign key surface as `500`.- A session proxy whose credentials contain a bare `%` is refused by `POST /api/sessions` and `PATCH /api/sessions/:sessionId/proxy` when it is set, instead of being stored and then failing every later start and every proxied URL fetch with an opaque `URI malformed`.- A WebSocket handshake whose transport closes while the key is being validated no longer burns a slot of the per-key connection cap for the life of the process.+- A repeated query parameter on an ingress verification challenge fails the challenge instead of answering `500`: the value arrives from Express as an array and reached a constant-time compare that accepts only strings.+- A plugin's declared ingress ack can no longer write the response headers that decide how a browser treats its own reflected body, nor set a cookie on the gateway's origin. The declared content type still applies, through the allowlist that already governed it.+- An ingress route whose manifest carries a non-string ack body, status or header is answered rather than failing with `500`; a manifest is third-party JSON and the loader does not type-check every leaf.+- Uploading a zip whose trailer parses but whose directory does not answers `400`, not `500`.+- A `socks5://` or `socks4://` proxy at an IPv6 literal connects: the brackets `URL` keeps were going on the wire as part of a hostname.+- A proxy password no longer reaches the log. A failed SOCKS connect carries the whole proxy config as the error's only property, and `BAILEYS_LOG_LEVEL=debug` wrote it to stdout verbatim.- Baileys sessions list the saved address book again after a process restart. WhatsApp sends neither history nor an app-state snapshot to a device that has synced once, and the contact store is in memory, so a restarted gateway answered `GET /api/sessions/:sessionId/contacts` with only the peers it had seen since. Each session now re-pulls the snapshot of the app-state collection that carries saved contacts, once per engine start. That also repairs a PARTIAL address book, which is the usual shape: during the initial sync WhatsApp folds saved contacts into the history batch, where their names are stripped as chat titles, so the store keeps plenty of contacts with the saved ones missing. The list is also the address book only: a peer known by pushname alone is no longer listed, while `GET .../contacts/:contactId` still resolves it with `isMyContact: false`, and a chat title from history sync no longer overwrites a saved name. Thanks @gabrielmmoraes1999.- whatsapp-web.js sessions send media again on the WhatsApp Web builds rolled out on 2026-09-17: the library spread the media model into the outgoing message after its id, and the model's private `__x_id` clobbered it, so every image, video, audio, document, sticker and status media send failed with `Data passed to getter must include an id property` while text kept working. An install-time patch carries upstream's one-line fix until a whatsapp-web.js release ships it ([#1643](https://github.com/rmyndharis/OpenWA/issues/1643), [#1636](https://github.com/rmyndharis/OpenWA/issues/1636)). Thanks @15874611923 and @Magnarks for the reports.- An ingress route can declare `dedupOn: "body"` to key provider retries on the raw body instead of the delivery-id header. A provider that mints a fresh delivery id on every retry attempt, as supabase/auth does inside its hook retry loop, was never deduplicated when an ack was lost, so the contact received the message twice; routes that do not declare it keep the header ([#1641](https://github.com/rmyndharis/OpenWA/issues/1641)).diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 187adc584..09d253bc5 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4586,14 +4586,14 @@ Create a webhook for the session.**Request body** — `CreateWebhookDto`-| Field | Type | Required | Constraints | Description |-| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| 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`, `@MinLength(16)`, `@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`, `chatId`, `body`, `type`, `isGroup`, `kind`, `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`. |+| Field | Type | Required | Constraints | Description |+| ---------- | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| 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`, `@MinLength(16)`, `@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`, `chatId`, `body`, `type`, `isGroup`, `kind`, `fromMe`, `hasMedia`, `mentions`. An id-valued condition accepts a bare phone number, but a group must be written as its full `<id>@g.us` JID: bare digits canonicalise to `@c.us` and match no group. | 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`. |```json{diff --git a/src/common/security/proxy-dispatcher.ts b/src/common/security/proxy-dispatcher.tsindex 229a4722e..6555c78a0 100644--- a/src/common/security/proxy-dispatcher.ts+++ b/src/common/security/proxy-dispatcher.ts@@ -84,7 +84,9 @@ function socksConnector(proxyUrl: URL, pinnedAddresses?: string[]): buildConnect// SOCKS4 has no authentication: `socks` sends the user id in the connect request and drops the// password. Credentials are decoded here because URL keeps them percent-encoded.const proxy: SocksProxy = {- host: proxyUrl.hostname,+ // `URL` keeps an IPv6 literal bracketed; the SOCKS request carries the address itself, so the+ // brackets would go on the wire as part of a hostname and fail as a DNS lookup of "[::1]".+ host: proxyUrl.hostname.replace(/^\[|\]$/g, ''),port: Number(proxyUrl.port) || DEFAULT_SOCKS_PORT,type,userId: decodeURIComponent(proxyUrl.username) || undefined,diff --git a/src/engine/adapters/baileys-logger.spec.ts b/src/engine/adapters/baileys-logger.spec.tsnew file mode 100644index 000000000..187983763--- /dev/null+++ b/src/engine/adapters/baileys-logger.spec.ts@@ -0,0 +1,33 @@+import { createBaileysLogger } from './baileys-logger';+describe('createBaileysLogger redacts credentials the library hands it', () => {+ const captureLine = (write: (obj: unknown, msg?: string) => void, payload: unknown): Record<string, unknown> => {+ const written: string[] = [];+ const original = process.stdout.write.bind(process.stdout);+ (process.stdout as { write: unknown }).write = (chunk: string): boolean => {+ written.push(chunk);+ return true;+ };+ try {+ write(payload);+ } finally {+ (process.stdout as { write: unknown }).write = original;+ }+ return JSON.parse(written.join('')) as Record<string, unknown>;+ };++ it('replaces a proxy password carried by a socks connect error', () => {+ const previous = process.env.BAILEYS_LOG_LEVEL;+ process.env.BAILEYS_LOG_LEVEL = 'debug';+ try {+ const logger = createBaileysLogger();+ const line = captureLine(logger.error, {+ err: { options: { proxy: { host: 'p', port: 1080, userId: 'u', password: 'hunter2' } } },+ });+ expect(JSON.stringify(line)).not.toContain('hunter2');+ expect(JSON.stringify(line)).toContain('[redacted]');+ expect(JSON.stringify(line)).toContain('"host":"p"');+ } finally {+ process.env.BAILEYS_LOG_LEVEL = previous;+ }+ });+});diff --git a/src/engine/adapters/baileys-logger.ts b/src/engine/adapters/baileys-logger.tsindex 85d1a8595..d1276ac6b 100644--- a/src/engine/adapters/baileys-logger.ts+++ b/src/engine/adapters/baileys-logger.ts@@ -15,6 +15,29 @@ export function createSilentLogger(): BaileysLogger {return logger;}+/** Keys whose value is a credential wherever it appears in a record the library hands over. */+const SECRET_KEYS: ReadonlySet<string> = new Set(['password', 'secret', 'token', 'apikey', 'api_key', 'authorization']);++/**+ * Replace credential-valued keys before a library record is serialised.+ *+ * Baileys hands this logger whatever object the failure carried, and a `socks` connect error carries+ * the whole proxy config, password included, as its only enumerable property. At debug level that+ * went to stdout verbatim, which on a shipped deployment means the proxy password in the container+ * log. Bounded depth: these records nest a couple of levels at most, and a logger must not walk an+ * arbitrary graph on the wire path.+ */+function redactSecrets(value: unknown, depth = 0): unknown {+ if (depth > 4 || value === null || typeof value !== 'object') return value;+ if (Array.isArray(value)) return value.map(v => redactSecrets(v, depth + 1));+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([k, v]) => [+ k,+ SECRET_KEYS.has(k.toLowerCase()) ? '[redacted]' : redactSecrets(v, depth + 1),+ ]),+ );+}+const BAILEYS_LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error'];/**@@ -36,8 +59,9 @@ export function createBaileysLogger(): BaileysLogger {if (BAILEYS_LOG_LEVELS.indexOf(lvl) < threshold) {return;}- const rec =- typeof obj === 'string' ? { msg: obj } : { ...(obj as Record<string, unknown>), ...(msg ? { msg } : {}) };+ const rec = redactSecrets(+ typeof obj === 'string' ? { msg: obj } : { ...(obj as Record<string, unknown>), ...(msg ? { msg } : {}) },+ ) as Record<string, unknown>;process.stdout.write(JSON.stringify({ ts: new Date().toISOString(), level: lvl, context: 'baileys-wire', ...rec }) + '\n',);diff --git a/src/modules/webhook/filters/filter-evaluator.ts b/src/modules/webhook/filters/filter-evaluator.tsindex 6dece2b70..d020470dc 100644--- a/src/modules/webhook/filters/filter-evaluator.ts+++ b/src/modules/webhook/filters/filter-evaluator.ts@@ -23,6 +23,8 @@ const canonicalActor = (jid: string, resolve?: LidResolver): string => toNeutralconst canonicalInput = (value: string, resolve?: LidResolver): string => {// Bare digits are a phone-addressed user; anything else parses as a JID. Mirrors the engine's// user-input canonicalization (byte-identical to the former WaId.fromUserInput().toNeutral()).+ // A group therefore has to be written as a full `<id>@g.us`: digits alone become `<digits>@c.us`+ // and match no group, which the dashboard's chat picker avoids by storing the whole id.const trimmed = value.trim();if (trimmed && !trimmed.includes('@')) {return `${trimmed.replace(/\D/g, '') || trimmed}@c.us`.toLowerCase();diff --git a/src/modules/webhook/filters/filter-types.ts b/src/modules/webhook/filters/filter-types.tsindex 428815bcb..2346a49ca 100644--- a/src/modules/webhook/filters/filter-types.ts+++ b/src/modules/webhook/filters/filter-types.ts@@ -100,8 +100,11 @@ export const FILTER_FIELDS: Record<string, FieldDefinition[]> = {resolve: data => str(data.to),},{- // Conversation JID (DM or group). Every payload in this family carries it: `IncomingMessage`+ // Conversation JID (DM or group). Carried by the message events proper: `IncomingMessage`// declares `chatId` required, and the edited, reaction and revoked events set it explicitly.+ // NOT by `message.ack` and `message.failed`, whose payload is `{ id, messageId, status, ack }`,+ // so a chatId condition suppresses those two entirely rather than scoping them; scope the+ // subscription with `events[]` instead (docs/06 carries the same warning for `sender`).// Deliberately without a fall back to `from`, which is the sender on a DM and this session on// an outbound message, so it would silently scope the filter to the wrong conversation.field: 'chatId',