Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): clamp reconnect-backoff config to prevent a relaunch storm (#327)

Yudhi Armyndharis965a0888fa4f
diff --git a/src/modules/session/reconnect-config.spec.ts b/src/modules/session/reconnect-config.spec.ts
new file mode 100644
index 000000000..01ac43437
--- /dev/null
+++ b/src/modules/session/reconnect-config.spec.ts
@@ -0,0 +1,53 @@
+import { resolveReconnectConfig, clampReconnectDelay } from './session.service';
+
+// F-03 — an OPERATOR-supplied session.config flows into the reconnect backoff math unchecked.
+// config:{reconnectBaseDelay:'x'} makes the delay NaN -> setTimeout(fn, NaN) fires at 0 (relaunch
+// storm); config:{maxReconnectAttempts:'x'} makes the terminal guard `n >= NaN` always false, so the
+// loop never caps. These helpers coerce + clamp the config so the math is always finite and bounded.
+describe('resolveReconnectConfig (F-03)', () => {
+ it('uses the 5000ms / 5-attempt defaults for absent or empty config', () => {
+ expect(resolveReconnectConfig(null)).toEqual({ baseDelay: 5000, maxAttempts: 5 });
+ expect(resolveReconnectConfig({})).toEqual({ baseDelay: 5000, maxAttempts: 5 });
+ });
+
+ it('falls back to defaults for non-numeric (NaN) values', () => {
+ expect(resolveReconnectConfig({ reconnectBaseDelay: 'x', maxReconnectAttempts: 'y' })).toEqual({
+ baseDelay: 5000,
+ maxAttempts: 5,
+ });
+ });
+
+ it('clamps a huge baseDelay down to the 5-minute max (no infinite-timer wedge)', () => {
+ expect(resolveReconnectConfig({ reconnectBaseDelay: 1e15 }).baseDelay).toBe(300_000);
+ });
+
+ it('clamps a negative/too-small baseDelay up to the 1s min (no immediate relaunch)', () => {
+ expect(resolveReconnectConfig({ reconnectBaseDelay: -5 }).baseDelay).toBe(1000);
+ expect(resolveReconnectConfig({ reconnectBaseDelay: 0 }).baseDelay).toBe(1000);
+ });
+
+ it('clamps maxAttempts to the 0..20 range and floors fractions', () => {
+ expect(resolveReconnectConfig({ maxReconnectAttempts: 999 }).maxAttempts).toBe(20);
+ expect(resolveReconnectConfig({ maxReconnectAttempts: -3 }).maxAttempts).toBe(0);
+ expect(resolveReconnectConfig({ maxReconnectAttempts: 3.9 }).maxAttempts).toBe(3);
+ });
+
+ it('preserves a legitimate maxReconnectAttempts: 0 (disable reconnect) instead of forcing the default', () => {
+ expect(resolveReconnectConfig({ maxReconnectAttempts: 0 }).maxAttempts).toBe(0);
+ });
+});
+
+describe('clampReconnectDelay (F-03)', () => {
+ it('passes a finite delay through, flooring at 0', () => {
+ expect(clampReconnectDelay(8000, 5000)).toBe(8000);
+ expect(clampReconnectDelay(-1, 5000)).toBe(0);
+ });
+
+ it('falls back to baseDelay for a non-finite delay (NaN from a poisoned config)', () => {
+ expect(clampReconnectDelay(NaN, 5000)).toBe(5000);
+ });
+
+ it('caps the exponential so it never exceeds setTimeout range and fires immediately', () => {
+ expect(clampReconnectDelay(1e15, 5000)).toBe(3_600_000);
+ });
+});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index e4ba09075..61ca9f5e6 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -38,6 +38,40 @@ interface ReconnectState {
baseDelay: number;
}
+// Reconnect-backoff bounds. An OPERATOR-supplied session.config feeds this math, so the values
+// are coerced + clamped: a non-numeric value would otherwise make the delay NaN (setTimeout fires
+// at 0 — relaunch storm) and the terminal guard `attempts >= NaN` always false (unbounded loop).
+const RECONNECT_BASE_DELAY_MIN_MS = 1000;
+const RECONNECT_BASE_DELAY_MAX_MS = 300_000;
+const RECONNECT_MAX_ATTEMPTS_CAP = 20;
+const RECONNECT_DELAY_CAP_MS = 3_600_000;
+
+const clampNumber = (n: number, min: number, max: number): number => Math.min(Math.max(n, min), max);
+
+/** Coerce + clamp the untyped session.config reconnect knobs to finite, bounded values. Defaults
+ * (5000ms / 5 attempts) are preserved; a legitimate `maxReconnectAttempts: 0` (disable) is kept. */
+export function resolveReconnectConfig(
+ config: { maxReconnectAttempts?: unknown; reconnectBaseDelay?: unknown } | null,
+): { maxAttempts: number; baseDelay: number } {
+ const baseRaw = Number(config?.reconnectBaseDelay);
+ const baseDelay = clampNumber(
+ Number.isFinite(baseRaw) ? baseRaw : 5000,
+ RECONNECT_BASE_DELAY_MIN_MS,
+ RECONNECT_BASE_DELAY_MAX_MS,
+ );
+ const attemptsRaw = Number(config?.maxReconnectAttempts);
+ const maxAttempts = Math.floor(
+ clampNumber(Number.isFinite(attemptsRaw) ? attemptsRaw : 5, 0, RECONNECT_MAX_ATTEMPTS_CAP),
+ );
+ return { maxAttempts, baseDelay };
+}
+
+/** Clamp a computed backoff delay finite and within setTimeout's safe range (a huge value would
+ * overflow its 32-bit ms field and fire immediately). */
+export function clampReconnectDelay(rawDelay: number, baseDelay: number): number {
+ return clampNumber(Number.isFinite(rawDelay) ? rawDelay : baseDelay, 0, RECONNECT_DELAY_CAP_MS);
+}
+
@Injectable()
export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicationBootstrap {
private readonly logger = createLogger('SessionService');
@@ -329,17 +363,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
},
);
- // Initialize reconnect state
- const config = session.config as {
- maxReconnectAttempts?: number;
- reconnectBaseDelay?: number;
- } | null;
- this.reconnectStates.set(id, {
- attempts: 0,
- timer: null,
- maxAttempts: config?.maxReconnectAttempts ?? 5,
- baseDelay: config?.reconnectBaseDelay ?? 5000,
- });
+ // Initialize reconnect state from the (untrusted) opaque session.config — coerced + clamped
+ // so a poisoned value can't drive a NaN/immediate-relaunch storm or an unbounded loop (F-03).
+ const { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);
+ this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });
await this.initializeEngine(id, session);
return this.findOne(id);
@@ -724,8 +751,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return;
}
- // Exponential backoff: baseDelay * 2^attempts (with jitter)
- const delay = state.baseDelay * Math.pow(2, state.attempts) + Math.random() * 1000;
+ // Exponential backoff: baseDelay * 2^attempts (with jitter), clamped finite + within
+ // setTimeout's safe range so the timer can't overflow and fire immediately.
+ const delay = clampReconnectDelay(
+ state.baseDelay * Math.pow(2, state.attempts) + Math.random() * 1000,
+ state.baseDelay,
+ );
state.attempts++;
this.logger.log(