n8n-nodes-pilot-status 2.17.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,56 @@
2
2
 
3
3
  All notable changes to `n8n-nodes-pilot-status`.
4
4
 
5
+ ## 2.19.0 - 2026-11-24
6
+
7
+ ### Added
8
+
9
+ - **Message Type** field on Message → Send, right below the recipient: **Template**
10
+ (default), **Text**, **Media**, **Interactive**. With **Text** a required **Text** field
11
+ shows and the request carries no `templateId` and no `variables: {}`; **Media** shows
12
+ **Media URL**, **Media Type** and **Caption**; **Interactive** shows **Text** and uses the
13
+ buttons/list/carousel/Flow from Additional Fields. Saved workflows without the field keep
14
+ the default **Template** and send exactly the same body as before.
15
+
16
+ - **Workspace Webhook → Rotate Secret** (`POST /v1/workspace/webhooks/{id}/rotate-secret`, no
17
+ body). Answers `{ id, hasSecret: true, secret }`; the new `plwh_…` secret is shown once and
18
+ the old one stops working immediately, so the Trigger's **Signing Secret** must be updated.
19
+ Account keys use the credential's existing **Workspace ID** (`x-workspace-id`).
20
+
21
+ ### Fixed
22
+
23
+ - **List / Carousel / Flow (JSON)** under Additional Fields were never read (the node looked
24
+ them up as top-level parameters), so the message went out without the block. They are read
25
+ from Additional Fields now.
26
+
27
+ - Trigger events **Chat Archived** (`chat.archived`), **Chat Unarchived** (`chat.unarchived`),
28
+ **Contact Blocked** (`contact.blocked`) and **Contact Unblocked** (`contact.unblocked`).
29
+ Shared body `{ id, event, data: { numberId, numberPhone, provider, jid, phone, isGroup,
30
+ occurredAt, source } }`. `chat.*` is QR Code only; `contact.*` fires on QR Code numbers and
31
+ on official Meta numbers (Meta: via the API only).
32
+
33
+ ## 2.18.0 - 2026-11-23
34
+
35
+ ### Fixed
36
+
37
+ - **Trigger on official (Meta Cloud API) numbers.** Those numbers forward Meta's native
38
+ envelope `{ object, entry }`, which has no `event` field, so a Trigger set to any
39
+ specific event answered `200 Ignored event` to every delivery and never ran. The
40
+ Trigger now matches the selected event against `entry[0].changes[0].field` too.
41
+ - **Automatic registration no longer creates a silent webhook.** The API filters
42
+ `events` down to what the number can emit, so `message.reply` on an official number
43
+ was stored as `[]` and delivered nothing. Activation now fails with an explanation and
44
+ deletes that empty webhook.
45
+
46
+ ### Added
47
+
48
+ - Trigger event **Meta: Messages (Official Numbers)** (`messages`).
49
+
50
+ ### Changed
51
+
52
+ - Credential field descriptions name the three key kinds (number `ps_number_`, workspace
53
+ `ps_workspace_`, account `ps_account_`) and which fields each one needs.
54
+
5
55
  ## 2.17.0 - 2026-11-11
6
56
 
7
57
  ### Added
