Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(common): parse TRUSTED_PROXIES in one place
Yudhi Armyndharis043697419f35
diff --git a/src/common/security/proxy-aware-throttler.guard.ts b/src/common/security/proxy-aware-throttler.guard.tsindex df15b1a75..2274ba7c3 100644--- a/src/common/security/proxy-aware-throttler.guard.ts+++ b/src/common/security/proxy-aware-throttler.guard.ts@@ -1,6 +1,6 @@import { ExecutionContext, Injectable } from '@nestjs/common';import { normalizeIp, ThrottlerGuard, ThrottlerLimitDetail } from '@nestjs/throttler';-import { resolveClientIp, RequestLike } from '../utils/ip';+import { parseTrustedProxies, resolveClientIp, RequestLike } from '../utils/ip';import { createLogger } from '../services/logger.service';const logger = createLogger('ProxyAwareThrottlerGuard');@@ -42,10 +42,7 @@ export class ProxyAwareThrottlerGuard extends ThrottlerGuard {private warnedSharedProxyBucket = false;protected getTracker(req: Record<string, unknown>): Promise<string> {- const trustedProxies = (process.env.TRUSTED_PROXIES || '')- .split(',')- .map(proxy => proxy.trim())- .filter(Boolean);+ const trustedProxies = parseTrustedProxies(process.env.TRUSTED_PROXIES);// An X-Forwarded-For header with an empty TRUSTED_PROXIES is the silent self-DoS this guard// exists to prevent: every client collapses onto the proxy's socket address, so all traffic// shares ONE bucket per tier and one abuser rate-limits everyone. The header itself must staydiff --git a/src/common/utils/ip.spec.ts b/src/common/utils/ip.spec.tsindex 899dbeab4..cdb1c7ef6 100644--- a/src/common/utils/ip.spec.ts+++ b/src/common/utils/ip.spec.ts@@ -1,4 +1,12 @@-import { normalizeIp, ipMatches, limiterKeyForIp, resolveClientIp, isIpOrCidrEntry, invalidTrustedProxies } from './ip';+import {+ normalizeIp,+ ipMatches,+ limiterKeyForIp,+ resolveClientIp,+ isIpOrCidrEntry,+ invalidTrustedProxies,+ parseTrustedProxies,+} from './ip';describe('normalizeIp', () => {it('strips an IPv4-mapped IPv6 prefix', () => {@@ -141,3 +149,17 @@ describe('resolveClientIp', () => {);});});++describe('parseTrustedProxies', () => {+ it('splits on commas, trims each entry and drops blanks', () => {+ expect(parseTrustedProxies(' 10.0.0.1, 172.18.0.0/16 ,, fd00::/8 ')).toEqual([+ '10.0.0.1',+ '172.18.0.0/16',+ 'fd00::/8',+ ]);+ });++ it.each([undefined, '', ' ', ' , , '])('reads %p as no proxies', raw => {+ expect(parseTrustedProxies(raw)).toEqual([]);+ });+});diff --git a/src/common/utils/ip.ts b/src/common/utils/ip.tsindex 75f1cf827..6fe2b3d60 100644--- a/src/common/utils/ip.ts+++ b/src/common/utils/ip.ts@@ -117,10 +117,15 @@ export function isIpOrCidrEntry(entry: string): boolean {* never matches a peer, so the proxy it was meant to name is treated as a direct client.*/export function invalidTrustedProxies(raw: string | undefined): string[] {+ return parseTrustedProxies(raw).filter(entry => !isIpOrCidrEntry(entry));+}++/** The comma-separated TRUSTED_PROXIES value as a list of entries; blanks are dropped. */+export function parseTrustedProxies(raw: string | undefined): string[] {return (raw || '').split(',').map(entry => entry.trim())- .filter(entry => entry && !isIpOrCidrEntry(entry));+ .filter(Boolean);}/**diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 82bd979e4..f04fd6749 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -5,6 +5,7 @@ import { resolveInflightBodyBudgetBytes } from './inflight-body-budget';import { resolveRequestTimeoutMs } from './http-timeouts';import { readWsRateLimitConfig } from '../modules/events/ws-rate-limit';import { DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS, MAX_TIMER_MS } from '../common/services/shutdown-budget';+import { parseTrustedProxies } from '../common/utils/ip';import { positiveIntFromEnv } from '../common/utils/env-int';/**@@ -338,10 +339,7 @@ export default () => ({// may be trusted for client-IP resolution. Empty by default: X-Forwarded-For// is ignored and the direct socket address is used, preventing spoofing of// the API-key allowedIps whitelist.- trustedProxies: (process.env.TRUSTED_PROXIES || '')- .split(',')- .map(proxy => proxy.trim())- .filter(Boolean),+ trustedProxies: parseTrustedProxies(process.env.TRUSTED_PROXIES),},// Plugin platform configurationdiff --git a/src/configure-app.ts b/src/configure-app.tsindex 9363a64b5..a417d466e 100644--- a/src/configure-app.ts+++ b/src/configure-app.ts@@ -18,6 +18,7 @@ import { ShutdownService } from './common/services/shutdown.service';import { injectDashboardCspNonce } from './config/dashboard-csp';import { resolveCorsPolicy, isUpgradeInsecureRequestsEnabled, resolveBodyLimit } from './config/bootstrap-security';import { resolveRequestTimeoutMs } from './config/http-timeouts';+import { parseTrustedProxies } from './common/utils/ip';/** Where the bundled dashboard documents come from, and whether to serve them at all. */export interface DashboardSource {@@ -259,10 +260,7 @@ export function configureApp(app: INestApplication, options: ConfigureAppOptionsconst keyIndex = optional(ActiveKeyIndex);app.use(createInflightBodyBudget(inflightBudgetBytes, {- trustedProxies: (process.env.TRUSTED_PROXIES || '')- .split(',')- .map(p => p.trim())- .filter(Boolean),+ trustedProxies: parseTrustedProxies(process.env.TRUSTED_PROXIES),classify: (req, clientIp) => keyIndex?.recognise(req.headers, clientIp),bodyLimitBytes: parseBodyLimitBytes(bodyLimit),requestTimeoutMs: resolveRequestTimeoutMs(process.env.REQUEST_TIMEOUT_MS),diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex ffb8c3122..c482ebb30 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -18,7 +18,12 @@ import { isWsRedisEnabled } from './redis-io.adapter';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveCorsPolicy } from '../../config/bootstrap-security';-import { limiterKeyForIp, resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';+import {+ limiterKeyForIp,+ parseTrustedProxies,+ resolveClientIp as resolveRequestClientIp,+ type RequestLike,+} from '../../common/utils/ip';import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';import { isSafeSessionName } from '../../common/utils/path-safety';import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';@@ -45,10 +50,7 @@ function resolveWsCorsOrigin(): boolean | string[] {* client IP with the same trusted-proxy-aware logic as the REST guard and the MCP mount.*/function readTrustedProxies(): string[] {- return (process.env.TRUSTED_PROXIES ?? '')- .split(',')- .map(s => s.trim())- .filter(Boolean);+ return parseTrustedProxies(process.env.TRUSTED_PROXIES);}import type {WSClientMessage,diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex 713ee225d..128090300 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -17,7 +17,7 @@ import type { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { handleToolError, jsonToolResult, smartToolResult } from './tool-result';import type { KeyRateLimiter } from './mcp-rate-limit';-import { limiterKeyForIp, resolveClientIp } from '../../common/utils/ip';+import { limiterKeyForIp, parseTrustedProxies, resolveClientIp } from '../../common/utils/ip';import { resolveBodyLimit } from '../../config/bootstrap-security';import { presentedApiKey } from '../../common/security/bearer-token';@@ -72,10 +72,7 @@ export function auditMcpAuthFailure(/** Read TRUSTED_PROXIES once as a list (shared by the pre-auth throttle and the audit IP resolver). */function readTrustedProxies(): string[] {- return (process.env.TRUSTED_PROXIES ?? '')- .split(',')- .map(s => s.trim())- .filter(Boolean);+ return parseTrustedProxies(process.env.TRUSTED_PROXIES);}/** Resolve the trusted-proxy-aware client IP + HTTP method/path for an audit record. */