Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(common): share environment integer parsing

Yudhi Armyndharis3f086bf437a9
diff --git a/src/common/media/load-remote-media.ts b/src/common/media/load-remote-media.ts
index cd471d09f..21de33216 100644
--- a/src/common/media/load-remote-media.ts
+++ b/src/common/media/load-remote-media.ts
@@ -3,6 +3,7 @@ import { EngineNotSentError } from '../errors/engine-not-sent.error';
import { SsrfBlockedError, withSafeFetch } from '../security/ssrf-guard';
import { urlFetchProxy } from '../security/proxy-dispatcher';
import { createLogger } from '../services/logger.service';
+import { positiveIntFromEnv } from '../utils/env-int';
const logger = createLogger('RemoteMedia');
@@ -11,16 +12,6 @@ const DEFAULT_MEDIA_MAX_BYTES = 50 * 1024 * 1024;
/** Default timeout for a server-side media download: 30s (overridable via MEDIA_DOWNLOAD_TIMEOUT_MS). */
const DEFAULT_MEDIA_TIMEOUT_MS = 30_000;
-/**
- * Read a positive-integer knob. Boot validation rejects a malformed value for every key read here,
- * so the fallback covers unset and empty only: `parseInt` accepts the leading digits of a
- * unit-suffixed value and would silently take `50mb` as 50.
- */
-function positiveIntFromEnv(name: string, fallback: number): number {
- const parsed = Number.parseInt(process.env[name] ?? '', 10);
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
-}
-
/**
* Fetch remote media as a Buffer for sending, with an SSRF host guard, a byte cap, and a timeout.
* The guard runs BEFORE any network call, so an internal/reserved URL throws `SsrfBlockedError`
diff --git a/src/common/storage/storage-transfer.ts b/src/common/storage/storage-transfer.ts
index 60439dba4..c6f08d1f6 100644
--- a/src/common/storage/storage-transfer.ts
+++ b/src/common/storage/storage-transfer.ts
@@ -4,6 +4,7 @@ import { createGunzip } from 'zlib';
import * as fs from 'fs';
import { Readable, PassThrough, Transform, pipeline } from 'stream';
import { LoggerService } from '../services/logger.service';
+import { positiveIntFromEnv } from '../utils/env-int';
/** Per-entry buffer cap for an import (200 MiB — 4× the inbound media cap). Bounds a decompression bomb. */
export const DEFAULT_IMPORT_MAX_BYTES = 200 * 1024 * 1024;
@@ -28,11 +29,6 @@ export function isMissingObjectError(error: unknown): boolean {
);
}
-function positiveIntFromEnv(name: string, fallback: number): number {
- const parsed = Number.parseInt(process.env[name] ?? '', 10);
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
-}
-
// ============================================================================
// Export - Create tar.gz stream from current storage
// ============================================================================
diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.ts
index 9fe07348d..9202148c8 100644
--- a/src/common/storage/storage.service.ts
+++ b/src/common/storage/storage.service.ts
@@ -13,6 +13,7 @@ import {
CreateBucketCommand,
} from '@aws-sdk/client-s3';
import { createLogger } from '../services/logger.service';
+import { positiveIntFromEnv } from '../utils/env-int';
import { isSafeStorageKey } from '../utils/path-safety';
import { DEFAULT_S3_KEY_PREFIX, normalizeS3KeyPrefix } from './s3-key-prefix';
import { createExportStream, ExportFileSource, importFromStream, isMissingObjectError } from './storage-transfer';
@@ -63,11 +64,6 @@ export const S3_PROBE_TIMEOUT_MS = 10_000;
export const S3_CONNECT_TIMEOUT_MS = 5_000;
export const S3_SOCKET_TIMEOUT_MS = 30_000;
-function positiveIntFromEnv(name: string, fallback: number): number {
- const parsed = Number.parseInt(process.env[name] ?? '', 10);
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
-}
-
@Injectable()
export class StorageService implements OnModuleDestroy {
private readonly logger = createLogger('StorageService');
diff --git a/src/common/utils/env-int.spec.ts b/src/common/utils/env-int.spec.ts
new file mode 100644
index 000000000..0079806e3
--- /dev/null
+++ b/src/common/utils/env-int.spec.ts
@@ -0,0 +1,45 @@
+import { positiveIntFromEnv, positiveIntOrDefault } from './env-int';
+
+describe('positiveIntFromEnv', () => {
+ const KEY = 'OPENWA_TEST_POSITIVE_INT';
+
+ afterEach(() => {
+ delete process.env[KEY];
+ });
+
+ it('falls back when the variable is unset or empty', () => {
+ expect(positiveIntFromEnv(KEY, 7)).toBe(7);
+ process.env[KEY] = '';
+ expect(positiveIntFromEnv(KEY, 7)).toBe(7);
+ });
+
+ it('reads a plain positive integer', () => {
+ process.env[KEY] = '42';
+ expect(positiveIntFromEnv(KEY, 7)).toBe(42);
+ });
+
+ it.each(['0', '-5', 'abc'])('falls back on %s', raw => {
+ process.env[KEY] = raw;
+ expect(positiveIntFromEnv(KEY, 7)).toBe(7);
+ });
+
+ // Boot validation rejects these before they reach a reader; this pins what the reader itself does.
+ it('takes the leading digits of a unit-suffixed or fractional value', () => {
+ process.env[KEY] = '50mb';
+ expect(positiveIntFromEnv(KEY, 7)).toBe(50);
+ process.env[KEY] = '2.9';
+ expect(positiveIntFromEnv(KEY, 7)).toBe(2);
+ });
+});
+
+describe('positiveIntOrDefault', () => {
+ it.each([undefined, '', ' ', 'abc', 'NaN', 'Infinity', '0', '-3', '0.5'])('falls back on %p', raw => {
+ expect(positiveIntOrDefault(raw, 7)).toBe(7);
+ });
+
+ it('reads a positive number and floors a fraction', () => {
+ expect(positiveIntOrDefault('42', 7)).toBe(42);
+ expect(positiveIntOrDefault('2.9', 7)).toBe(2);
+ expect(positiveIntOrDefault(' 15 ', 7)).toBe(15);
+ });
+});
diff --git a/src/common/utils/env-int.ts b/src/common/utils/env-int.ts
new file mode 100644
index 000000000..1b0c9b836
--- /dev/null
+++ b/src/common/utils/env-int.ts
@@ -0,0 +1,21 @@
+/**
+ * Read a positive-integer knob from the environment. Boot validation rejects a malformed value for
+ * every key read through this, so the fallback covers unset and empty only: `parseInt` accepts the
+ * leading digits of a unit-suffixed value and would silently take `50mb` as 50.
+ */
+export function positiveIntFromEnv(name: string, fallback: number): number {
+ const parsed = Number.parseInt(process.env[name] ?? '', 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+/**
+ * A positive integer from a raw environment value, for the limiters that read their budget leniently:
+ * blank, non-numeric and non-positive values fall back, and a fraction is floored (`2.9` reads as 2).
+ */
+export function positiveIntOrDefault(raw: string | undefined, fallback: number): number {
+ if (!raw || raw.trim() === '') return fallback;
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return fallback;
+ const i = Math.floor(n);
+ return i >= 1 ? i : fallback;
+}
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 1ed2d16f5..82bd979e4 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 { positiveIntFromEnv } from '../common/utils/env-int';
/**
* Root of the host's persistent state. Relative on purpose: the image sets WORKDIR /app and mounts
@@ -286,27 +287,18 @@ export default () => ({
// opt-out here — a 0-byte cap rejects every dispatch (a total webhook outage), and a NaN would
// silently disable the cap (`payloadBytes > NaN` is always false). env.validation rejects
// non-decimal / non-positive values at boot.
- maxPayloadBytes: (() => {
- const n = parseInt(process.env.WEBHOOK_MAX_PAYLOAD_BYTES ?? '', 10);
- return Number.isFinite(n) && n > 0 ? n : 1024 * 1024;
- })(),
+ maxPayloadBytes: positiveIntFromEnv('WEBHOOK_MAX_PAYLOAD_BYTES', 1024 * 1024),
// Max webhooks registered per session. One inbound event fans out to every registered webhook
// of the session, so an unbounded count multiplies per-event copies of the payload. Creating a
// NEW webhook above the cap is rejected with 400; existing ones are grandfathered (never
// deleted). Default 16; 0 disables the cap. Garbage falls back to the default.
- maxPerSession: (() => {
- const n = parseInt(process.env.WEBHOOK_MAX_PER_SESSION ?? '', 10);
- return Number.isFinite(n) && n >= 0 ? n : 16;
- })(),
+ maxPerSession: resolveNonNegativeIntEnv(process.env.WEBHOOK_MAX_PER_SESSION, 16),
// Inline base64 media cap for webhook payloads (decoded bytes). A media blob larger than this
// is replaced with the { omitted: true, sizeBytes } marker BEFORE the payload is cloned per
// webhook / queued into Redis, so fan-out and failed-job retention never copy the blob. Media
// at or under the cap stays inline (unchanged). Default 1 MiB; 0 = never inline media. Garbage
// falls back to the default.
- mediaInlineMaxBytes: (() => {
- const n = parseInt(process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES ?? '', 10);
- return Number.isFinite(n) && n >= 0 ? n : 1024 * 1024;
- })(),
+ mediaInlineMaxBytes: resolveNonNegativeIntEnv(process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES, 1024 * 1024),
// How long shutdown waits for in-flight direct deliveries to finish before abandoning them.
// 0 = don't wait (explicit opt-out); blank/garbage falls back to the default — a NaN here would
// silently remove the drain deadline downstream (Math.max(0, NaN) is NaN).
diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.ts
index 4850cbf4c..020590771 100644
--- a/src/engine/adapters/baileys-message-store.service.ts
+++ b/src/engine/adapters/baileys-message-store.service.ts
@@ -7,11 +7,7 @@ import { BaileysStoredMessage } from './baileys-stored-message.entity';
import { BaileysMessageStore } from '../types/baileys.types';
import { createLogger } from '../../common/services/logger.service';
import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
-
-function positiveIntFromEnv(name: string, fallback: number): number {
- const parsed = Number.parseInt(process.env[name] ?? '', 10);
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
-}
+import { positiveIntFromEnv } from '../../common/utils/env-int';
/**
* True when a write failed because the parent `sessions` row is absent (a foreign-key violation),
diff --git a/src/modules/events/ws-rate-limit.ts b/src/modules/events/ws-rate-limit.ts
index 8258a7fd5..425dd0811 100644
--- a/src/modules/events/ws-rate-limit.ts
+++ b/src/modules/events/ws-rate-limit.ts
@@ -27,6 +27,8 @@
* distinct-key (or spoofed-IP) flood cannot grow process memory without limit.
*/
+import { positiveIntOrDefault } from '../../common/utils/env-int';
+
const DEFAULT_FRAME_PER_SECOND = 60;
const DEFAULT_FRAME_BURST = 120;
const DEFAULT_HANDSHAKE_MAX = 10;
@@ -34,14 +36,6 @@ const DEFAULT_HANDSHAKE_WINDOW_MS = 60_000;
const DEFAULT_MAX_SOCKETS_PER_KEY = 16;
const DEFAULT_MAX_KEYS = 50_000;
-const parsePositiveInt = (raw: string | undefined, fallback: number): number => {
- if (!raw || raw.trim() === '') return fallback;
- const n = Number(raw);
- if (!Number.isFinite(n)) return fallback;
- const i = Math.floor(n);
- return i >= 1 ? i : fallback;
-};
-
export interface WsRateLimitConfig {
framePerSecond: number;
frameBurst: number;
@@ -57,11 +51,11 @@ export interface WsRateLimitConfig {
*/
export function readWsRateLimitConfig(env: NodeJS.ProcessEnv = process.env): WsRateLimitConfig {
return {
- framePerSecond: parsePositiveInt(env['WS_RATE_LIMIT_FRAME_PER_SECOND'], DEFAULT_FRAME_PER_SECOND),
- frameBurst: parsePositiveInt(env['WS_RATE_LIMIT_FRAME_BURST'], DEFAULT_FRAME_BURST),
- handshakeMax: parsePositiveInt(env['WS_RATE_LIMIT_HANDSHAKE_MAX'], DEFAULT_HANDSHAKE_MAX),
- handshakeWindowMs: parsePositiveInt(env['WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS'], DEFAULT_HANDSHAKE_WINDOW_MS),
- maxSocketsPerKey: parsePositiveInt(env['WS_MAX_SOCKETS_PER_KEY'], DEFAULT_MAX_SOCKETS_PER_KEY),
+ framePerSecond: positiveIntOrDefault(env['WS_RATE_LIMIT_FRAME_PER_SECOND'], DEFAULT_FRAME_PER_SECOND),
+ frameBurst: positiveIntOrDefault(env['WS_RATE_LIMIT_FRAME_BURST'], DEFAULT_FRAME_BURST),
+ handshakeMax: positiveIntOrDefault(env['WS_RATE_LIMIT_HANDSHAKE_MAX'], DEFAULT_HANDSHAKE_MAX),
+ handshakeWindowMs: positiveIntOrDefault(env['WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS'], DEFAULT_HANDSHAKE_WINDOW_MS),
+ maxSocketsPerKey: positiveIntOrDefault(env['WS_MAX_SOCKETS_PER_KEY'], DEFAULT_MAX_SOCKETS_PER_KEY),
};
}
diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.ts
index f7d996a94..4ad327846 100644
--- a/src/modules/mcp/mcp-rate-limit.ts
+++ b/src/modules/mcp/mcp-rate-limit.ts
@@ -1,4 +1,5 @@
import { HttpException, HttpStatus } from '@nestjs/common';
+import { positiveIntOrDefault } from '../../common/utils/env-int';
const DEFAULT_MAX = 60;
const DEFAULT_WINDOW_MS = 60_000;
@@ -7,22 +8,14 @@ const DEFAULT_WINDOW_MS = 60_000;
const DEFAULT_IP_MAX = 120;
const DEFAULT_MAX_KEYS = 50_000;
-const parsePositiveInt = (raw: string | undefined, fallback: number): number => {
- if (!raw || raw.trim() === '') return fallback;
- const n = Number(raw);
- if (!Number.isFinite(n)) return fallback;
- const i = Math.floor(n);
- return i >= 1 ? i : fallback;
-};
-
/**
* Read MCP rate-limit configuration from the environment.
* Falls back to the default for any missing, blank, non-positive, or non-numeric value.
*/
export function readRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { max: number; windowMs: number } {
return {
- max: parsePositiveInt(env['MCP_RATE_LIMIT_MAX'], DEFAULT_MAX),
- windowMs: parsePositiveInt(env['MCP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),
+ max: positiveIntOrDefault(env['MCP_RATE_LIMIT_MAX'], DEFAULT_MAX),
+ windowMs: positiveIntOrDefault(env['MCP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),
};
}
@@ -32,8 +25,8 @@ export function readRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { max
*/
export function readIpRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { max: number; windowMs: number } {
return {
- max: parsePositiveInt(env['MCP_IP_RATE_LIMIT_MAX'], DEFAULT_IP_MAX),
- windowMs: parsePositiveInt(env['MCP_IP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),
+ max: positiveIntOrDefault(env['MCP_IP_RATE_LIMIT_MAX'], DEFAULT_IP_MAX),
+ windowMs: positiveIntOrDefault(env['MCP_IP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),
};
}