package/README.md CHANGED
@@ -72,12 +72,14 @@ The secret is returned in clear **once**: in the `201` of the create (`POST /v1/
72
72
  - **Message Failed** (`message.failed`): Triggered if the message fails to send (includes error details).
73
73
  - **Message Reply** (`message.reply`): Triggered when a user replies specifically to an automated message.
74
74
  - **Message Received** (`message.received`): Triggered when a general inbound message is received on your connected WhatsApp number.
75
+ - **Meta: Messages (Official Numbers)** (`messages`): Meta Cloud API numbers only. Official numbers never send the canonical message events: they forward Meta's native envelope `{ object, entry }`, named by the webhook field in `entry[0].changes[0].field`. This event fires on that envelope (inbound messages, button taps and delivery statuses). Since 2.18.0 a specific event is matched against that field too, and Automatic registration fails at activation (deleting the webhook) when the API stores an event list without the selected event.
75
76
  - **Group Message** (`message.group`): Triggered when an inbound group message is received (group subject is included when available).
76
77
  - **Newsletter Message** (`message.newsletter`): Triggered when an inbound WhatsApp channel / newsletter message is received.
77
78
  - **Number Created / Connected / Disconnected / Removed / Restored** (`number.created`, `number.connected`, `number.disconnected`, `number.removed`, `number.restored`): Lifecycle of a WhatsApp number in your account. `number.restored` means a deleted number was brought back within its 30-day window — it returns disconnected and must be reconnected. Every `number.*` body carries a top-level `id` (UUID), the same on every retry or replay of that event — deduplicate on it; `number.connected` also carries `data.connectedAt` (ISO 8601, when the connection was established).
78
79
  - **Call Ringing / Connected / Ended / Missed / Permission Updated** (`call.ringing`, `call.connected`, `call.ended`, `call.missed`, `call.permission_updated`): WhatsApp Business Calling events (`call.*`) — Meta Cloud API **and web (Pilot Status) numbers** (`call.permission_updated` is Meta-only). Payloads are **flat** (fields next to `event`, no `data` wrapper): `{ event, callId, externalCallId?, direction, status, from, to, timestamp, duration? }`; `duration` (seconds) appears on `call.ended` only when the call was answered. `externalCallId` is the provider call id (Meta `wacid...` or Evolution GO CallID).
79
80
  - **Flow Response Received** (`flow.response_received`): Triggered when someone SUBMITS a WhatsApp Flow form — the answers arrive here. **META numbers only.** Wrapped in `data`: `{ event, data: { event, flowId, metaFlowId, flowToken, messageId, whatsappNumberId, from, receivedAt, response, responseRaw, flowMedia, submitted } }`. Four things to know. The number field is **`whatsappNumberId`, not `numberId`** — same value, different name on the wire. **`response` and `responseRaw` are mutually exclusive**: `response` holds what your own Flow endpoint returned, already parsed, and `responseRaw` is `null`; if the parse failed it is the other way round, and the raw string is the only copy of the answer there is. **On a Flow with a `data_exchange` endpoint `response` is EMPTY even on a number that stores everything** — Meta's completion payload carries only the `flow_token` — and what the person typed is in **`submitted`**: one entry per `data_exchange` screen, `{ screen, at, data, omitted }`, in order, where `omitted` (`DATA_TOO_LARGE`, `LIMIT_REACHED` or `UNREADABLE`) says why a `data` is `null`. `flowMedia` holds the files attached inside the form: `{ field, fileName, mimeType, status, url }`. Both are `null` and **never `[]`** when empty, so a node testing for an empty array never fires; `GET /v1/flows/{id}/responses` publishes the same two lists as arrays, under `media` and `submitted`. And picking this event for a **non-Meta** number fails SILENTLY: the API filters a webhook's events down to what the number's provider can emit, so the subscription is created with an empty event list, returns `201`, and never fires.
80
81
  - **Lead Received** (`lead.received`): A lead from a **Meta Lead Ads Instant Form** (Facebook / Instagram), delivered on the WhatsApp number whose Page is linked in the dashboard — **any provider**, not only Meta numbers. Wrapped in `data`: `{ event, data: { leadId, leadgenId, whatsappNumberId, pageId, pageName, formId, formName, adId, adsetId, campaignId, adName, adsetName, campaignName, platform, isOrganic, createdAt, fullName, email, phone, fields, consentGiven, conversationId } }`. The number field is **`whatsappNumberId`, not `numberId`**. `leadId` is the Pilot Status id (the one **Lead → Get** takes); `leadgenId` is Meta's, unique per lead — use it to deduplicate. `createdAt` is when the person **submitted** the form. `fields` holds every answer as `{ key, label?, values }`, and `values` is **always a list**, even for a single answer. `label` is absent when it could not be resolved; on **Lead → Get** / **Get Many** it is always present, falling back to the key. `consentGiven` is `true`/`false` only when the form has a consent checkbox configured; `null` means **unknown**, never a refusal.
82
+ - **Chat Archived / Unarchived** (`chat.archived`, `chat.unarchived`) and **Contact Blocked / Unblocked** (`contact.blocked`, `contact.unblocked`): one shared payload, `{ id, event, data: { numberId, numberPhone, provider, jid, phone, isGroup, occurredAt, source } }`. `provider` is `qrcode` or `meta`; `source` is `phone` (changed on the device) or `api` (changed through Pilot Status); `phone` is `null` when the JID is not a phone (group, LID). **`chat.*` is QR Code only**; `contact.*` fires on QR Code numbers and on official Meta numbers (Meta: only when the block is done through the API). Deduplicate on the top-level `id`.
81
83
 
82
84
  Webhook payload notes:
83
85
  - Customer webhook payloads do not include: `projectSlug`, `lastMessageId`. Optional `correlationId` (same as HTTP 202 when present) may appear on outbound status events and on `message.reply` / `message.received` when correlated to a prior send.
@@ -93,7 +95,7 @@ Webhook payload notes:
93
95
  The **Pilot Status** node provides several resources and operations to manage your account and send messages.
94
96
 
95
97
  ### 1. Message
96
- - **Send:** Send a template message (OTP, Utility, or Marketing). Choose **Phone Number** or **WhatsApp Group**; for groups use `groupId` (JID ending in `@g.us`) instead of `destinationNumber`. Optional dropdown loads groups from `GET /v1/groups` when the WhatsApp session is connected. Variables can be provided via JSON or the UI collection (including placeholders used in button labels). Add **Mark Read** (switched off) under Additional Fields to reply without marking the conversation read — e.g. an AI agent answering while a human should still see it unread; leave it out to follow the number's **Mark Read On Send** setting. Meta Cloud API numbers only (no "typing" indicator either); on Evolution numbers turn off **Read Messages** instead. Note that **Send Typing Indicator** on a Meta number also marks read. Add **Idempotency Key** under Additional Fields to make retries safe: it is sent as the `Idempotency-Key` header (never in the body), and within 24 hours the same key with the same body returns the first accepted response instead of sending again (`Idempotent-Replayed: true`). Map it from your own data (e.g. an order id) so a retry reuses it. Same key + different body → `409 IDEMPOTENCY_KEY_REUSED`; first call still running → `409 IDEMPOTENCY_KEY_IN_USE`; invalid key → `400 IDEMPOTENCY_KEY_INVALID`. Only 2xx responses are remembered, so after an error you can fix the input and retry with the same key.
98
+ - **Send:** Pick a **Message Type** first (right below the recipient): **Template** (default; OTP, Utility or Marketing template with variables), **Text** (free text — required **Text** field, no template), **Media** (**Media URL**, **Media Type**, optional **Caption**) or **Interactive** (**Text** plus buttons/list/carousel/Flow from Additional Fields). Workflows saved before this field keep working as **Template**. Choose **Phone Number** or **WhatsApp Group**; for groups use `groupId` (JID ending in `@g.us`) instead of `destinationNumber`. Optional dropdown loads groups from `GET /v1/groups` when the WhatsApp session is connected. Variables can be provided via JSON or the UI collection (including placeholders used in button labels). Add **Mark Read** (switched off) under Additional Fields to reply without marking the conversation read — e.g. an AI agent answering while a human should still see it unread; leave it out to follow the number's **Mark Read On Send** setting. Meta Cloud API numbers only (no "typing" indicator either); on Evolution numbers turn off **Read Messages** instead. Note that **Send Typing Indicator** on a Meta number also marks read. Add **Idempotency Key** under Additional Fields to make retries safe: it is sent as the `Idempotency-Key` header (never in the body), and within 24 hours the same key with the same body returns the first accepted response instead of sending again (`Idempotent-Replayed: true`). Map it from your own data (e.g. an order id) so a retry reuses it. Same key + different body → `409 IDEMPOTENCY_KEY_REUSED`; first call still running → `409 IDEMPOTENCY_KEY_IN_USE`; invalid key → `400 IDEMPOTENCY_KEY_INVALID`. Only 2xx responses are remembered, so after an error you can fix the input and retry with the same key.
97
99
  - **Get Status:** Retrieve the current status of a specific message using either its Pilot Status message id or WhatsApp provider id.
98
100
  - **Get History:** Read the conversation history of the number, newest first — both directions, every provider, including messages imported from the device on connect. Filters by **Start Date** / **End Date** over the *provider* timestamp (when the message happened, not when it was ingested). This is how you fetch old messages: the webhook does not replay history by default. Requires a number-scoped API key.
99
101
  - **Get Many:** The message **log** — sent and received, with delivery status, newest first. Different from Get History: this is the operational trail (`status`, `errorCode`, `origin`, whether the 24h window was open at send), not the chat thread. Filters: Direction, Status (comma-separated), Page, Page Size. For date/search/template filters use the HTTP Request node.
@@ -220,7 +222,7 @@ Events: `phone_line.purchased`, `phone_line.audio_received`, `phone_line.code_re
220
222
 
221
223
  ### 14. Workspace Webhook (workspace events: phone lines + `wallet.topup_paid`)
222
224
 
223
- `/v1/workspace/webhooks*` — the **same rows** as Phone Line Webhook (a webhook created on one shows on the other, same `plwh_...` secret and signature), with a wider event set: every `phone_line.*` event plus **`wallet.topup_paid`** (a wallet top-up, Pix or card, was credited: `data` = `{ orderId, amount, currency, method, provider, paidAt, balance }`). ⚠️ `*` (**All Phone Line Events**) means every *phone-line* event — it does **not** include `wallet.topup_paid`, which is opt-in: select it by name. Same seven operations, fields and rules as Phone Line Webhook (Create shows the secret once and is not idempotent; Update sends only the added fields; Get Deliveries `limit` 1–200; Get Delivery returns the exact signed `payload`). Tenant-scoped credential; `phone_lines:webhooks` (**ADMIN** and up).
225
+ `/v1/workspace/webhooks*` — the **same rows** as Phone Line Webhook (a webhook created on one shows on the other, same `plwh_...` secret and signature), with a wider event set: every `phone_line.*` event plus **`wallet.topup_paid`** (a wallet top-up, Pix or card, was credited: `data` = `{ orderId, amount, currency, method, provider, paidAt, balance }`). ⚠️ `*` (**All Phone Line Events**) means every *phone-line* event — it does **not** include `wallet.topup_paid`, which is opt-in: select it by name. Same seven operations, fields and rules as Phone Line Webhook (Create shows the secret once and is not idempotent; Update sends only the added fields; Get Deliveries `limit` 1–200; Get Delivery returns the exact signed `payload`), plus **Rotate Secret**: `POST /v1/workspace/webhooks/{id}/rotate-secret`, no body → `{ id, hasSecret: true, secret: "plwh_…" }`, the new secret shown only once. ⚠️ The old secret stops working immediately — update the **Signing Secret** of the Pilot Status Trigger (or any receiver) right away. With an account key (`ps_account_`), fill the credential's **Workspace ID** (sent as `x-workspace-id`). Tenant-scoped credential; `phone_lines:webhooks` (**ADMIN** and up).
224
226
 
225
227
  ### 15. Billing (`/v1/billing/*`)
226
228
 
@@ -7,7 +7,7 @@ export declare const DEFAULT_BASE_URL = "https://pilotstatus.com.br";
7
7
  * `/v1` callers by User-Agent and recognises this node only when the header STARTS
8
8
  * with `pilot-status-n8n/<version>`; without it n8n would send its generic `n8n`.
9
9
  */
10
- export declare const USER_AGENT = "pilot-status-n8n/2.17.0";
10
+ export declare const USER_AGENT = "pilot-status-n8n/2.19.0";
11
11
  export declare class PilotStatusApi implements ICredentialType {
12
12
  name: string;
13
13
  displayName: string;
@@ -26,7 +26,7 @@ class PilotStatusApi {
26
26
  },
27
27
  default: '',
28
28
  required: true,
29
- description: 'API Key can be found in Pilot Status Dashboard -> API Keys',
29
+ description: 'A number key (ps_number_…, dashboard → API Keys), a workspace key (ps_workspace_…, dashboard → Workspace keys) or an account key (ps_account_…, Profile → API). Number key: leave the two fields below empty. Workspace key: fill WhatsApp Number ID. Account key: fill both.',
30
30
  },
31
31
  {
32
32
  displayName: 'Base URL',
@@ -42,7 +42,7 @@ class PilotStatusApi {
42
42
  type: 'string',
43
43
  default: '',
44
44
  required: false,
45
- description: 'Sent as x-whatsapp-number-id on every request. Required when the key is tenant-scoped and the operation is per-number (Chatwoot, webhook logs); leave empty for a number-scoped key, which already carries its number.',
45
+ description: 'Sent as x-whatsapp-number-id on every request. Required with a WORKSPACE or ACCOUNT key for anything that acts on one number (sending, logs, templates, webhooks, Trigger Automatic registration) — without it those calls answer 403 TENANT_SCOPE_NOT_ALLOWED or 400 NUMBER_REQUIRED. Leave empty for a number key (ps_number_…), which already carries its number. The id comes from Number → Get Many.',
46
46
  },
47
47
  {
48
48
  displayName: 'Workspace ID',
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.17.0";
1
+ export declare const PACKAGE_VERSION = "2.19.0";
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PACKAGE_VERSION = void 0;
4
4
  // GENERATED by scripts/write-version.cjs from package.json — do not edit by hand.
5
- exports.PACKAGE_VERSION = "2.17.0";
5
+ exports.PACKAGE_VERSION = "2.19.0";
@@ -756,7 +756,7 @@ class PilotStatus {
756
756
  send: {
757
757
  preSend: [
758
758
  async function (requestOptions) {
759
- var _a, _b, _c;
759
+ var _a, _b, _c, _d, _e, _f, _g;
760
760
  const destinationType = this.getNodeParameter('sendDestinationType') || 'phone';
761
761
  if (!requestOptions.body || typeof requestOptions.body !== 'object') {
762
762
  requestOptions.body = {};
@@ -789,9 +789,43 @@ class PilotStatus {
789
789
  throw new Error('Pilot Status: informe destinationNumber (E.164) ao enviar para telefone.');
790
790
  }
791
791
  }
792
+ // Message Type. Saved workflows from before this field have no
793
+ // `messageType`; n8n fills the default ('template'), and the `||` covers
794
+ // callers that hand back undefined — both keep the old request body.
795
+ const messageType = this.getNodeParameter('messageType', 'template') || 'template';
796
+ if (messageType !== 'template') {
797
+ // Free text, media and interactive sends carry no template: no
798
+ // templateId and no `variables: {}`.
799
+ delete body.templateId;
800
+ delete body.variables;
801
+ if (messageType === 'text' || messageType === 'interactive') {
802
+ const text = String((_a = this.getNodeParameter('messageText', '')) !== null && _a !== void 0 ? _a : '').trim();
803
+ if (!text) {
804
+ throw new Error('Pilot Status: informe o campo "Text" para enviar uma mensagem de texto.');
805
+ }
806
+ body.text = text;
807
+ }
808
+ else if (messageType === 'media') {
809
+ const mediaUrl = String((_b = this.getNodeParameter('mediaUrl', '')) !== null && _b !== void 0 ? _b : '').trim();
810
+ if (!mediaUrl) {
811
+ throw new Error('Pilot Status: informe o campo "Media URL" para enviar mídia.');
812
+ }
813
+ const mediaKind = this.getNodeParameter('mediaKind', 'image') || 'image';
814
+ const caption = String((_c = this.getNodeParameter('mediaCaption', '')) !== null && _c !== void 0 ? _c : '').trim();
815
+ body.media = mediaUrl;
816
+ body.mediaType = mediaKind;
817
+ if (caption)
818
+ body.text = caption;
819
+ else
820
+ delete body.text;
821
+ }
822
+ }
792
823
  const mode = this.getNodeParameter('variablesMode');
793
824
  let variables = {};
794
- if (mode === 'json') {
825
+ if (messageType !== 'template') {
826
+ // no template variables to collect
827
+ }
828
+ else if (mode === 'json') {
795
829
  const raw = this.getNodeParameter('variablesJson');
796
830
  try {
797
831
  const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
@@ -807,8 +841,8 @@ class PilotStatus {
807
841
  }
808
842
  else {
809
843
  const ui = this.getNodeParameter('variablesUi');
810
- for (const entry of (_a = ui === null || ui === void 0 ? void 0 : ui.values) !== null && _a !== void 0 ? _a : []) {
811
- variables[entry.name] = String((_b = entry.value) !== null && _b !== void 0 ? _b : '');
844
+ for (const entry of (_d = ui === null || ui === void 0 ? void 0 : ui.values) !== null && _d !== void 0 ? _d : []) {
845
+ variables[entry.name] = String((_e = entry.value) !== null && _e !== void 0 ? _e : '');
812
846
  }
813
847
  }
814
848
  // reason: defensive re-guard — requestOptions.body is already an object here (set above by the first guard / destination handling), so this branch is unreachable.
@@ -817,7 +851,9 @@ class PilotStatus {
817
851
  requestOptions.body = {};
818
852
  }
819
853
  /* v8 ignore stop */
820
- requestOptions.body['variables'] = variables;
854
+ if (messageType === 'template') {
855
+ requestOptions.body['variables'] = variables;
856
+ }
821
857
  // Blocos interativos: cada um chega como JSON e entra no corpo com o
822
858
  // nome que a API espera. Um JSON invalido para AQUI com o valor a
823
859
  // vista — deixar passar mandaria a mensagem sem o bloco, e ela sairia
@@ -827,7 +863,13 @@ class PilotStatus {
827
863
  ['carouselJson', 'carousel'],
828
864
  ['flowJson', 'flow'],
829
865
  ]) {
830
- const bruto = this.getNodeParameter(param, '');
866
+ // The fields live under Additional Fields; a top-level parameter of
867
+ // the same name is still honoured for older callers.
868
+ const extras = ((_f = this.getNodeParameter('additionalFields', {})) !== null && _f !== void 0 ? _f : {});
869
+ const topLevel = this.getNodeParameter(param, '');
870
+ const bruto = topLevel !== undefined && topLevel !== null && topLevel !== ''
871
+ ? topLevel
872
+ : extras[param];
831
873
  if (bruto === undefined || bruto === null || bruto === '')
832
874
  continue;
833
875
  let valor = bruto;
@@ -851,7 +893,7 @@ class PilotStatus {
851
893
  : '';
852
894
  if (idempotencyKey) {
853
895
  requestOptions.headers = {
854
- ...((_c = requestOptions.headers) !== null && _c !== void 0 ? _c : {}),
896
+ ...((_g = requestOptions.headers) !== null && _g !== void 0 ? _g : {}),
855
897
  'Idempotency-Key': idempotencyKey,
856
898
  };
857
899
  }
@@ -936,16 +978,6 @@ class PilotStatus {
936
978
  default: 'send',
937
979
  },
938
980
  // Message: Send — campos
939
- {
940
- displayName: 'Template ID',
941
- name: 'templateId',
942
- type: 'options',
943
- typeOptions: { loadOptionsMethod: 'getTemplates' },
944
- displayOptions: { show: { resource: ['message'], operation: ['send'] } },
945
- default: '',
946
- required: false,
947
- routing: { send: { type: 'body', property: 'templateId' } },
948
- },
949
981
  {
950
982
  displayName: 'Send To',
951
983
  name: 'sendDestinationType',
@@ -999,6 +1031,81 @@ class PilotStatus {
999
1031
  description: 'ID do canal (@newsletter)',
1000
1032
  routing: { send: { type: 'body', property: 'newsletterId' } },
1001
1033
  },
1034
+ // Message Type: right below the recipient, so free text is not hidden behind
1035
+ // Additional Fields. Default 'template' = exactly the pre-2.19 behaviour.
1036
+ {
1037
+ displayName: 'Message Type',
1038
+ name: 'messageType',
1039
+ type: 'options',
1040
+ noDataExpression: true,
1041
+ options: [
1042
+ { name: 'Template', value: 'template', description: 'Approved template with variables' },
1043
+ { name: 'Text', value: 'text', description: 'Free-form text message (no template)' },
1044
+ { name: 'Media', value: 'media', description: 'Image, video, document, audio, voice note or sticker' },
1045
+ {
1046
+ name: 'Interactive',
1047
+ value: 'interactive',
1048
+ description: 'Text with buttons, list, carousel or Flow (set them under Additional Fields)',
1049
+ },
1050
+ ],
1051
+ default: 'template',
1052
+ displayOptions: { show: { resource: ['message'], operation: ['send'] } },
1053
+ },
1054
+ {
1055
+ displayName: 'Text',
1056
+ name: 'messageText',
1057
+ type: 'string',
1058
+ typeOptions: { rows: 4 },
1059
+ default: '',
1060
+ required: true,
1061
+ description: 'Message body',
1062
+ displayOptions: {
1063
+ show: { resource: ['message'], operation: ['send'], messageType: ['text', 'interactive'] },
1064
+ },
1065
+ },
1066
+ {
1067
+ displayName: 'Media URL',
1068
+ name: 'mediaUrl',
1069
+ type: 'string',
1070
+ default: '',
1071
+ required: true,
1072
+ description: 'Public URL of the file to send',
1073
+ displayOptions: { show: { resource: ['message'], operation: ['send'], messageType: ['media'] } },
1074
+ },
1075
+ {
1076
+ displayName: 'Media Type',
1077
+ name: 'mediaKind',
1078
+ type: 'options',
1079
+ options: [
1080
+ { name: 'Image', value: 'image' },
1081
+ { name: 'Video', value: 'video' },
1082
+ { name: 'Document', value: 'document' },
1083
+ { name: 'Audio (File on Official Numbers)', value: 'audio' },
1084
+ { name: 'Voice Note', value: 'voice' },
1085
+ { name: 'Sticker', value: 'sticker' },
1086
+ ],
1087
+ default: 'image',
1088
+ description: 'Audio and Sticker take no caption. Sticker must be image/webp.',
1089
+ displayOptions: { show: { resource: ['message'], operation: ['send'], messageType: ['media'] } },
1090
+ },
1091
+ {
1092
+ displayName: 'Caption',
1093
+ name: 'mediaCaption',
1094
+ type: 'string',
1095
+ default: '',
1096
+ description: 'Optional text sent with the media',
1097
+ displayOptions: { show: { resource: ['message'], operation: ['send'], messageType: ['media'] } },
1098
+ },
1099
+ {
1100
+ displayName: 'Template ID',
1101
+ name: 'templateId',
1102
+ type: 'options',
1103
+ typeOptions: { loadOptionsMethod: 'getTemplates' },
1104
+ displayOptions: { show: { resource: ['message'], operation: ['send'], messageType: ['template'] } },
1105
+ default: '',
1106
+ required: false,
1107
+ routing: { send: { type: 'body', property: 'templateId' } },
1108
+ },
1002
1109
  {
1003
1110
  displayName: 'Variables Mode',
1004
1111
  name: 'variablesMode',
@@ -1009,7 +1116,7 @@ class PilotStatus {
1009
1116
  { name: 'JSON Object', value: 'json', description: 'Provide an object with key-value pairs' },
1010
1117
  ],
1011
1118
  default: 'collection',
1012
- displayOptions: { show: { resource: ['message'], operation: ['send'] } },
1119
+ displayOptions: { show: { resource: ['message'], operation: ['send'], messageType: ['template'] } },
1013
1120
  },
1014
1121
  {
1015
1122
  displayName: 'Variables (JSON)',
@@ -1017,7 +1124,7 @@ class PilotStatus {
1017
1124
  type: 'string',
1018
1125
  default: '{}',
1019
1126
  displayOptions: {
1020
- show: { resource: ['message'], operation: ['send'], variablesMode: ['json'] },
1127
+ show: { resource: ['message'], operation: ['send'], messageType: ['template'], variablesMode: ['json'] },
1021
1128
  },
1022
1129
  description: 'A JSON object containing key-value pairs for variables',
1023
1130
  },
@@ -1027,7 +1134,7 @@ class PilotStatus {
1027
1134
  type: 'fixedCollection',
1028
1135
  typeOptions: { multipleValues: true },
1029
1136
  displayOptions: {
1030
- show: { resource: ['message'], operation: ['send'], variablesMode: ['collection'] },
1137
+ show: { resource: ['message'], operation: ['send'], messageType: ['template'], variablesMode: ['collection'] },
1031
1138
  },
1032
1139
  default: {},
1033
1140
  description: 'Preencha as variáveis do template selecionado',
@@ -3805,6 +3912,18 @@ class PilotStatus {
3805
3912
  },
3806
3913
  },
3807
3914
  },
3915
+ {
3916
+ name: 'Rotate Secret',
3917
+ value: 'rotateSecret',
3918
+ description: 'Generate a NEW signing secret for the webhook. No body. Answers {id, hasSecret: true, secret: "plwh_…"} — the secret is shown ONLY in this response, store it now. ⚠️ The old secret stops working IMMEDIATELY: deliveries are signed with the new one from now on, so update the Signing Secret of every Pilot Status Trigger (or receiver) that validates this webhook, or it starts answering 401.',
3919
+ action: 'Rotate the signing secret of a workspace webhook',
3920
+ routing: {
3921
+ request: {
3922
+ method: 'POST',
3923
+ url: '=/workspace/webhooks/{{encodeURIComponent($parameter.workspaceWebhookId)}}/rotate-secret',
3924
+ },
3925
+ },
3926
+ },
3808
3927
  ],
3809
3928
  default: 'getAll',
3810
3929
  },
@@ -3816,7 +3935,7 @@ class PilotStatus {
3816
3935
  displayOptions: {
3817
3936
  show: {
3818
3937
  resource: ['workspaceWebhook'],
3819
- operation: ['delete', 'get', 'update', 'getDeliveries', 'getDelivery'],
3938
+ operation: ['delete', 'get', 'update', 'getDeliveries', 'getDelivery', 'rotateSecret'],
3820
3939
  },
3821
3940
  },
3822
3941
  default: '',
@@ -13,6 +13,16 @@ export declare const DEFAULT_BASE_URL = "https://pilotstatus.com.br";
13
13
  * rejection).
14
14
  */
15
15
  export declare function isValidSignature(rawBody: Buffer, signature: string, secret: string): boolean;
16
+ /**
17
+ * The event name a delivery stands for.
18
+ *
19
+ * A Meta Cloud API (official) number does not send `{ event, data }`: it forwards
20
+ * Meta's native envelope `{ object, entry }`, whose only name is the webhook FIELD
21
+ * in `entry[0].changes[0].field` (`messages`, `message_template_status_update`, ...).
22
+ * Reading `body.event` alone made every Meta delivery look nameless, so a Trigger
23
+ * set to any specific event answered `Ignored event` to all of them and never ran.
24
+ */
25
+ export declare function deliveredEventName(body: unknown): string | undefined;
16
26
  export declare class PilotStatusTrigger implements INodeType {
17
27
  description: INodeTypeDescription;
18
28
  webhookMethods: {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PilotStatusTrigger = exports.DEFAULT_BASE_URL = exports.SIGNATURE_HEADER = void 0;
4
4
  exports.isValidSignature = isValidSignature;
5
+ exports.deliveredEventName = deliveredEventName;
5
6
  const crypto_1 = require("crypto");
6
7
  /** Header the dispatcher uses to sign every delivery (HMAC-SHA256 hex of the raw body). */
7
8
  exports.SIGNATURE_HEADER = 'x-pilot-status-signature';
@@ -23,6 +24,25 @@ function isValidSignature(rawBody, signature, secret) {
23
24
  return false;
24
25
  return (0, crypto_1.timingSafeEqual)(received, expected);
25
26
  }
27
+ /**
28
+ * The event name a delivery stands for.
29
+ *
30
+ * A Meta Cloud API (official) number does not send `{ event, data }`: it forwards
31
+ * Meta's native envelope `{ object, entry }`, whose only name is the webhook FIELD
32
+ * in `entry[0].changes[0].field` (`messages`, `message_template_status_update`, ...).
33
+ * Reading `body.event` alone made every Meta delivery look nameless, so a Trigger
34
+ * set to any specific event answered `Ignored event` to all of them and never ran.
35
+ */
36
+ function deliveredEventName(body) {
37
+ var _a, _b, _c, _d;
38
+ if (!body || typeof body !== 'object')
39
+ return undefined;
40
+ const b = body;
41
+ if (typeof b.event === 'string')
42
+ return b.event;
43
+ const field = (_d = (_c = (_b = (_a = b.entry) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.changes) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.field;
44
+ return typeof field === 'string' ? field : undefined;
45
+ }
26
46
  /** The credential's `/v1` root, for the auto-registration calls. */
27
47
  async function apiBaseUrl(ctx) {
28
48
  const credentials = (await ctx.getCredentials('pilotStatusApi'));
@@ -112,6 +132,11 @@ class PilotStatusTrigger {
112
132
  name: 'Message Received',
113
133
  value: 'message.received',
114
134
  },
135
+ {
136
+ name: 'Meta: Messages (Official Numbers)',
137
+ value: 'messages',
138
+ description: "Meta Cloud API numbers only: Meta's native envelope { object, entry } for the 'messages' field — inbound messages, button taps and delivery statuses (value.statuses). Official numbers never send message.received / message.reply.",
139
+ },
115
140
  {
116
141
  name: 'Group Message',
117
142
  value: 'message.group',
@@ -178,6 +203,26 @@ class PilotStatusTrigger {
178
203
  // the number's provider, and is routed to the number its Page is linked to.
179
204
  description: 'A lead from a Meta Lead Ads Instant Form (Facebook / Instagram), delivered on the number whose Page is linked in the dashboard — any provider. The data wrapper names the number whatsappNumberId, NOT numberId, and the lead id is data.leadId (the id GET /v1/leads/{id} takes), NOT Meta\'s leadgenId. consentGiven null means UNKNOWN, not a refusal.',
180
205
  },
206
+ {
207
+ name: 'Chat Archived',
208
+ value: 'chat.archived',
209
+ description: 'A chat was archived on the phone. QR Code numbers only: on a Meta number this subscribes to nothing.',
210
+ },
211
+ {
212
+ name: 'Chat Unarchived',
213
+ value: 'chat.unarchived',
214
+ description: 'A chat was unarchived on the phone. QR Code numbers only: on a Meta number this subscribes to nothing.',
215
+ },
216
+ {
217
+ name: 'Contact Blocked',
218
+ value: 'contact.blocked',
219
+ description: 'A contact was blocked. QR Code numbers (on the phone or via the API) and Meta numbers (via the API only).',
220
+ },
221
+ {
222
+ name: 'Contact Unblocked',
223
+ value: 'contact.unblocked',
224
+ description: 'A contact was unblocked. QR Code numbers (on the phone or via the API) and Meta numbers (via the API only).',
225
+ },
181
226
  ],
182
227
  default: '*',
183
228
  description: 'The event to listen to',
@@ -251,6 +296,25 @@ class PilotStatusTrigger {
251
296
  }));
252
297
  if (!(created === null || created === void 0 ? void 0 : created.id))
253
298
  return false;
299
+ // The API FILTERS `events` down to what the number's provider can emit
300
+ // instead of rejecting the list: `message.reply` on a Meta number comes
301
+ // back 201 with `events: []`, a subscription that never delivers. Fail
302
+ // the activation loudly and remove the empty webhook instead.
303
+ if (Array.isArray(created.events) && !created.events.includes(event)) {
304
+ try {
305
+ await this.helpers.requestWithAuthentication.call(this, 'pilotStatusApi', {
306
+ method: 'DELETE',
307
+ baseURL: await apiBaseUrl(this),
308
+ url: `/webhooks/${created.id}`,
309
+ json: true,
310
+ });
311
+ }
312
+ catch {
313
+ // Best effort: the error below is what the author must see.
314
+ }
315
+ throw new Error(`Pilot Status: this number cannot emit "${event}", so the webhook would never fire. ` +
316
+ 'Official (Meta Cloud API) numbers send Meta\'s native envelope: pick "Meta: Messages (Official Numbers)" or "All Events".');
317
+ }
254
318
  this.getWorkflowStaticData('node').webhookId = created.id;
255
319
  return true;
256
320
  },
@@ -303,7 +367,7 @@ class PilotStatusTrigger {
303
367
  };
304
368
  }
305
369
  }
306
- if (event !== '*' && bodyData.event !== event) {
370
+ if (event !== '*' && deliveredEventName(bodyData) !== event) {
307
371
  return {
308
372
  webhookResponse: {
309
373
  status: 200,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-nodes-pilot-status",
3
- "version": "2.17.0",
3
+ "version": "2.19.0",
4
4
  "description": "n8n node for Pilot Status API",
5
5
  "keywords": [
6
6
  "n8ncommunity",