Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): validate the read config keys when a session is created

Yudhi Armyndharis51624123eea8
diff --git a/src/modules/session/dto/create-session.dto.spec.ts b/src/modules/session/dto/create-session.dto.spec.ts
index 4cd8d4dbd..64d1e0ed9 100644
--- a/src/modules/session/dto/create-session.dto.spec.ts
+++ b/src/modules/session/dto/create-session.dto.spec.ts
@@ -1,5 +1,7 @@
+import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { validateSync } from 'class-validator';
import { plainToInstance } from 'class-transformer';
+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';
import { CreateSessionDto } from './create-session.dto';
describe('CreateSessionDto proxyUrl validation', () => {
@@ -47,3 +49,44 @@ describe('CreateSessionDto config validation', () => {
expect(errs({ maxReconnectAttempts: 5, custom: 'x' })).toHaveLength(0);
});
});
+
+/**
+ * The three keys the session reads are held to the same rules as PATCH /config. Stored unvalidated, an
+ * out-of-range value was clamped at start time without a word: -1 or 0.5 became 0 and disabled
+ * reconnect, and the string "true" left autoRejectCalls off.
+ */
+describe('CreateSessionDto config keys through the global pipe', () => {
+ const pipe = new ValidationPipe(GLOBAL_VALIDATION_OPTIONS);
+ const create = (config: Record<string, unknown>): Promise<CreateSessionDto> =>
+ pipe.transform(
+ { name: 'my-bot', config },
+ { type: 'body', metatype: CreateSessionDto },
+ ) as Promise<CreateSessionDto>;
+
+ it.each([
+ [{ maxReconnectAttempts: -1 }, 'config.maxReconnectAttempts must not be less than 0'],
+ [{ maxReconnectAttempts: 0.5 }, 'config.maxReconnectAttempts must be an integer number'],
+ [{ maxReconnectAttempts: 50 }, 'config.maxReconnectAttempts must not be greater than 20'],
+ [{ reconnectBaseDelay: 500 }, 'config.reconnectBaseDelay must not be less than 1000'],
+ [{ autoRejectCalls: 'yes' }, 'config.autoRejectCalls must be a boolean value'],
+ ])('refuses %j with a 400 naming the key', async (config, message) => {
+ const error = await create(config).then(
+ () => undefined,
+ (e: unknown) => e,
+ );
+ expect(error).toBeInstanceOf(BadRequestException);
+ expect(((error as BadRequestException).getResponse() as { message: string[] }).message).toEqual([
+ expect.stringContaining(message),
+ ]);
+ });
+
+ it('stores the strict spellings PATCH /config accepts as their typed values', async () => {
+ const dto = await create({ autoRejectCalls: 'true', maxReconnectAttempts: '5', reconnectBaseDelay: 2000 });
+ expect(dto.config).toEqual({ autoRejectCalls: true, maxReconnectAttempts: 5, reconnectBaseDelay: 2000 });
+ });
+
+ it('keeps unknown keys and leaves absent ones absent', async () => {
+ const dto = await create({ custom: 'x', maxReconnectAttempts: null });
+ expect(dto.config).toEqual({ custom: 'x', maxReconnectAttempts: null });
+ });
+});
diff --git a/src/modules/session/dto/create-session.dto.ts b/src/modules/session/dto/create-session.dto.ts
index f4fecbe5b..9e85526c2 100644
--- a/src/modules/session/dto/create-session.dto.ts
+++ b/src/modules/session/dto/create-session.dto.ts
@@ -1,7 +1,9 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { Transform } from 'class-transformer';
import { IsIn, IsObject, IsOptional, IsString, IsUrl, Matches, MaxLength, MinLength, Validate } from 'class-validator';
import { MaxCodePoints } from '../../../common/validation/max-code-points';
import { HasDecodableProxyCredentialsConstraint } from './has-decodable-proxy-credentials.validator';
+import { normaliseSessionConfig, RecognisedSessionConfigConstraint } from './recognised-session-config.validator';
export class CreateSessionDto {
@ApiProperty({
@@ -32,8 +34,10 @@ export class CreateSessionDto {
'from the next session start.',
example: { autoRejectCalls: false, maxReconnectAttempts: 5, reconnectBaseDelay: 5000 },
})
+ @Transform(({ value }) => normaliseSessionConfig(value))
@IsOptional()
@IsObject()
+ @Validate(RecognisedSessionConfigConstraint)
config?: Record<string, unknown>;
// Phase 3: Proxy per session
diff --git a/src/modules/session/dto/recognised-session-config.validator.ts b/src/modules/session/dto/recognised-session-config.validator.ts
new file mode 100644
index 000000000..c3d01cdc0
--- /dev/null
+++ b/src/modules/session/dto/recognised-session-config.validator.ts
@@ -0,0 +1,49 @@
+import { plainToInstance } from 'class-transformer';
+import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface, validateSync } from 'class-validator';
+import { UpdateSessionConfigDto } from './session-config.dto';
+
+const RECOGNISED_KEYS = ['autoRejectCalls', 'maxReconnectAttempts', 'reconnectBaseDelay'] as const;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/** The recognised keys the caller sent, through UpdateSessionConfigDto's strict coercions. */
+function recognisedKeys(config: Record<string, unknown>): UpdateSessionConfigDto {
+ const sent = Object.fromEntries(RECOGNISED_KEYS.filter(key => key in config).map(key => [key, config[key]]));
+ return plainToInstance(UpdateSessionConfigDto, sent);
+}
+
+/**
+ * The create body's `config`, with the three keys the session reads coerced exactly as PATCH /config
+ * coerces them (`"true"` to `true`, `"5"` to `5`), so a value that route accepts is stored typed.
+ * Unknown keys are kept as sent: they are stored but ignored. A non-object is left for `@IsObject`.
+ */
+export function normaliseSessionConfig(value: unknown): unknown {
+ if (!isRecord(value)) return value;
+ const coerced = recognisedKeys(value);
+ const normalised = { ...value };
+ for (const key of RECOGNISED_KEYS) if (key in value) normalised[key] = coerced[key];
+ return normalised;
+}
+
+function configErrors(value: unknown): string[] {
+ if (!isRecord(value)) return [];
+ return validateSync(recognisedKeys(value))
+ .flatMap(error => Object.values(error.constraints ?? {}))
+ .map(message => `config.${message}`);
+}
+
+/**
+ * Hold the create route's `config` to the rules PATCH /config enforces on the same three keys. Without
+ * it the values were stored as sent and clamped at start time without a word: `-1` or `0.5` turned
+ * reconnect off, `50` became `20`, and `"yes"` left autoRejectCalls off.
+ */
+@ValidatorConstraint({ name: 'isRecognisedSessionConfig', async: false })
+export class RecognisedSessionConfigConstraint implements ValidatorConstraintInterface {
+ validate(value: unknown): boolean {
+ return configErrors(value).length === 0;
+ }
+ defaultMessage(args: ValidationArguments): string {
+ return configErrors(args.value).join('; ');
+ }
+}