Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): publish a secret example the route accepts
Yudhi Armyndharis48ea0c147dce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7ab033fb..ce243e7f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,6 +51,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0size, on both engines, instead of dropping the field and looking like a message that never had media.- Webhook filters and automation rules gated on `hasMedia` now match those messages.- Baileys logs a failed inbound media download at `warn` instead of `debug`, so it is visible by default.+- The webhook `secret` example in Swagger and the API reference was shorter than the 16-character floor+ the route enforces, so pasting it back answered `400`; it now passes, and the schema publishes the+ length bounds ([#1491](https://github.com/rmyndharis/OpenWA/issues/1491)). Thanks @onepay-ye.### Dependenciesdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 22bede2aa..80fda98d5 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4501,7 +4501,7 @@ Create a webhook for the session.| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. || events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |-| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |+| secret | string | no | `@IsString`, `@MinLength(16)`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. || headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. || filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload cannot match, so it suppresses the event entirely (a field with no definition for the family is skipped instead, and does not suppress) — `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` filter silently drops all three. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. || retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |@@ -4510,7 +4510,7 @@ Create a webhook for the session.{"url": "https://your-server.com/webhook","events": ["message.received", "session.status"],- "secret": "your-secret-key",+ "secret": "your-webhook-signing-secret","headers": { "X-Custom-Header": "value" },"filters": {"conditions": [@@ -4567,7 +4567,7 @@ Update a webhook. Partial — only fields present in the body are changed.| ---------- | ---------------------- | -------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- || url | string | no | `@IsOptional`, `@IsUrl({ require_tld: false })`; re-runs the SSRF guard when provided → `400` if blocked. | New URL. || events | string[] | no | `@IsOptional`, `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Same allowed set as create (incl. `*`). |-| secret | string | no | `@IsOptional`, `@IsString`, `@MaxLength(255)` | **Write-only.** An empty string is normalized to `null`, which disables HMAC. |+| secret | string | no | `@IsOptional`, `@IsString`, `@MinLength(16)` (skipped for `""`, which clears it), `@MaxLength(255)` | **Write-only.** An empty string is normalized to `null`, which disables HMAC. || headers | Record<string,string> | no | `@IsOptional`, `@IsHeaderMap()` (same constraints as create) | **Write-only.** Replaces existing headers wholesale when provided. || filters | WebhookFilters \| null | no | `@IsOptional`, `@IsValidWebhookFilters()` | Set to `null` to clear filters. || active | boolean | no | `@IsOptional`, `@IsBoolean` | Enable/disable the webhook. (Present only on update, not create.) |diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex f2f0f5749..16653370d 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -1156,7 +1156,7 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/webhooks" \-d '{"url": "https://your-server.com/webhook","events": ["message.received", "session.status"],- "secret": "your-secret-key",+ "secret": "your-webhook-signing-secret","headers": { "X-Custom-Header": "value" },"filters": {"conditions": [diff --git a/openapi.json b/openapi.jsonindex a1e5f1582..0bd49771c 100644--- a/openapi.json+++ b/openapi.json@@ -10815,12 +10815,14 @@},"secret": {"type": "string",- "description": "Secret key for HMAC signature verification",- "example": "your-secret-key"+ "description": "Secret key for HMAC signature verification. Never returned by any webhook route; it is used to compute the `X-OpenWA-Signature: sha256=<hex>` header on every delivery.",+ "minLength": 16,+ "maxLength": 255,+ "example": "your-webhook-signing-secret"},"headers": {"type": "object",- "description": "Custom headers to include in webhook requests",+ "description": "Custom headers to include in webhook requests. Never returned by any webhook route. At delivery, `content-type` and `x-openwa-*` names are stripped so a custom header cannot shadow a system one.","example": {"X-Custom-Header": "value"}@@ -11007,11 +11009,16 @@},"secret": {"type": "string",- "description": "Secret key for HMAC signature"+ "description": "Secret key for HMAC signature. At least 16 characters, or an empty string to clear it. Never returned by any webhook route.",+ "maxLength": 255,+ "example": "your-webhook-signing-secret"},"headers": {"type": "object",- "description": "Custom headers"+ "description": "Custom headers. Replaces the stored map wholesale. Never returned by any webhook route.",+ "example": {+ "X-Custom-Header": "value"+ }},"filters": {"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.",diff --git a/src/config/openapi-contract.spec.ts b/src/config/openapi-contract.spec.tsindex 47d645d2a..e8eb5e204 100644--- a/src/config/openapi-contract.spec.ts+++ b/src/config/openapi-contract.spec.ts@@ -247,3 +247,55 @@ describe('every JSON request body publishes an object schema', () => {expect(primitives).toEqual([]);});});++/**+ * A published `example` is what a reader pastes into Swagger's "Try it out", so an example its own+ * route rejects is worse than no example at all: the first request against a new endpoint answers+ * `400`, and the schema that caused it says nothing about why. `CreateWebhookDto.secret` offered a+ * 15-character example under a 16-character floor, which is exactly how it was found+ * ([#1491](https://github.com/rmyndharis/OpenWA/issues/1491)).+ *+ * Only length is checked here. It is the constraint a hand-written example actually drifts past, and+ * it needs no validator: the bound and the example sit in the same schema object.+ */+describe('every published string example fits its own schema', () => {+ type Example = { where: string; example: string; min?: number; max?: number };++ const examples = (): Example[] => {+ const schemas = (snapshot().components?.schemas ?? {}) as Record<+ string,+ { properties?: Record<string, { type?: string; example?: unknown; minLength?: number; maxLength?: number }> }+ >;+ const out: Example[] = [];+ for (const [name, schema] of Object.entries(schemas)) {+ for (const [property, spec] of Object.entries(schema.properties ?? {})) {+ if (spec.type === 'string' && typeof spec.example === 'string') {+ out.push({ where: `${name}.${property}`, example: spec.example, min: spec.minLength, max: spec.maxLength });+ }+ }+ }+ return out;+ };++ const bounded = (): Example[] => examples().filter(({ min, max }) => min !== undefined || max !== undefined);++ // Guards the assertion below twice over: an extractor that found no examples would pass it+ // vacuously, and so would one that found examples but never a schema that bounds their length.+ it('finds the document’s string examples, and the bounded ones among them', () => {+ expect(examples().length).toBeGreaterThan(200);+ expect(bounded().length).toBeGreaterThan(9);+ });++ it('publishes none of them outside its own minLength/maxLength', () => {+ const violations = bounded()+ .filter(+ ({ example, min, max }) =>+ (min !== undefined && example.length < min) || (max !== undefined && example.length > max),+ )+ .map(+ ({ where, example, min, max }) =>+ `${where}: ${JSON.stringify(example)} is ${example.length} chars, bounds [${min ?? '-'}, ${max ?? '-'}]`,+ );+ expect(violations).toEqual([]);+ });+});diff --git a/src/modules/webhook/dto/webhook-secret-entropy.spec.ts b/src/modules/webhook/dto/webhook-secret-entropy.spec.tsindex 2ede02b32..b87029f05 100644--- a/src/modules/webhook/dto/webhook-secret-entropy.spec.ts+++ b/src/modules/webhook/dto/webhook-secret-entropy.spec.ts@@ -68,3 +68,36 @@ describe('UpdateWebhookDto secret entropy', () => {expect(errors.some(e => e.property === 'secret')).toBe(true);});});++/**+ * The example Swagger renders is the body most readers send first, so the floor above has to hold for+ * it too. It did not: the published example was 15 characters, and pasting it back through "Try it+ * out" answered `400` naming a `minLength` the schema never declared, which reads as the API dropping+ * the field rather than refusing it ([#1491](https://github.com/rmyndharis/OpenWA/issues/1491)).+ *+ * Read straight off the decorator rather than restating the value, so an example edited in the DTO is+ * still the one under test.+ */+describe('the documented secret example', () => {+ const exampleOf = (target: object, property: string): unknown =>+ (Reflect.getMetadata('swagger/apiModelProperties', target, property) as { example?: unknown } | undefined)?.example;++ it('is published on both routes', () => {+ expect(typeof exampleOf(CreateWebhookDto.prototype, 'secret')).toBe('string');+ expect(typeof exampleOf(UpdateWebhookDto.prototype, 'secret')).toBe('string');+ });++ it('passes the validation the create route applies to it', async () => {+ const dto = new CreateWebhookDto();+ dto.url = 'https://receiver.example.com/hook';+ dto.events = ['message.received'];+ dto.secret = exampleOf(CreateWebhookDto.prototype, 'secret') as string;+ expect(await validate(dto)).toEqual([]);+ });++ it('passes the validation the update route applies to it', async () => {+ const dto = new UpdateWebhookDto();+ dto.secret = exampleOf(UpdateWebhookDto.prototype, 'secret') as string;+ expect(await validate(dto)).toEqual([]);+ });+});diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex f0b81bad7..c30f1ae77 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -124,8 +124,16 @@ export class CreateWebhookDto {events?: string[];@ApiPropertyOptional({- description: 'Secret key for HMAC signature verification',- example: 'your-secret-key',+ description:+ 'Secret key for HMAC signature verification. Never returned by any webhook route; it is used to ' ++ 'compute the `X-OpenWA-Signature: sha256=<hex>` header on every delivery.',+ // Both bounds are spelled out because @MinLength/@MaxLength do not reach the published schema on+ // their own, and the example must satisfy them: the previous 15-character one was rejected by the+ // very route that offered it, so pasting it back from Swagger answered 400+ // ([#1491](https://github.com/rmyndharis/OpenWA/issues/1491)).+ minLength: 16,+ maxLength: 255,+ example: 'your-webhook-signing-secret',})@IsOptional()@IsString()@@ -136,7 +144,9 @@ export class CreateWebhookDto {secret?: string;@ApiPropertyOptional({- description: 'Custom headers to include in webhook requests',+ description:+ 'Custom headers to include in webhook requests. Never returned by any webhook route. At delivery, ' ++ '`content-type` and `x-openwa-*` names are stripped so a custom header cannot shadow a system one.',example: { 'X-Custom-Header': 'value' },})@IsOptional()@@ -190,7 +200,16 @@ export class UpdateWebhookDto {@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })events?: string[];- @ApiPropertyOptional({ description: 'Secret key for HMAC signature' })+ @ApiPropertyOptional({+ // No `minLength` here, unlike create: this route also accepts the empty string as "clear the+ // secret", so a 16 in the schema would reject a value the route honours. The floor still applies+ // to every other value, which only the description can say.+ description:+ 'Secret key for HMAC signature. At least 16 characters, or an empty string to clear it. ' ++ 'Never returned by any webhook route.',+ maxLength: 255,+ example: 'your-webhook-signing-secret',+ })@IsOptional()@IsString()// Same floor as create: a short secret is brute-forcible from one observed signature. The@@ -201,7 +220,10 @@ export class UpdateWebhookDto {@MaxLength(255)secret?: string;- @ApiPropertyOptional({ description: 'Custom headers' })+ @ApiPropertyOptional({+ description: 'Custom headers. Replaces the stored map wholesale. Never returned by any webhook route.',+ example: { 'X-Custom-Header': 'value' },+ })@IsOptional()@IsHeaderMap()headers?: Record<string, string>;