Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: read boolean and numeric request fields strictly, and harden the new group, call, edit and status paths (#845)
Yudhi Armyndharisd2a2041a665c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex addd06cae..5d5549b17 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,35 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]-### Security--- **Resolved every known advisory in the dependency tree (17 → 0, including one critical).** The- critical one was a set of path-traversal and symlink issues in `node-tar`, reached only through- `sqlite3@5` → `node-gyp` → `tar`. `sqlite3` moves to `6.0.1`, which drops the `node-gyp`- dependency entirely in favour of `prebuild-install` and pulls a patched `tar@7`; `typeorm` moves- to `0.3.31`, the first release declaring `sqlite3@^6` as a supported peer. `shell-quote` (reached- through the `concurrently` dev dependency, and with no upstream fix available on any release- line) is pinned forward with an `overrides` entry.-- The bundled SQLite build advances to 3.52.0. Migrations, the FTS5 full-text search tables, both- database connections and a full boot were verified against the new driver.--### Changed--- **The security audit runs as its own CI job.** `npm audit` reports against the advisory database- rather than against the diff, so a newly published advisory turns red on unrelated pull requests.- While it was the first step of the Lint job, that failure aborted the job before ESLint, the- type-check, the format check, the version-consistency check and the OpenAPI drift gate had run —- so an advisory silently switched off every code-quality gate at once. It is still blocking (the- build job depends on it) but can no longer mask an unrelated result.-### Added-- **Outbound message edit.** `POST /api/sessions/:sessionId/messages/edit` edits the text of amessage sent by the account, on both engines (whatsapp-web.js `Message.edit`, Baileys`sendMessage` with an `edit` key). Attempting to edit another sender's message fails with `403`,an unknown message/chat with `404`, and the stored record's body is updated through the sameserialized mutation queue as inbound edit events. `message.edited` continues to cover inbound edits.+ An edit passes the `message:sending` plugin gate like every other sender, so a plugin can rewrite+ or block the replacement text.- **Live group events.** `group.join`, `group.leave`, and `group.update` are now actuallydispatched — to webhooks (HMAC-signed, with stable idempotency keys) and to Socket.IOsubscribers — on both engines. They were previously accepted in subscriptions but never emitted@@ -51,12 +30,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0(`announce`, `locked`) and the disappearing-message timer (`ephemeralSeconds`, Baileys only — itreturns a documented `501` on whatsapp-web.js, which has no such API). A settings patch appliesthe timer first, so a `501` can never silently follow an already-applied flag change, and- explicit `null` fields are rejected with `400`.+ explicit `null` fields are rejected with `400`. `announce` and `locked` accept only a real boolean+ or the exact strings `"true"`/`"false"`; any other spelling is rejected with `400` rather than+ being interpreted, so a form-encoded `announce=false` can never restrict a group. `ephemeralSeconds`+ is read the same way — a blank value is a `400`, not a silent `0` that would switch the+ disappearing-message timer off.- **Own-profile management.** `PUT /api/sessions/:sessionId/profile/name`, `/status`, and`/picture` set the linked account's display name, about text, and profile picture on both engines.- **Incoming-call handling.** A new `call.received` webhook + Socket.IO event fires when anincoming call starts ringing (both engines; stale offers replayed from an offline window and the- account's own outgoing calls are not emitted). `POST /api/sessions/:sessionId/calls/:callId/reject`+ account's own outgoing calls are not emitted). It fires once per call: both engines signal a+ ringing call more than once (whatsapp-web.js on every write to its internal call map, Baileys via+ the `offer` and `offer_notice` tags), and only the first is dispatched.+ `POST /api/sessions/:sessionId/calls/:callId/reject`rejects a ringing call, and the per-session `config.autoRejectCalls: true` flag (settable atsession creation) rejects every incoming call automatically — the event is still dispatchedfirst. Unknown or expired call ids return `404`.@@ -65,7 +51,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0[OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) repo, and`docs/23-community-integrations.md` clarifies that it lists community projects only.-### Fixed+### Changed+- **The security audit runs as its own CI job.** `npm audit` reports against the advisory database+ rather than against the diff, so a newly published advisory turns red on unrelated pull requests.+ While it was the first step of the Lint job, that failure aborted the job before ESLint, the+ type-check, the format check, the version-consistency check and the OpenAPI drift gate had run —+ so an advisory silently switched off every code-quality gate at once. It is still blocking (the+ build job depends on it) but can no longer mask an unrelated result.++- **Status posts now pass the `message:sending` plugin gate.** `POST /api/sessions/:sessionId/status/{text,image,video}`+ publish content from the linked account, but were the only content-bearing senders that did not+ consult plugins first. They now run the same gate as chat sends, tagged `status-text`,+ `status-image` and `status-video`, with the hook context `source` set to `StatusService` so a+ plugin can distinguish a status post from a chat send. A blocked post returns `400`, now declared+ on all three operations. A plugin may also rewrite the post; a rewritten media payload is+ re-checked against the data-URI and `MEDIA_DOWNLOAD_MAX_BYTES` guards before it reaches the engine.+ **Two notes for plugin authors:** a plugin that blocks broadly will now also block status posts,+ where it previously had no visibility into them; and the gate `input` for a status post is **not**+ a send DTO — it carries no `chatId`, but `{ text, options }` or `{ media: { mimetype, data }, options }`.+ A handler that reads `input.chatId` unconditionally should branch on `source` or `type` first.++### Fixed+- **`forEveryone: false` on message delete is honoured again.** `POST /api/sessions/:sessionId/messages/delete`+ defaults `forEveryone` to `true`, so sending it at all means "delete only for me" — but a request+ that carried the value as a string (any form-encoded body, since that parser produces only string+ scalars) had it read as `true`, retracting the message from the recipient's device instead of+ hiding it locally. That is not reversible, and the recipient sees a "message deleted" placeholder.+ The field now accepts a real boolean or the exact strings `"true"`/`"false"`; **any other spelling+ — `1`, `0`, `yes`, `no` — is now rejected with `400` instead of being read as `true`.** JSON+ clients and all five SDKs send real booleans and are unaffected. `allowMultipleAnswers` on poll+ send is read the same way, which is what its validation always claimed to do.++- **Every boolean and numeric request field is now read strictly, and a test keeps it that way.**+ The same coercion applied to every such field: a boolean took any non-empty string as `true`, and+ a numeric field took a blank value as `0`. Fourteen more fields are covered — `active` and+ `retryCount` on webhooks (a blank `retryCount` silently meant "no retries"), `enabled` on+ integration instances, `ptt` on audio and bulk sends, `randomizeDelay` and `stopOnError` on bulk+ batches, `latitude`/`longitude` on location sends (a blank pair became the valid coordinates+ `0, 0`), `dateFrom`/`dateTo`/`offset` on search, and `font` on text status. Values that were+ already correct still work — a numeric field still accepts `"5"`, and a boolean still accepts+ `"true"`/`"false"` — so only input that was previously being guessed at is now refused with `400`.+ A drift test walks class-validator's registry and fails the build if any boolean or numeric+ request field, including one in a class that is never exported, accepts a value the pipe would+ otherwise coerce. The published OpenAPI schema is unchanged.- Running more than one session no longer corrupts the Chromium launch flags of everysession started after the first. The whatsapp-web.js adapter appended its per-session@@ -93,6 +121,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0depends on `[open]` alone, so focus is applied once when the dialog opens and staysput across parent re-renders. Reported in #837, fixed in #838.+### Security+- **Resolved every known advisory in the dependency tree (17 → 0, including one critical).** The+ critical one was a set of path-traversal and symlink issues in `node-tar`, reached only through+ `sqlite3@5` → `node-gyp` → `tar`. `sqlite3` moves to `6.0.1`, which drops the `node-gyp`+ dependency entirely in favour of `prebuild-install` and pulls a patched `tar@7`; `typeorm` moves+ to `0.3.31`, the first release declaring `sqlite3@^6` as a supported peer. `shell-quote` (reached+ through the `concurrently` dev dependency, and with no upstream fix available on any release+ line) is pinned forward with an `overrides` entry.++ The bundled SQLite build advances to 3.52.0. Migrations, the FTS5 full-text search tables, both+ database connections and a full boot were verified against the new driver.+## [0.10.2] - 2026-07-20### Addeddiff --git a/openapi.json b/openapi.jsonindex db7c3a45f..3db982468 100644--- a/openapi.json+++ b/openapi.json@@ -2052,7 +2052,10 @@}},"400": {- "description": "Session not active or invalid request"+ "description": "Session not active, invalid request, or the send was blocked by a plugin"+ },+ "403": {+ "description": "The message was not sent by this account, or the engine refused the edit"},"404": {"description": "Message not found"@@ -3066,6 +3069,9 @@"responses": {"200": {"description": "Joined the group"+ },+ "400": {+ "description": "Invalid or expired invite code, or session is not started"}},"summary": "Join a group via invite code",@@ -3147,7 +3153,13 @@"description": "Group settings updated"},"400": {- "description": "No setting provided"+ "description": "No setting provided, or a value is not a boolean"+ },+ "403": {+ "description": "The engine refused the change (the account is not a group admin)"+ },+ "404": {+ "description": "Group not found"},"501": {"description": "The active engine does not support a requested setting"@@ -3585,6 +3597,12 @@"responses": {"200": {"description": "Profile name updated"+ },+ "400": {+ "description": "Session is not started"+ },+ "403": {+ "description": "The engine refused the name change"}},"summary": "Set the account display name",@@ -3620,6 +3638,9 @@"responses": {"200": {"description": "Profile status updated"+ },+ "400": {+ "description": "Session is not started"}},"summary": "Set the account about/status text",@@ -3657,7 +3678,13 @@"description": "Profile picture updated"},"400": {- "description": "Neither url nor base64 provided, or base64 without mimetype"+ "description": "Neither url nor base64 provided, base64 without mimetype, or session is not started"+ },+ "403": {+ "description": "The engine refused the picture change"+ },+ "413": {+ "description": "Decoded base64 image exceeds the configured media cap"}},"summary": "Set the account profile picture (URL or base64 image)",@@ -4229,6 +4256,9 @@"responses": {"201": {"description": "Text status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience."+ },+ "400": {+ "description": "Invalid request, or the post was blocked by a plugin."}},"summary": "Post a text status",@@ -4264,6 +4294,9 @@"201": {"description": "Image status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience."},+ "400": {+ "description": "Neither url nor base64 provided, or the post was blocked by a plugin."+ },"413": {"description": "Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES."}@@ -4301,6 +4334,9 @@"201": {"description": "Video status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience."},+ "400": {+ "description": "Neither url nor base64 provided, or the post was blocked by a plugin."+ },"413": {"description": "Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES."}diff --git a/src/common/utils/dto-strict-coercion.spec.ts b/src/common/utils/dto-strict-coercion.spec.tsnew file mode 100644index 000000000..3dcb70381--- /dev/null+++ b/src/common/utils/dto-strict-coercion.spec.ts@@ -0,0 +1,120 @@+import 'reflect-metadata';+import { getMetadataStorage, validate } from 'class-validator';+import { plainToInstance } from 'class-transformer';+import { readdirSync, statSync } from 'fs';+import { join } from 'path';++/**+ * Drift gate for the input-coercion contract.+ *+ * The global ValidationPipe runs with `transformOptions.enableImplicitConversion: true`+ * (`src/config/app-validation.ts`). That is deliberate — it lets a client send `"5"` for a numeric+ * field, which form-encoded bodies and several HTTP clients do by default. But it also means+ * class-transformer rewrites the value BEFORE any `@Is*` validator sees it, and two of its+ * conversions destroy information rather than preserving it:+ *+ * Boolean — every non-empty string becomes `true`, so `"false"`, `"no"` and `"0"` all arrive as+ * `true` and `@IsBoolean()` can never reject them.+ * Number — `Number('')` and `Number(' ')` are `0`, so a blank field arrives as a real zero+ * and `@IsInt()`/`@IsNumber()` accept it.+ *+ * Both fail toward the more permissive value, which is how a `forEveryone=false` delete became a+ * delete-for-everyone. `ToStrictBoolean`/`ToStrictNumber` (`./strict-boolean`) restore the+ * rejection while keeping the useful half of the conversion.+ *+ * This spec asserts the BEHAVIOUR rather than the presence of a decorator, so any future mechanism+ * that produces the same guarantee also satisfies it. Every boolean and numeric property that+ * carries validation metadata is covered — including classes that are never exported, because+ * discovery walks class-validator's own registry rather than module exports.+ */++const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };+const PIPE_VALIDATOR_OPTS = { whitelist: true, forbidNonWhitelisted: true };++/** The value each type is probed with, and why it must be refused. */+const PROBES: Record<string, { value: string; reason: string }> = {+ Boolean: { value: 'yes', reason: 'implicit conversion turns any non-empty string into true' },+ Number: { value: '', reason: 'Number("") is 0, so a blank field becomes a real zero' },+};++function dtoFiles(dir: string, out: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ const path = join(dir, entry);+ if (statSync(path).isDirectory()) dtoFiles(path, out);+ else if (path.endsWith('.dto.ts') && !path.endsWith('.spec.ts')) out.push(path);+ }+ return out;+}++// Importing every DTO module registers its decorators. Classes only reach the registry once their+// module has been loaded, so this has to happen before the registry is read.+const SRC = join(__dirname, '..', '..');+dtoFiles(SRC).forEach(file => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-call+ require(file);+});++interface ValidatedClass {+ new (...args: never[]): object;+ name: string;+ prototype: object;+}++function registeredClasses(): ValidatedClass[] {+ const storage = getMetadataStorage() as unknown as { validationMetadatas?: Map<unknown, unknown> };+ const registry = storage.validationMetadatas;+ if (!(registry instanceof Map)) {+ // The internal shape changed. Fail loudly — a silently empty scan would report "no drift".+ throw new Error('class-validator metadata registry is not the expected Map; update this spec');+ }+ return [...registry.keys()].filter((k): k is ValidatedClass => typeof k === 'function');+}++function coercibleProps(cls: ValidatedClass): Array<{ prop: string; type: string }> {+ const metas = getMetadataStorage().getTargetValidationMetadatas(cls, cls.name, true, false);+ const props = [...new Set(metas.map(m => m.propertyName))];+ return props+ .map(prop => {+ const declared = Reflect.getMetadata('design:type', cls.prototype, prop) as { name?: string } | undefined;+ return { prop, type: declared?.name ?? '' };+ })+ .filter(({ type }) => type in PROBES);+}++describe('DTO input-coercion drift gate', () => {+ const classes = registeredClasses();+ const targets = classes.flatMap(cls => coercibleProps(cls).map(p => ({ cls, ...p })));++ // Guard the DISCOVERY, not just the assertions. A scan that silently finds nothing would report a+ // clean result forever; these pin the mechanism against a known-positive of each kind.+ it('discovers the DTO registry, including classes that are never exported', () => {+ const names = classes.map(c => c.name);+ expect(names).toContain('DeleteMessageDto'); // exported, top-level+ expect(names).toContain('BulkMessageOptionsDto'); // NOT exported — reached only via the registry+ expect(names.length).toBeGreaterThanOrEqual(40);+ });++ it('finds both a boolean and a numeric property to check', () => {+ expect(targets.some(t => t.type === 'Boolean')).toBe(true);+ expect(targets.some(t => t.type === 'Number')).toBe(true);+ expect(targets.length).toBeGreaterThanOrEqual(15);+ });++ it.each(targets.map(t => [`${t.cls.name}.${t.prop}`, t] as const))(+ '%s refuses a value the pipe would otherwise coerce',+ async (_label, target) => {+ const { value, reason } = PROBES[target.type];+ const instance = plainToInstance(target.cls, { [target.prop]: value }, PIPE_TRANSFORM_OPTS);+ const errors = await validate(instance, PIPE_VALIDATOR_OPTS);++ // Only this property's verdict matters — other properties may be absent and report their own+ // errors, which is irrelevant here.+ const refused = errors.some(e => e.property === target.prop);+ expect(+ refused ||+ `${target.cls.name}.${target.prop} accepted ${JSON.stringify(value)} — ${reason}. ` ++ `Add @ToStrict${target.type}() from common/utils/strict-boolean.`,+ ).toBe(true);+ },+ );+});diff --git a/src/common/utils/strict-boolean.spec.ts b/src/common/utils/strict-boolean.spec.tsnew file mode 100644index 000000000..75e2c7ae9--- /dev/null+++ b/src/common/utils/strict-boolean.spec.ts@@ -0,0 +1,123 @@+import 'reflect-metadata';+import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { IsBoolean, ValidateIf } from 'class-validator';+import { IsInt } from 'class-validator';+import { ToStrictBoolean, ToStrictNumber } from './strict-boolean';++// Mirrors the real pipe: whitelist + forbidNonWhitelisted from src/main.ts, and the+// enableImplicitConversion transform option from src/config/app-validation.ts. Leaving the+// transform option out here is what previously made a DTO spec pass while production accepted+// the opposite value.+const PIPE_VALIDATOR_OPTS = { whitelist: true, forbidNonWhitelisted: true };+const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };++class Subject {+ @ToStrictBoolean()+ @ValidateIf((o: Subject) => o.flag !== undefined)+ @IsBoolean()+ flag?: boolean;+}++class Unguarded {+ @ValidateIf((o: Unguarded) => o.flag !== undefined)+ @IsBoolean()+ flag?: boolean;+}++async function run<T extends object>(cls: new () => T, payload: unknown) {+ const instance = plainToInstance(cls, payload as object, PIPE_TRANSFORM_OPTS);+ const errors = await validate(instance, PIPE_VALIDATOR_OPTS);+ return { instance, errors };+}++describe('ToStrictBoolean', () => {+ it('preserves real booleans', async () => {+ for (const value of [true, false]) {+ const { instance, errors } = await run(Subject, { flag: value });+ expect(instance.flag).toBe(value);+ expect(errors).toHaveLength(0);+ }+ });++ it('maps the canonical string spellings a form-encoded body produces', async () => {+ const asFalse = await run(Subject, { flag: 'false' });+ expect(asFalse.instance.flag).toBe(false);+ expect(asFalse.errors).toHaveLength(0);++ const asTrue = await run(Subject, { flag: 'true' });+ expect(asTrue.instance.flag).toBe(true);+ expect(asTrue.errors).toHaveLength(0);+ });++ it('rejects ambiguous spellings instead of guessing', async () => {+ for (const value of ['yes', 'no', '0', '1', 'FALSE', '']) {+ const { errors } = await run(Subject, { flag: value });+ expect(errors.length).toBeGreaterThan(0);+ }+ });++ it('leaves an absent property absent', async () => {+ const { instance, errors } = await run(Subject, {});+ expect(instance.flag).toBeUndefined();+ expect(errors).toHaveLength(0);+ });++ // Characterizes the behaviour the decorator exists to prevent. If this ever stops failing,+ // enableImplicitConversion was turned off and the decorator can be reconsidered.+ it('documents the unguarded behaviour it replaces: every non-empty string becomes true', async () => {+ for (const value of ['false', 'no', '0']) {+ const { instance, errors } = await run(Unguarded, { flag: value });+ expect(instance.flag).toBe(true);+ expect(errors).toHaveLength(0);+ }+ });+});++class NumberSubject {+ @ToStrictNumber()+ @ValidateIf((o: NumberSubject) => o.count !== undefined)+ @IsInt()+ count?: number;+}++class UnguardedNumber {+ @ValidateIf((o: UnguardedNumber) => o.count !== undefined)+ @IsInt()+ count?: number;+}++describe('ToStrictNumber', () => {+ it('preserves real numbers and converts fully-numeric strings', async () => {+ for (const [input, expected] of [+ [7, 7],+ [0, 0],+ ['86400', 86400],+ ['0', 0],+ ] as const) {+ const { instance, errors } = await run(NumberSubject, { count: input });+ expect(instance.count).toBe(expected);+ expect(errors).toHaveLength(0);+ }+ });++ it('rejects blank and non-numeric strings instead of reading them as 0', async () => {+ for (const value of ['', ' ', 'abc', '1abc']) {+ const { errors } = await run(NumberSubject, { count: value });+ expect(errors.length).toBeGreaterThan(0);+ }+ });++ it('leaves an absent property absent', async () => {+ const { instance, errors } = await run(NumberSubject, {});+ expect(instance.count).toBeUndefined();+ expect(errors).toHaveLength(0);+ });++ // The behaviour the decorator exists to prevent: a blank form field arriving as a valid zero.+ it('documents the unguarded behaviour it replaces: a blank string becomes 0', async () => {+ const { instance, errors } = await run(UnguardedNumber, { count: '' });+ expect(instance.count).toBe(0);+ expect(errors).toHaveLength(0);+ });+});diff --git a/src/common/utils/strict-boolean.ts b/src/common/utils/strict-boolean.tsnew file mode 100644index 000000000..59ae17a54--- /dev/null+++ b/src/common/utils/strict-boolean.ts@@ -0,0 +1,56 @@+import { Transform, TransformFnParams } from 'class-transformer';++/**+ * Accept a boolean only when the caller spelled one unambiguously, and leave anything else+ * untouched so `@IsBoolean()` rejects it.+ *+ * The global `ValidationPipe` runs with `transformOptions.enableImplicitConversion: true`+ * (`src/config/app-validation.ts`). For a `boolean`-typed property that makes class-transformer+ * cast *any* non-empty string to `true` — `'false'`, `'0'` and `'no'` all become `true` — and it+ * happens before `@IsBoolean()` ever runs, so the validator can never reject it. Requests reach a+ * DTO as strings whenever the body arrives through the global `express.urlencoded` parser+ * (`src/main.ts`), whose scalars are always strings.+ *+ * The callback deliberately reads `obj[key]` (the untouched plain source) instead of `value`:+ * implicit conversion has already run by the time a `@Transform` callback is invoked, so `value`+ * is the coerced `true` and the caller's original spelling is only still recoverable from `obj`.+ *+ * Only exact `'true'` / `'false'` are mapped. Anything else keeps its original value and fails+ * validation — for a permission flag, an ambiguous spelling is safer refused than guessed.+ *+ * Because it reads `obj` and never `value`, it does NOT compose: class-transformer threads each+ * `@Transform` result into the next, and this one discards whatever a previously-registered+ * transform produced. Do not stack another `@Transform` on a property that uses it.+ */+export function coerceStrictBoolean({ obj, key }: Pick<TransformFnParams, 'obj' | 'key'>): unknown {+ const raw = (obj as Record<string, unknown> | undefined)?.[key];+ if (typeof raw === 'boolean') return raw;+ if (raw === 'true') return true;+ if (raw === 'false') return false;+ return raw;+}++/** Property decorator form of {@link coerceStrictBoolean}. Pair it with `@IsBoolean()`. */+export const ToStrictBoolean = (): PropertyDecorator => Transform(coerceStrictBoolean);++/**+ * The numeric counterpart, for the same reason and with the same `obj[key]` trick.+ *+ * Implicit conversion applies `Number(value)` to a `number`-typed property, and `Number('')` and+ * `Number(' ')` are both `0` — so an empty form field arrives as a real, valid zero rather than+ * being rejected as missing. On a field where `0` is itself meaningful (a disappearing-message+ * timer, where `0` means "off") that silently performs an action the caller never asked for.+ *+ * Only a genuine number or a string that is entirely a finite number is converted. Everything else+ * keeps its original value and fails `@IsInt()`/`@IsNumber()`.+ */+export function coerceStrictNumber({ obj, key }: Pick<TransformFnParams, 'obj' | 'key'>): unknown {+ const raw = (obj as Record<string, unknown> | undefined)?.[key];+ if (typeof raw === 'number') return raw;+ if (typeof raw !== 'string' || raw.trim() === '') return raw;+ const parsed = Number(raw);+ return Number.isFinite(parsed) ? parsed : raw;+}++/** Property decorator form of {@link coerceStrictNumber}. Pair it with `@IsInt()` / `@IsNumber()`. */+export const ToStrictNumber = (): PropertyDecorator => Transform(coerceStrictNumber);diff --git a/src/core/hooks/index.ts b/src/core/hooks/index.tsindex 8cff5554a..4db3a4a15 100644--- a/src/core/hooks/index.ts+++ b/src/core/hooks/index.ts@@ -1,3 +1,4 @@export * from './hook.interfaces';export * from './hook-manager.service';export * from './hooks.module';+export * from './sending-gate';diff --git a/src/core/hooks/sending-gate.ts b/src/core/hooks/sending-gate.tsnew file mode 100644index 000000000..0e7203269--- /dev/null+++ b/src/core/hooks/sending-gate.ts@@ -0,0 +1,38 @@+import { BadRequestException } from '@nestjs/common';+import { HookManager } from './hook-manager.service';++/**+ * Run the pre-send `message:sending` plugin gate for one piece of outbound content and return the+ * (possibly plugin-modified) input, or throw `BadRequestException` when a plugin blocked it.+ *+ * Lives here rather than on a service so callers in different modules share one implementation.+ * A second copy of a moderation chokepoint is a chokepoint that will eventually disagree with itself.+ *+ * Current callers: `MessageService` (all senders + edit) and `StatusService` (the three posts).+ * `BulkMessageService` still runs its own inlined copy — it has to flag a plugin block separately+ * from a delivery failure so the per-item `message:failed` hook is skipped, which this signature+ * cannot express. If you change the gate's semantics here, change it there too+ * (`bulk-message.service.ts`, the `blockedByPlugin` branch).+ *+ * `source` names the caller in the hook context so a plugin can tell a chat send from a status+ * post without inspecting the payload shape — which matters because the shapes differ: a+ * MessageService `input` is a send DTO carrying `chatId`, a StatusService `input` is not.+ */+export async function applySendingGate<T extends object>(+ hookManager: HookManager,+ sessionId: string,+ type: string,+ input: T,+ source: string,+): Promise<T> {+ const { continue: shouldContinue, data: hookData } = await hookManager.execute(+ 'message:sending',+ { sessionId, input, type },+ { sessionId, source },+ );+ if (!shouldContinue) {+ throw new BadRequestException('Message sending blocked by plugin');+ }+ // Use the potentially plugin-modified input.+ return (hookData as { input: T }).input;+}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 03cdae518..be20b8025 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2771,6 +2771,73 @@ describe('BaileysAdapter call events (call offer) + rejectCall', () => {expect(firstCallEvent(onCall).from).toBe('[email protected]');});+ // Baileys folds both the `offer` and `offer_notice` wire tags onto status 'offer' with the same+ // call-id, so one ringing call can reach the handler more than once.+ it('emits once per call id even when the same offer arrives repeatedly', async () => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer()]);+ fakeSock.fire('call', [offer()]);+ fakeSock.fire('call', [offer()]);++ expect(onCall).toHaveBeenCalledTimes(1);+ });++ it('deduplicates repeats delivered in a single batch', async () => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer(), offer()]);++ expect(onCall).toHaveBeenCalledTimes(1);+ });++ it('still emits for a genuinely different call id', async () => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer({ id: 'CALL1' }), offer({ id: 'CALL2' })]);++ expect(onCall).toHaveBeenCalledTimes(2);+ });++ it('a deduplicated repeat does not evict the live call', async () => {+ const { adapter } = await readyWithCallEvents();++ fakeSock.fire('call', [offer()]);+ fakeSock.fire('call', [offer()]);++ await expect(adapter.rejectCall('CALL1')).resolves.toBeUndefined();+ });++ // Discriminating on the REFRESH specifically: the second offer lands 90s in, so the entry is only+ // expired at 150s if its expiry was never extended. LIVE_CALL_TTL_MS is 120s.+ it('a repeat extends the rejectable window from the latest offer, not the first', async () => {+ const { adapter } = await readyWithCallEvents();+ jest.useFakeTimers();+ try {+ fakeSock.fire('call', [offer()]);+ jest.advanceTimersByTime(90_000);+ fakeSock.fire('call', [offer()]);+ jest.advanceTimersByTime(60_000); // 150s after the first offer, 60s after the second++ await expect(adapter.rejectCall('CALL1')).resolves.toBeUndefined();+ } finally {+ jest.useRealTimers();+ }+ });++ it('a call still expires when no repeat arrives', async () => {+ const { adapter } = await readyWithCallEvents();+ jest.useFakeTimers();+ try {+ fakeSock.fire('call', [offer()]);+ jest.advanceTimersByTime(150_000);++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ } finally {+ jest.useRealTimers();+ }+ });+it.each(['ringing', 'preaccept', 'transport', 'relaylatency', 'timeout', 'reject', 'accept', 'terminate'])('skips status %s (lifecycle update, not a new incoming call)',async status => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 83fa53272..2d9967553 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -900,7 +900,11 @@ export class BaileysAdapter implements IWhatsAppEngine {let jid: string | undefined;try {jid = await this.sock!.groupAcceptInvite(inviteCode);- } catch {+ } catch (error) {+ // A refused invite and a socket/protocol failure both land here, and only the first is the+ // caller's fault. The client-facing answer stays 400, but the original error is kept in the+ // log: without it an upstream change turns every join into an unexplained 400.+ this.logger.warn('Failed to accept group invite', { error: String(error) });jid = undefined;}if (!jid) {@@ -1502,7 +1506,13 @@ export class BaileysAdapter implements IWhatsAppEngine {continue;}}- this.cacheLiveCall(call.id, call.from);+ // Baileys maps both the `offer` and `offer_notice` wire tags onto status 'offer' carrying the+ // same call-id, so a single call can reach this loop more than once. Cache first and emit+ // only for an id not already live, otherwise one call surfaces as several `call.received`+ // events.+ if (!this.cacheLiveCall(call.id, call.from)) {+ continue;+ }const payload: IncomingCallEvent = {callId: call.id,// callerPn is the phone-dialect twin of a lid caller: prefer it so the neutral caller id@@ -1526,15 +1536,21 @@ export class BaileysAdapter implements IWhatsAppEngine {* call drops already-expired entries, so a session that receives calls but never rejects them* can't grow the map without bound; an entry that never sees another call is tiny and is dropped* on teardown (disconnect/logout/destroy) or at the next call. No per-entry timer to clean up.+ *+ * Returns true when `callId` was not already ringing, which is what makes `call.received` fire+ * once per call rather than once per upstream offer tag. A repeat offer still refreshes the+ * entry, so a long-ringing call stays rejectable for a full TTL from the most recent signal.*/- private cacheLiveCall(callId: string, callFrom: string): void {+ private cacheLiveCall(callId: string, callFrom: string): boolean {const now = Date.now();for (const [id, entry] of this.liveCalls) {if (entry.expiresAt <= now) {this.liveCalls.delete(id);}}+ const isNewCall = !this.liveCalls.has(callId);this.liveCalls.set(callId, { callFrom, expiresAt: now + BaileysAdapter.LIVE_CALL_TTL_MS });+ return isNewCall;}/**diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 3f63558b4..fcff43ef6 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -2097,6 +2097,72 @@ describe('WhatsAppWebJsAdapter call event + rejectCall', () => {expect(onCall).not.toHaveBeenCalled();});+ // The upstream handler is driven by a patched internalCallMap.set(), which fires on every write+ // to that map rather than only on insertion, so the same ringing call reaches the adapter more+ // than once.+ it('emits once per call id even when the same call is signalled repeatedly', () => {+ const { onCall, client } = wireCallHandler();++ client.emit('call', liveCall());+ client.emit('call', liveCall());+ client.emit('call', liveCall());++ expect(onCall).toHaveBeenCalledTimes(1);+ });++ it('still emits for a genuinely different call id', () => {+ const { onCall, client } = wireCallHandler();++ client.emit('call', liveCall({ id: 'CALL1' }));+ client.emit('call', liveCall({ id: 'CALL2' }));++ expect(onCall).toHaveBeenCalledTimes(2);+ });++ it('a deduplicated repeat does not evict the live call', async () => {+ const { adapter, client } = wireCallHandler();+ const call = liveCall();++ client.emit('call', call);+ client.emit('call', call);++ await expect(adapter.rejectCall('CALL1')).resolves.toBeUndefined();+ expect(call.reject).toHaveBeenCalledTimes(1);+ });++ // Discriminating on the REFRESH specifically: the second signal lands 90s in, so the entry is+ // only expired at 150s if its expiry was never extended. LIVE_CALL_TTL_MS is 120s.+ it('a repeat extends the rejectable window from the latest signal, not the first', async () => {+ jest.useFakeTimers();+ try {+ const { adapter, client } = wireCallHandler();+ const call = liveCall();++ client.emit('call', call);+ jest.advanceTimersByTime(90_000);+ client.emit('call', call);+ jest.advanceTimersByTime(60_000); // 150s after the first signal, 60s after the second++ await expect(adapter.rejectCall('CALL1')).resolves.toBeUndefined();+ } finally {+ jest.useRealTimers();+ }+ });++ it('a call still expires when no repeat arrives', async () => {+ jest.useFakeTimers();+ try {+ const { adapter, client } = wireCallHandler();++ client.emit('call', liveCall());+ jest.advanceTimersByTime(150_000);++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ } finally {+ jest.useRealTimers();+ }+ });+it.each([{ id: '' }, { id: undefined }, { from: '' }, { from: undefined }, null])('drops a malformed call (%o) — nothing emitted, nothing cached',async malformed => {@@ -3272,6 +3338,30 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);});+ // joinGroupViaInviteCode answers 400 for every acceptInvite failure, because a refused invite is+ // indistinguishable from a page error at that call site. The 400 stays, but a dead page still has+ // to reach the liveness path rather than being reported purely as the caller's bad invite code.+ it('detects a transport error during joinGroupViaInviteCode (still a 400 to the caller)', async () => {+ const acceptInvite = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));+ const { adapter, onDisconnected } = readyAdapter({ acceptInvite });++ await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBeInstanceOf(InvalidInviteCodeError);++ expect(onDisconnected).toHaveBeenCalledTimes(1);+ expect(onDisconnected).toHaveBeenCalledWith('Page transport error during joinGroupViaInviteCode');+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ });++ it('does not report an ordinary refused invite as a disconnect', async () => {+ const acceptInvite = jest.fn().mockRejectedValue(new Error('Evaluation failed: invite revoked'));+ const { adapter, onDisconnected } = readyAdapter({ acceptInvite });++ await expect(adapter.joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(InvalidInviteCodeError);++ expect(onDisconnected).not.toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ });+it('reports nothing when the failure happens during an intentional teardown', async () => {const sendMessage = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));const { adapter, onDisconnected } = readyAdapter({ sendMessage });diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex a38e8f034..9a3b2b905 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -909,7 +909,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (call.fromMe) {return;}- this.cacheLiveCall(call.id, call);+ // whatsapp-web.js fires this handler from a patched `internalCallMap.set()`, which runs on+ // every write to that map — including updates to a call already ringing — so the same call id+ // can arrive more than once. Cache first and emit only for an id not already live, otherwise+ // one call surfaces as several `call.received` events.+ if (!this.cacheLiveCall(call.id, call)) {+ return;+ }const payload: IncomingCallEvent = {callId: call.id,from: call.from ?? '',@@ -931,15 +937,21 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin* already-expired entries, so a session that receives calls but never rejects them can't grow* the map without bound; an entry that never sees another call is tiny and is dropped on* teardown (beginClientTeardown) or at the next call. No per-entry timer to clean up.+ *+ * Returns true when `callId` was not already ringing, which is what makes `call.received` fire+ * once per call rather than once per upstream map write. A repeat write still refreshes the+ * entry, so a long-ringing call stays rejectable for a full TTL from the most recent signal.*/- private cacheLiveCall(callId: string, call: Call): void {+ private cacheLiveCall(callId: string, call: Call): boolean {const now = Date.now();for (const [id, entry] of this.liveCalls) {if (entry.expiresAt <= now) {this.liveCalls.delete(id);}}+ const isNewCall = !this.liveCalls.has(callId);this.liveCalls.set(callId, { call, expiresAt: now + WhatsAppWebJsAdapter.LIVE_CALL_TTL_MS });+ return isNewCall;}/**@@ -2280,7 +2292,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginlet groupId: string | undefined;try {groupId = await this.client!.acceptInvite(inviteCode);- } catch {+ } catch (error) {+ // A refused invite and a broken page both land here, and only the first is the caller's+ // fault. Surface the transport case to the liveness path and keep the original error in the+ // log: without it an upstream rename turns every join into an unexplained 400.+ this.reportIfPageTransportError(error, 'joinGroupViaInviteCode');+ this.logger.warn(`Failed to accept group invite: ${String(error)}`);groupId = undefined;}if (!groupId) {diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.tsindex 66313151c..db17d0bde 100644--- a/src/modules/group/dto/group.dto.spec.ts+++ b/src/modules/group/dto/group.dto.spec.ts@@ -10,11 +10,19 @@ import {GroupSettingsDto,} from './group.dto';-// Mirror the global ValidationPipe options (src/main.ts): whitelist + forbidNonWhitelisted.+// Mirror the global ValidationPipe: whitelist + forbidNonWhitelisted from src/main.ts, AND the+// enableImplicitConversion transform option from src/config/app-validation.ts. The transform+// option has to be applied here too — without it a spec exercises a stricter pipe than the one+// that actually runs, so a payload this file rejects can still be accepted in production.const PIPE_OPTS = { whitelist: true, forbidNonWhitelisted: true };+const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };function errorsFor<T extends object>(cls: new () => T, payload: unknown): Promise<ValidationError[]> {- return validate(plainToInstance(cls, payload as object), PIPE_OPTS);+ return validate(plainToInstance(cls, payload as object, PIPE_TRANSFORM_OPTS), PIPE_OPTS);+}++function instanceFor<T extends object>(cls: new () => T, payload: unknown): T {+ return plainToInstance(cls, payload as object, PIPE_TRANSFORM_OPTS);}describe('group DTO validation', () => {@@ -82,4 +90,35 @@ describe('group DTO validation', () => {const errors = await errorsFor(GroupSettingsDto, { announce: true, hacker: true });expect(errors.some(e => e.property === 'hacker')).toBe(true);});++ // A form-encoded body reaches the DTO as string scalars, and the pipe converts implicitly. These+ // assert the resulting VALUE, not just the error count: the failure mode being pinned is+ // `announce=false` arriving as `announce: true` and silently restricting the group.+ it('GroupSettingsDto reads a form-encoded "false" as false, not true', () => {+ expect(instanceFor(GroupSettingsDto, { announce: 'false' }).announce).toBe(false);+ expect(instanceFor(GroupSettingsDto, { locked: 'false' }).locked).toBe(false);+ expect(instanceFor(GroupSettingsDto, { announce: 'true' }).announce).toBe(true);+ expect(instanceFor(GroupSettingsDto, { locked: 'true' }).locked).toBe(true);+ });++ it('GroupSettingsDto rejects ambiguous boolean spellings rather than defaulting them to true', async () => {+ for (const value of ['yes', 'no', '0', '1', 'FALSE']) {+ expect((await errorsFor(GroupSettingsDto, { announce: value })).length).toBeGreaterThan(0);+ expect((await errorsFor(GroupSettingsDto, { locked: value })).length).toBeGreaterThan(0);+ }+ });++ // Same class of hole as the booleans above: Number('') and Number(' ') are both 0, and 0 is a+ // meaningful value here (it turns disappearing messages OFF), so an empty form field must not be+ // read as a deliberate request to disable the timer.+ it('GroupSettingsDto rejects an empty ephemeralSeconds instead of reading it as 0', async () => {+ for (const value of ['', ' ']) {+ expect((await errorsFor(GroupSettingsDto, { ephemeralSeconds: value })).length).toBeGreaterThan(0);+ }+ });++ it('GroupSettingsDto still accepts a numeric-string ephemeralSeconds from a form body', () => {+ expect(instanceFor(GroupSettingsDto, { ephemeralSeconds: '86400' }).ephemeralSeconds).toBe(86400);+ expect(instanceFor(GroupSettingsDto, { ephemeralSeconds: '0' }).ephemeralSeconds).toBe(0);+ });});diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex 3de22c748..5e2a8f76a 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -10,6 +10,7 @@ import {Min,ValidateIf,} from 'class-validator';+import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';export class CreateGroupDto {@ApiProperty({ description: 'Group subject/name', maxLength: 100 })@@ -67,11 +68,13 @@ export class JoinGroupDto {*/export class GroupSettingsDto {@ApiPropertyOptional({ description: 'Only admins can send messages (announce group)' })+ @ToStrictBoolean()@ValidateIf((o: GroupSettingsDto) => o.announce !== undefined)@IsBoolean()announce?: boolean;@ApiPropertyOptional({ description: 'Only admins can edit group info (locked group)' })+ @ToStrictBoolean()@ValidateIf((o: GroupSettingsDto) => o.locked !== undefined)@IsBoolean()locked?: boolean;@@ -81,6 +84,7 @@ export class GroupSettingsDto {'Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d)',minimum: 0,})+ @ToStrictNumber()@ValidateIf((o: GroupSettingsDto) => o.ephemeralSeconds !== undefined)@IsInt()@Min(0)diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex 83af1726a..97ec6b3b3 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -38,6 +38,7 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiBody({ type: JoinGroupDto })@ApiResponse({ status: 200, description: 'Joined the group' })+ @ApiResponse({ status: 400, description: 'Invalid or expired invite code, or session is not started' })async join(@Param('sessionId') sessionId: string, @Body() dto: JoinGroupDto) {const groupId = await this.groupService.joinGroupViaInviteCode(sessionId, dto.inviteCode);return { success: true, groupId };@@ -60,7 +61,9 @@ export class GroupController {@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiBody({ type: GroupSettingsDto })@ApiResponse({ status: 200, description: 'Group settings updated' })- @ApiResponse({ status: 400, description: 'No setting provided' })+ @ApiResponse({ status: 400, description: 'No setting provided, or a value is not a boolean' })+ @ApiResponse({ status: 403, description: 'The engine refused the change (the account is not a group admin)' })+ @ApiResponse({ status: 404, description: 'Group not found' })@ApiResponse({ status: 501, description: 'The active engine does not support a requested setting' })async updateSettings(@Param('sessionId') sessionId: string,diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.tsindex f0d9435fa..844145171 100644--- a/src/modules/integration/dto/instance.dto.ts+++ b/src/modules/integration/dto/instance.dto.ts@@ -1,6 +1,7 @@import { IsBoolean, IsNotEmpty, IsObject, IsOptional, IsString, Matches, MaxLength, MinLength } from 'class-validator';import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';import { IngressUrl } from '../ingress-url';+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';// Safe charset: also prevents an instanceId containing ':' (which would collide the P1 ordering key).const INSTANCE_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;@@ -63,6 +64,7 @@ export class UpdateInstanceDto {description: 'Whether the instance is enabled (ingress accepted, dispatch active).',example: true,})+ @ToStrictBoolean()@IsOptional()@IsBoolean()enabled?: boolean;diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.tsindex 5fc65f3b9..17a34f8ee 100644--- a/src/modules/message/dto/bulk-message.dto.ts+++ b/src/modules/message/dto/bulk-message.dto.ts@@ -14,6 +14,7 @@ import {ArrayMaxSize,} from 'class-validator';import { Type } from 'class-transformer';+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';class BulkMediaDto {@ApiPropertyOptional({ description: 'Media URL (http/https)' })@@ -37,6 +38,7 @@ class BulkMediaDto {filename?: string;@ApiPropertyOptional({ description: 'Audio only: send as a WhatsApp voice note (PTT)' })+ @ToStrictBoolean()@IsOptional()@IsBoolean()ptt?: boolean;@@ -112,11 +114,13 @@ class BulkMessageOptionsDto {delayBetweenMessages?: number;@ApiPropertyOptional({ description: 'Add random 0-2s to delay', default: true })+ @ToStrictBoolean()@IsOptional()@IsBoolean()randomizeDelay?: boolean;@ApiPropertyOptional({ description: 'Stop batch on first error', default: false })+ @ToStrictBoolean()@IsOptional()@IsBoolean()stopOnError?: boolean;diff --git a/src/modules/message/dto/message-actions.dto.spec.ts b/src/modules/message/dto/message-actions.dto.spec.tsindex a438601cd..670d52522 100644--- a/src/modules/message/dto/message-actions.dto.spec.ts+++ b/src/modules/message/dto/message-actions.dto.spec.ts@@ -14,8 +14,17 @@ import {* runtime validation). e2e is deferred (broken harness), so we validate the* decorators directly via class-validator.*/+// The transform option has to match src/config/app-validation.ts. Without it these specs exercise a+// stricter pipe than the one that actually runs, so a payload rejected here can still be accepted in+// production — which is exactly how a stringly-typed boolean stayed invisible.+const PIPE_TRANSFORM_OPTS = { enableImplicitConversion: true };+function errorsFor<T extends object>(cls: new () => T, obj: object): Promise<ValidationError[]> {- return validate(plainToInstance(cls, obj));+ return validate(plainToInstance(cls, obj, PIPE_TRANSFORM_OPTS));+}++function instanceFor<T extends object>(cls: new () => T, obj: object): T {+ return plainToInstance(cls, obj, PIPE_TRANSFORM_OPTS);}describe('message action DTOs', () => {@@ -88,6 +97,25 @@ describe('message action DTOs', () => {expect(await errorsFor(DeleteMessageDto, { chatId: '[email protected]', messageId: 'm1' })).toHaveLength(0);});+ // The service defaults an absent forEveryone to true, so `false` is the only reason to send the+ // field at all. Asserting the VALUE, not just the error count: a form-encoded "false" read as+ // `true` would retract the message from the recipient instead of hiding it locally, and that+ // cannot be undone.+ it('DeleteMessageDto: a form-encoded "false" stays false', () => {+ const base = { chatId: '[email protected]', messageId: 'm1' };+ expect(instanceFor(DeleteMessageDto, { ...base, forEveryone: 'false' }).forEveryone).toBe(false);+ expect(instanceFor(DeleteMessageDto, { ...base, forEveryone: 'true' }).forEveryone).toBe(true);+ expect(instanceFor(DeleteMessageDto, { ...base, forEveryone: false }).forEveryone).toBe(false);+ expect(instanceFor(DeleteMessageDto, { ...base, forEveryone: true }).forEveryone).toBe(true);+ });++ it('DeleteMessageDto: rejects an ambiguous forEveryone rather than defaulting it to true', async () => {+ for (const value of ['yes', 'no', '0', '1', 'FALSE']) {+ const errs = await errorsFor(DeleteMessageDto, { chatId: '[email protected]', messageId: 'm1', forEveryone: value });+ expect(errs.some(e => e.property === 'forEveryone')).toBe(true);+ }+ });+it('ForwardMessageDto: requires all three ids', async () => {const errs = await errorsFor(ForwardMessageDto, { fromChatId: '[email protected]' });expect(errs.some(e => e.property === 'toChatId')).toBe(true);diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex 505f9ad16..5c6fcc435 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -11,6 +11,7 @@ import {ArrayMaxSize,MaxLength,} from 'class-validator';+import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';/*** Validated DTOs for the message action endpoints. These replaced inline@@ -25,10 +26,12 @@ export class SendLocationDto {chatId: string;@ApiProperty({ example: -6.2088 })+ @ToStrictNumber()@IsLatitude()latitude: number;@ApiProperty({ example: 106.8456 })+ @ToStrictNumber()@IsLongitude()longitude: number;@@ -92,6 +95,10 @@ export class SendPollDto {options: string[];@ApiPropertyOptional({ description: 'Allow voters to pick several options (default single choice)' })+ // Read strictly for the same reason as DeleteMessageDto.forEveryone: without it the pipe's+ // implicit conversion turns any non-empty string into `true`, and this file's own spec has always+ // asserted that a non-boolean here is rejected.+ @ToStrictBoolean()@IsOptional()@IsBoolean()allowMultipleAnswers?: boolean;@@ -162,6 +169,11 @@ export class DeleteMessageDto {messageId: string;@ApiPropertyOptional({ description: 'Delete for everyone (default true)' })+ // The field's only purpose is to say "no, delete locally" — the default is already true+ // (message.service.ts). Under the pipe's implicit conversion a string `"false"` would become+ // boolean `true`, turning an explicit local-only delete into an irreversible retraction from the+ // recipient's device, so the value is read strictly rather than interpreted.+ @ToStrictBoolean()@IsOptional()@IsBoolean()forEveryone?: boolean;diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex cf8dfe245..64240d9ff 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -10,6 +10,7 @@ import {ArrayMaxSize,IsBoolean,} from 'class-validator';+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';const MENTIONS_DESCRIPTION ='WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';@@ -111,6 +112,7 @@ export class SendAudioMessageDto extends SendMediaMessageDto {'bytes for reliable playback; when the mimetype is omitted it defaults to that for voice notes. ' +'Expects a JSON boolean. Default false = plain audio file. Only valid on send-audio.',})+ @ToStrictBoolean()@IsOptional()@IsBoolean()ptt?: boolean;diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 6c0467abe..633d2152a 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -377,7 +377,11 @@ export class MessageController {})@ApiResponse({status: 400,- description: 'Session not active or invalid request',+ description: 'Session not active, invalid request, or the send was blocked by a plugin',+ })+ @ApiResponse({+ status: 403,+ description: 'The message was not sent by this account, or the engine refused the edit',})@ApiResponse({ status: 404, description: 'Message not found' })async edit(@Param('sessionId') sessionId: string, @Body() dto: EditMessageDto): Promise<MessageResponseDto> {diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 2a3888d41..4c5e8a5f1 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1032,6 +1032,41 @@ describe('MessageService', () => {).rejects.toBeInstanceOf(BadRequestException);expect(mockEngine.editMessage).not.toHaveBeenCalled();});++ // An edit replaces the text the recipient sees, so it belongs to the same moderation+ // chokepoint as every other sender rather than going out unseen by plugins.+ it('runs the message:sending gate tagged as an edit', async () => {+ await service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' });++ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'edit' }),+ expect.any(Object),+ );+ });++ it('lets a plugin block an edit before the engine is called', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });++ await expect(+ service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' }),+ ).rejects.toThrow('Message sending blocked by plugin');++ expect(mockEngine.editMessage).not.toHaveBeenCalled();+ expect(sessionService.recordOutboundMessageEdit).not.toHaveBeenCalled();+ });++ it('threads a plugin-rewritten edit body through to the engine and the stored row', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { input: { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'redacted' } },+ });++ await service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'secret' });++ expect(mockEngine.editMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', 'redacted');+ expect(sessionService.recordOutboundMessageEdit).toHaveBeenCalledWith('sess-1', 'wa-msg-1', 'redacted');+ });});/**diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex d2022b47a..42af7375c 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -9,7 +9,7 @@ import { SendTemplateMessageDto } from './dto/send-template.dto';import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';-import { HookManager } from '../../core/hooks';+import { HookManager, applySendingGate } from '../../core/hooks';import { TemplateService } from '../template/template.service';import { renderTemplate } from '../../common/utils/template-render';import { createLogger } from '../../common/services/logger.service';@@ -93,20 +93,12 @@ export class MessageService {/*** Run the pre-send `message:sending` plugin gate for one outbound message and return the* (possibly plugin-modified) input, or throw BadRequestException if a plugin blocked the send.- * Centralised so EVERY public sender — text, media, and extended (location/contact/poll/sticker/- * reply/forward) — passes through the same moderation chokepoint, instead of only `sendText`.+ * Centralised so EVERY public sender — text, media, extended (location/contact/poll/sticker/+ * reply/forward) and edit — passes through the same moderation chokepoint, instead of only+ * `sendText`. The implementation is shared with StatusService via core/hooks/sending-gate.*/- private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {- const { continue: shouldContinue, data: hookData } = await this.hookManager.execute(- 'message:sending',- { sessionId, input, type },- { sessionId, source: 'MessageService' },- );- if (!shouldContinue) {- throw new BadRequestException('Message sending blocked by plugin');- }- // Use the potentially plugin-modified input.- return (hookData as { input: T }).input;+ private applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {+ return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');}/**@@ -675,12 +667,16 @@ export class MessageService {dto: { chatId: string; messageId: string; body: string },): Promise<MessageResponseDto> {const engine = this.getEngine(sessionId);- const result = await engine.editMessage(dto.chatId, dto.messageId, dto.body);+ // An edit replaces the text the recipient sees, so it is content leaving the account and goes+ // through the same moderation chokepoint as every other sender. A plugin can rewrite `body`+ // here exactly as it can for a first send.+ const finalDto = await this.applySendingGate(sessionId, 'edit', dto);+ const result = await engine.editMessage(finalDto.chatId, finalDto.messageId, finalDto.body);// Best-effort: reflect the new body in the stored copy (mirrors deleteMessage's revoked flag),// serialized with the inbound edit/reaction writers through the session's per-message mutation// queue. A missing row must not fail the request — the engine edit already succeeded.- await this.sessionService.recordOutboundMessageEdit(sessionId, dto.messageId, dto.body);+ await this.sessionService.recordOutboundMessageEdit(sessionId, finalDto.messageId, finalDto.body);return { messageId: result.id, timestamp: result.timestamp };}diff --git a/src/modules/profile/profile.controller.ts b/src/modules/profile/profile.controller.tsindex a4ba70c7d..42e239f2a 100644--- a/src/modules/profile/profile.controller.ts+++ b/src/modules/profile/profile.controller.ts@@ -16,6 +16,8 @@ export class ProfileController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiBody({ type: SetProfileNameDto })@ApiResponse({ status: 200, description: 'Profile name updated' })+ @ApiResponse({ status: 400, description: 'Session is not started' })+ @ApiResponse({ status: 403, description: 'The engine refused the name change' })async setName(@Param('sessionId') sessionId: string, @Body() dto: SetProfileNameDto) {await this.profileService.setProfileName(sessionId, dto.name);return { success: true, message: 'Profile name updated' };@@ -27,6 +29,7 @@ export class ProfileController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiBody({ type: SetProfileStatusDto })@ApiResponse({ status: 200, description: 'Profile status updated' })+ @ApiResponse({ status: 400, description: 'Session is not started' })async setStatus(@Param('sessionId') sessionId: string, @Body() dto: SetProfileStatusDto) {await this.profileService.setProfileStatus(sessionId, dto.status);return { success: true, message: 'Profile status updated' };@@ -38,7 +41,12 @@ export class ProfileController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiBody({ type: SetProfilePictureDto })@ApiResponse({ status: 200, description: 'Profile picture updated' })- @ApiResponse({ status: 400, description: 'Neither url nor base64 provided, or base64 without mimetype' })+ @ApiResponse({+ status: 400,+ description: 'Neither url nor base64 provided, base64 without mimetype, or session is not started',+ })+ @ApiResponse({ status: 403, description: 'The engine refused the picture change' })+ @ApiResponse({ status: 413, description: 'Decoded base64 image exceeds the configured media cap' })async setPicture(@Param('sessionId') sessionId: string, @Body() dto: SetProfilePictureDto) {await this.profileService.setProfilePicture(sessionId, dto);return { success: true, message: 'Profile picture updated' };diff --git a/src/modules/search/dto/search-query.dto.ts b/src/modules/search/dto/search-query.dto.tsindex b1813d94d..ebd936a83 100644--- a/src/modules/search/dto/search-query.dto.ts+++ b/src/modules/search/dto/search-query.dto.ts@@ -3,6 +3,7 @@ import { IsString, IsNotEmpty, IsOptional, IsEnum, IsNumber, Min } from 'class-vimport { Type } from 'class-transformer';import { MessageDirection } from '../../message/entities/message.entity';import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';+import { ToStrictNumber } from '../../../common/utils/strict-boolean';/*** Request shape for GET /search. Numeric fields are coerced from query-string strings via@@ -45,12 +46,14 @@ export class SearchQueryDto {type?: MessageType;@ApiPropertyOptional({ description: 'Epoch-ms lower bound (inclusive)', type: Number })+ @ToStrictNumber()@IsOptional()@Type(() => Number)@IsNumber()dateFrom?: number;@ApiPropertyOptional({ description: 'Epoch-ms upper bound (inclusive)', type: Number })+ @ToStrictNumber()@IsOptional()@Type(() => Number)@IsNumber()@@ -65,6 +68,7 @@ export class SearchQueryDto {@ApiPropertyOptional({ description: 'Pagination offset', type: Number })@IsOptional()+ @ToStrictNumber()@Type(() => Number)@IsNumber()@Min(0)diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.tsindex 92fad8ad1..c400b8027 100644--- a/src/modules/status/dto/send-text-status.dto.ts+++ b/src/modules/status/dto/send-text-status.dto.ts@@ -11,6 +11,7 @@ import {ArrayMaxSize,} from 'class-validator';import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { ToStrictNumber } from '../../../common/utils/strict-boolean';export class SendTextStatusDto {@ApiProperty({ description: 'Status text body.', example: 'Out for delivery 📦', maxLength: 4096 })@@ -25,6 +26,7 @@ export class SendTextStatusDto {backgroundColor?: string;@ApiPropertyOptional({ description: 'Font family index (0–5).', example: 0, minimum: 0, maximum: 5 })+ @ToStrictNumber()@IsOptional()@IsInt()@Min(0)diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.tsindex d570652b6..9ad088158 100644--- a/src/modules/status/status.controller.ts+++ b/src/modules/status/status.controller.ts@@ -34,6 +34,7 @@ export class StatusController {'Text status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts ' +"to the account's status-privacy audience.",})+ @ApiResponse({ status: 400, description: 'Invalid request, or the post was blocked by a plugin.' })async sendTextStatus(@Param('sessionId') sessionId: string, @Body() dto: SendTextStatusDto) {return this.statusService.postTextStatus(sessionId, dto.text, {recipients: dto.recipients,@@ -51,6 +52,10 @@ export class StatusController {'Image status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts ' +"to the account's status-privacy audience.",})+ @ApiResponse({+ status: 400,+ description: 'Neither url nor base64 provided, or the post was blocked by a plugin.',+ })@ApiResponse({ status: 413, description: 'Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES.' })async sendImageStatus(@Param('sessionId') sessionId: string, @Body() dto: SendImageStatusDto) {return this.statusService.postImageStatus(sessionId, dto.image, {@@ -68,6 +73,10 @@ export class StatusController {'Video status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts ' +"to the account's status-privacy audience.",})+ @ApiResponse({+ status: 400,+ description: 'Neither url nor base64 provided, or the post was blocked by a plugin.',+ })@ApiResponse({ status: 413, description: 'Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES.' })async sendVideoStatus(@Param('sessionId') sessionId: string, @Body() dto: SendVideoStatusDto) {return this.statusService.postVideoStatus(sessionId, dto.video, {diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.tsindex 5b0876788..8a1753c66 100644--- a/src/modules/status/status.service.spec.ts+++ b/src/modules/status/status.service.spec.ts@@ -1,19 +1,28 @@import { BadRequestException, PayloadTooLargeException } from '@nestjs/common';import { StatusService } from './status.service';import { SessionService } from '../session/session.service';+import { HookManager } from '../../core/hooks';import { plainToInstance } from 'class-transformer';import { validate } from 'class-validator';import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';describe('StatusService media validation and selection', () => {const engine = {+ postTextStatus: jest.fn().mockResolvedValue({ id: 'text-status' }),postImageStatus: jest.fn().mockResolvedValue({ id: 'image-status' }),postVideoStatus: jest.fn().mockResolvedValue({ id: 'video-status' }),};const sessionService = { getEngine: jest.fn().mockReturnValue(engine) };- const service = new StatusService(sessionService as unknown as SessionService);+ // Pass-through gate: continue, input unchanged. The blocking/rewriting behaviour has its own+ // tests below.+ const passThrough = (_event: string, data: unknown) => Promise.resolve({ continue: true, data });+ const hookManager = { execute: jest.fn(passThrough) };+ const service = new StatusService(sessionService as unknown as SessionService, hookManager as unknown as HookManager);- beforeEach(() => jest.clearAllMocks());+ beforeEach(() => {+ jest.clearAllMocks();+ hookManager.execute.mockImplementation(passThrough);+ });it('prefers explicit base64 over url for image and video status media', async () => {const media = { url: 'https://example.com/stale', base64: 'QUJD', mimetype: 'image/png' };@@ -67,4 +76,96 @@ describe('StatusService media validation and selection', () => {else process.env.MEDIA_DOWNLOAD_MAX_BYTES = previous;}});++ // A status post publishes content from the account, so it passes the same `message:sending`+ // moderation gate as a chat send rather than going out unseen by plugins.+ describe('message:sending gate', () => {+ it('consults the gate for text, image and video status posts', async () => {+ await service.postTextStatus('s1', 'hello', { recipients: [] });+ await service.postImageStatus('s1', { base64: 'QUJD', mimetype: 'image/png' }, { recipients: [] });+ await service.postVideoStatus('s1', { base64: 'QUJD', mimetype: 'video/mp4' }, { recipients: [] });++ const types = hookManager.execute.mock.calls.map(([, data]) => (data as { type: string }).type);+ expect(types).toEqual(['status-text', 'status-image', 'status-video']);+ expect(hookManager.execute.mock.calls.every(([event]) => event === 'message:sending')).toBe(true);+ });++ it('identifies itself as StatusService so a plugin can tell it from a chat send', async () => {+ await service.postTextStatus('s1', 'hello', { recipients: [] });++ const [, , context] = hookManager.execute.mock.calls[0] as unknown as [string, unknown, { source: string }];+ expect(context.source).toBe('StatusService');+ });++ it('blocks the post and never reaches the engine when a plugin refuses', async () => {+ hookManager.execute.mockResolvedValue({ continue: false, data: undefined });++ await expect(service.postTextStatus('s1', 'spam', { recipients: [] })).rejects.toBeInstanceOf(+ BadRequestException,+ );+ expect(engine.postTextStatus).not.toHaveBeenCalled();+ });++ it('sends the plugin-rewritten text rather than the original', async () => {+ hookManager.execute.mockResolvedValue({+ continue: true,+ data: { input: { text: 'redacted', options: { recipients: [] } } },+ });++ await service.postTextStatus('s1', 'secret', { recipients: [] });++ expect(engine.postTextStatus).toHaveBeenCalledWith('redacted', { recipients: [] });+ });++ it('sends plugin-rewritten media rather than the original, for image and video', async () => {+ hookManager.execute.mockResolvedValue({+ continue: true,+ data: { input: { media: { mimetype: 'image/png', data: 'UkVX' }, options: { recipients: [] } } },+ });++ await service.postImageStatus('s1', { base64: 'QUJD', mimetype: 'image/png' }, { recipients: [] });+ await service.postVideoStatus('s1', { base64: 'QUJD', mimetype: 'video/mp4' }, { recipients: [] });++ expect(engine.postImageStatus).toHaveBeenCalledWith({ mimetype: 'image/png', data: 'UkVX' }, { recipients: [] });+ expect(engine.postVideoStatus).toHaveBeenCalledWith({ mimetype: 'image/png', data: 'UkVX' }, { recipients: [] });+ });++ // The chat path gates first and validates afterwards, so a rewritten chat payload is always+ // re-checked. The status path validates the caller's input before the gate, so the gate's+ // OUTPUT has to be re-checked explicitly or a plugin rewrite becomes a way past the byte cap.+ it('re-applies the media byte cap to a plugin rewrite', async () => {+ const previous = process.env.MEDIA_DOWNLOAD_MAX_BYTES;+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '2';+ hookManager.execute.mockResolvedValue({+ continue: true,+ data: { input: { media: { mimetype: 'image/png', data: 'QUJDREVGRw' }, options: { recipients: [] } } },+ });+ try {+ // The caller's own payload is within the cap; only the plugin's replacement exceeds it.+ await expect(+ service.postImageStatus('s1', { base64: 'QQ', mimetype: 'image/png' }, { recipients: [] }),+ ).rejects.toBeInstanceOf(PayloadTooLargeException);+ expect(engine.postImageStatus).not.toHaveBeenCalled();+ } finally {+ if (previous === undefined) delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;+ else process.env.MEDIA_DOWNLOAD_MAX_BYTES = previous;+ }+ });++ it('strips a data-URI prefix a plugin reintroduces', async () => {+ hookManager.execute.mockResolvedValue({+ continue: true,+ data: {+ input: {+ media: { mimetype: 'image/png', data: 'data:image/png;base64,UkVX' },+ options: { recipients: [] },+ },+ },+ });++ await service.postImageStatus('s1', { base64: 'QUJD', mimetype: 'image/png' }, { recipients: [] });++ expect(engine.postImageStatus).toHaveBeenCalledWith({ mimetype: 'image/png', data: 'UkVX' }, { recipients: [] });+ });+ });});diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.tsindex 6b2df3aaa..8432a556b 100644--- a/src/modules/status/status.service.ts+++ b/src/modules/status/status.service.ts@@ -2,10 +2,43 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/commimport { SessionService } from '../session/session.service';import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';+import { HookManager, applySendingGate } from '../../core/hooks';@Injectable()export class StatusService {- constructor(private readonly sessionService: SessionService) {}+ // HookManager comes from the @Global() HooksModule, so no module import is needed here.+ constructor(+ private readonly sessionService: SessionService,+ private readonly hookManager: HookManager,+ ) {}++ /**+ * A status post is content published from the account, so it goes through the same+ * `message:sending` moderation gate as a chat send. `source` distinguishes it from MessageService+ * for plugins that only want to police one of the two.+ *+ * Note for plugin authors: `input` here is NOT a send DTO — it carries no `chatId`. Text posts+ * receive `{ text, options }` and media posts `{ media: { mimetype, data }, options }`.+ */+ private gate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {+ return applySendingGate(this.hookManager, sessionId, type, input, 'StatusService');+ }++ /**+ * Re-apply the media guards to whatever the gate returned. A plugin may rewrite `media.data`, and+ * a rewritten payload has to clear the same data-URI and size checks as the original — this is+ * what the chat path gets for free by gating first and calling buildMediaInput afterwards+ * (`message.service.ts`). Here the guards run before the gate too, so a plugin cannot use a+ * rewrite to slip past `MEDIA_DOWNLOAD_MAX_BYTES`.+ */+ private guardGatedMedia(media: { mimetype: string; data: string }): { mimetype: string; data: string } {+ // `data` carries either a URL or base64 — the two are indistinguishable once merged into one+ // field. Both helpers are safe over either form: stripping a data-URI prefix leaves a URL+ // untouched, and the decoded-byte cap on a URL-length string is trivially satisfied.+ const data = stripBase64DataUri(media.data) ?? media.data;+ assertBase64WithinMediaCap(data);+ return { mimetype: media.mimetype, data };+ }async getStatuses(sessionId: string): Promise<Status[]> {const engine = this.sessionService.getEngine(sessionId);@@ -28,7 +61,8 @@ export class StatusService {if (!engine) {throw new NotFoundException(`Session ${sessionId} not found or not connected`);}- return engine.postTextStatus(text, options);+ const gated = await this.gate(sessionId, 'status-text', { text, options });+ return engine.postTextStatus(gated.text, gated.options);}async postImageStatus(@@ -47,7 +81,11 @@ export class StatusService {if (!engine) {throw new NotFoundException(`Session ${sessionId} not found or not connected`);}- return engine.postImageStatus({ mimetype: mimetype ?? 'image/jpeg', data: base64 || url || '' }, options);+ const gated = await this.gate(sessionId, 'status-image', {+ media: { mimetype: mimetype ?? 'image/jpeg', data: base64 || url || '' },+ options,+ });+ return engine.postImageStatus(this.guardGatedMedia(gated.media), gated.options);}async postVideoStatus(@@ -66,7 +104,11 @@ export class StatusService {if (!engine) {throw new NotFoundException(`Session ${sessionId} not found or not connected`);}- return engine.postVideoStatus({ mimetype: mimetype ?? 'video/mp4', data: base64 || url || '' }, options);+ const gated = await this.gate(sessionId, 'status-video', {+ media: { mimetype: mimetype ?? 'video/mp4', data: base64 || url || '' },+ options,+ });+ return engine.postVideoStatus(this.guardGatedMedia(gated.media), gated.options);}async deleteStatus(sessionId: string, statusId: string): Promise<void> {diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 6d51b0aa3..ee59e321c 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -17,6 +17,7 @@ import { Webhook } from '../entities/webhook.entity';import { WebhookFilters } from '../filters/filter-types';import { IsValidWebhookFilters } from '../filters/filter-validation';import { IsHeaderMap } from './is-header-map.validator';+import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';const FILTERS_API_DESCRIPTION ='Optional smart pre-filter. When set, every condition must match (AND) for the webhook to fire. Omit or null to fire on every subscribed event.';@@ -108,6 +109,7 @@ export class CreateWebhookDto {minimum: 0,maximum: 5,})+ @ToStrictNumber()@IsOptional()@IsInt()@Min(0)@@ -151,11 +153,13 @@ export class UpdateWebhookDto {filters?: WebhookFilters | null;@ApiPropertyOptional({ description: 'Enable/disable webhook' })+ @ToStrictBoolean()@IsOptional()@IsBoolean()active?: boolean;@ApiPropertyOptional({ description: 'Retry count' })+ @ToStrictNumber()@IsOptional()@IsInt()@Min(0)