n8n-nodes-pilot-status 1.3.0 → 2.2.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.
@@ -1,5 +1,26 @@
1
- import { IWebhookFunctions, INodeType, INodeTypeDescription, IWebhookResponseData } from 'n8n-workflow';
1
+ import { IHookFunctions, IWebhookFunctions, INodeType, INodeTypeDescription, IWebhookResponseData } from 'n8n-workflow';
2
+ /** Header the dispatcher uses to sign every delivery (HMAC-SHA256 hex of the raw body). */
3
+ export declare const SIGNATURE_HEADER = "x-pilot-status-signature";
4
+ /** Production. Mirrors the credential's default. */
5
+ export declare const DEFAULT_BASE_URL = "https://pilotstatus.com.br";
6
+ /**
7
+ * Checks the HMAC signature of a delivery.
8
+ *
9
+ * Without this, the Trigger fires on ANY POST that reaches the webhook URL —
10
+ * the event filter only looks at the body, which the attacker controls. Compares
11
+ * with `timingSafeEqual` over buffers of the same length (it THROWS when the
12
+ * lengths differ, so the length check is what avoids a 500 instead of a
13
+ * rejection).
14
+ */
15
+ export declare function isValidSignature(rawBody: Buffer, signature: string, secret: string): boolean;
2
16
  export declare class PilotStatusTrigger implements INodeType {
3
17
  description: INodeTypeDescription;
18
+ webhookMethods: {
19
+ default: {
20
+ checkExists(this: IHookFunctions): Promise<boolean>;
21
+ create(this: IHookFunctions): Promise<boolean>;
22
+ delete(this: IHookFunctions): Promise<boolean>;
23
+ };
24
+ };
4
25
  webhook(this: IWebhookFunctions): Promise<IWebhookResponseData>;
5
26
  }
@@ -1,6 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PilotStatusTrigger = void 0;
3
+ exports.PilotStatusTrigger = exports.DEFAULT_BASE_URL = exports.SIGNATURE_HEADER = void 0;
4
+ exports.isValidSignature = isValidSignature;
5
+ const crypto_1 = require("crypto");
6
+ /** Header the dispatcher uses to sign every delivery (HMAC-SHA256 hex of the raw body). */
7
+ exports.SIGNATURE_HEADER = 'x-pilot-status-signature';
8
+ /** Production. Mirrors the credential's default. */
9
+ exports.DEFAULT_BASE_URL = 'https://pilotstatus.com.br';
10
+ /**
11
+ * Checks the HMAC signature of a delivery.
12
+ *
13
+ * Without this, the Trigger fires on ANY POST that reaches the webhook URL —
14
+ * the event filter only looks at the body, which the attacker controls. Compares
15
+ * with `timingSafeEqual` over buffers of the same length (it THROWS when the
16
+ * lengths differ, so the length check is what avoids a 500 instead of a
17
+ * rejection).
18
+ */
19
+ function isValidSignature(rawBody, signature, secret) {
20
+ const expected = Buffer.from((0, crypto_1.createHmac)('sha256', secret).update(rawBody).digest('hex'), 'utf8');
21
+ const received = Buffer.from(signature, 'utf8');
22
+ if (received.length !== expected.length)
23
+ return false;
24
+ return (0, crypto_1.timingSafeEqual)(received, expected);
25
+ }
26
+ /** The credential's `/v1` root, for the auto-registration calls. */
27
+ async function apiBaseUrl(ctx) {
28
+ const credentials = (await ctx.getCredentials('pilotStatusApi'));
29
+ return `${((credentials === null || credentials === void 0 ? void 0 : credentials.baseUrl) || exports.DEFAULT_BASE_URL).replace(/\/+$/, '')}/v1`;
30
+ }
4
31
  class PilotStatusTrigger {
5
32
  constructor() {
6
33
  this.description = {
@@ -15,6 +42,15 @@ class PilotStatusTrigger {
15
42
  },
16
43
  inputs: [],
17
44
  outputs: ['main'],
45
+ // The credential is OPTIONAL on purpose: Manual mode (the default) keeps
46
+ // working without one, exactly as it always has. It is only needed in
47
+ // Automatic mode, which creates and deletes the subscription on its own.
48
+ credentials: [
49
+ {
50
+ name: 'pilotStatusApi',
51
+ required: false,
52
+ },
53
+ ],
18
54
  webhooks: [
19
55
  {
20
56
  name: 'default',
@@ -24,6 +60,25 @@ class PilotStatusTrigger {
24
60
  },
25
61
  ],
26
62
  properties: [
63
+ {
64
+ displayName: 'Registration',
65
+ name: 'registrationMode',
66
+ type: 'options',
67
+ options: [
68
+ {
69
+ name: 'Manual (paste the URL in the dashboard)',
70
+ value: 'manual',
71
+ description: 'Nothing is created for you; the filtering below happens after delivery',
72
+ },
73
+ {
74
+ name: 'Automatic (create the webhook via the API)',
75
+ value: 'auto',
76
+ description: 'Creates the subscription on activation and deletes it on deactivation, subscribed to the selected event only — so unwanted events are never delivered in the first place. Requires the Pilot Status API credential.',
77
+ },
78
+ ],
79
+ default: 'manual',
80
+ description: 'How the Pilot Status webhook subscription is created. Automatic also moves the event filter SERVER-side.',
81
+ },
27
82
  {
28
83
  displayName: 'Event',
29
84
  name: 'event',
@@ -101,31 +156,142 @@ class PilotStatusTrigger {
101
156
  name: 'Call Permission Updated',
102
157
  value: 'call.permission_updated',
103
158
  },
159
+ {
160
+ name: 'Flow Response Received',
161
+ value: 'flow.response_received',
162
+ // META NUMBERS ONLY, and the failure is SILENT in Automatic mode:
163
+ // the API constrains a webhook's events to what the number's provider
164
+ // can emit by FILTERING the list, not by rejecting it. Picked for a
165
+ // non-Meta number, the subscription is created with an EMPTY event
166
+ // list, HTTP 201, and never fires — so the warning has to live here,
167
+ // where the choice is made.
168
+ description: 'Answers of a submitted WhatsApp Flow. META numbers only: on any other number this subscribes to nothing and the Trigger never fires, with no error at activation. The data wrapper names the number whatsappNumberId, NOT numberId. On a Flow with a data_exchange endpoint the answers are in data.submitted, NOT in data.response — see the payload notice below before mapping anything.',
169
+ },
104
170
  ],
105
171
  default: '*',
106
172
  description: 'The event to listen to',
107
173
  },
174
+ {
175
+ displayName: 'Signing Secret',
176
+ name: 'signingSecret',
177
+ type: 'string',
178
+ typeOptions: { password: true },
179
+ default: '',
180
+ description: 'The webhook signing secret, shown ONCE in the dashboard when the webhook is created. When filled in, every delivery whose x-pilot-status-signature does not match is rejected with 401. Leave empty to accept unsigned deliveries — but then anyone who learns this URL can fire this workflow. The API never returns the secret, not even on create, so it cannot be filled in automatically.',
181
+ },
108
182
  {
109
183
  displayName: 'Notice: Webhook URL',
110
184
  name: 'notice',
111
185
  type: 'notice',
112
186
  default: '',
113
- description: 'Copy the Webhook URL from the side panel and paste it in the Pilot Status Dashboard under Webhooks.',
187
+ description: 'Copy the Webhook URL from the side panel and paste it in the Pilot Status Dashboard under Webhooks. Not needed in Automatic registration.',
114
188
  },
115
189
  {
116
190
  displayName: 'Notice: Payload shape',
117
191
  name: 'payloadNotice',
118
192
  type: 'notice',
119
193
  default: '',
120
- description: 'The full JSON body is passed through (event + data). Phones are E.164 with a leading "+"; message.* events carry from/to/numberId/id/messageId/type/createdAt and may include an optional correlationId. message.reply adds contentReplied and quotedMessageId. call.* events (WhatsApp Business Calling — Meta Cloud API and web/Pilot Status numbers; call.permission_updated is Meta-only) are FLAT — fields sit next to event with no data wrapper: { event, callId, externalCallId?, direction, status, from, to, timestamp, duration? }. externalCallId is the provider call id (Meta wacid or Evolution GO CallID). On every number.* event, data.numberId is the WhatsApp NUMBER id — the same id GET /v1/numbers returns and the other number operations take. It used to carry the underlying instance id on number.created/connected/removed, so a workflow that stored that value and matched later events against it never matched.',
194
+ description: 'The full JSON body is passed through (event + data). Phones are E.164 with a leading "+"; message.* events carry from/to/numberId/id/messageId/type/createdAt and may include an optional correlationId. message.reply adds contentReplied and quotedMessageId. call.* events (WhatsApp Business Calling — Meta Cloud API and web/Pilot Status numbers; call.permission_updated is Meta-only) are FLAT — fields sit next to event with no data wrapper: { event, callId, externalCallId?, direction, status, from, to, timestamp, duration? }. externalCallId is the provider call id (Meta wacid or Evolution GO CallID). On every number.* event, data.numberId is the WhatsApp NUMBER id — the same id GET /v1/numbers returns and the other number operations take. It used to carry the underlying instance id on number.created/connected/removed, so a workflow that stored that value and matched later events against it never matched. flow.response_received (Meta numbers only) carries the submitted Flow answers under data: { event, flowId, metaFlowId, flowToken, messageId, whatsappNumberId, from, receivedAt, response, responseRaw, flowMedia, submitted }. Its number field is whatsappNumberId, NOT numberId — same value, different name, so a mapping copied from a message.* branch reads undefined. response and responseRaw are mutually exclusive: response holds what YOUR OWN Flow endpoint returned, already parsed, and responseRaw carries the raw bytes from Meta ONLY when that parse failed. 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 submitted and flowMedia 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.',
121
195
  },
122
196
  ],
123
197
  };
198
+ this.webhookMethods = {
199
+ default: {
200
+ async checkExists() {
201
+ if (this.getNodeParameter('registrationMode') !== 'auto')
202
+ return true;
203
+ const data = this.getWorkflowStaticData('node');
204
+ if (!data.webhookId)
205
+ return false;
206
+ // A GET instead of trusting the stored id: someone may have deleted
207
+ // the subscription from the dashboard, and then `create` has to run
208
+ // again.
209
+ try {
210
+ await this.helpers.requestWithAuthentication.call(this, 'pilotStatusApi', {
211
+ method: 'GET',
212
+ baseURL: await apiBaseUrl(this),
213
+ url: `/webhooks/${data.webhookId}`,
214
+ json: true,
215
+ });
216
+ return true;
217
+ }
218
+ catch {
219
+ delete data.webhookId;
220
+ return false;
221
+ }
222
+ },
223
+ async create() {
224
+ var _a;
225
+ if (this.getNodeParameter('registrationMode') !== 'auto')
226
+ return true;
227
+ const event = this.getNodeParameter('event');
228
+ const created = (await this.helpers.requestWithAuthentication.call(this, 'pilotStatusApi', {
229
+ method: 'POST',
230
+ baseURL: await apiBaseUrl(this),
231
+ url: '/webhooks',
232
+ body: {
233
+ url: this.getNodeWebhookUrl('default'),
234
+ name: `n8n: ${(_a = this.getWorkflow().name) !== null && _a !== void 0 ? _a : 'workflow'}`,
235
+ // Subscribes to ONLY the selected event: the filter stops
236
+ // being a post-delivery one and becomes a real subscription.
237
+ events: [event],
238
+ },
239
+ json: true,
240
+ }));
241
+ if (!(created === null || created === void 0 ? void 0 : created.id))
242
+ return false;
243
+ this.getWorkflowStaticData('node').webhookId = created.id;
244
+ return true;
245
+ },
246
+ async delete() {
247
+ if (this.getNodeParameter('registrationMode') !== 'auto')
248
+ return true;
249
+ const data = this.getWorkflowStaticData('node');
250
+ if (!data.webhookId)
251
+ return true;
252
+ try {
253
+ await this.helpers.requestWithAuthentication.call(this, 'pilotStatusApi', {
254
+ method: 'DELETE',
255
+ baseURL: await apiBaseUrl(this),
256
+ url: `/webhooks/${data.webhookId}`,
257
+ json: true,
258
+ });
259
+ }
260
+ catch {
261
+ // It no longer exists on the server side: dropping the local id
262
+ // anyway is what avoids resurrecting a ghost subscription on the
263
+ // next activation.
264
+ }
265
+ delete data.webhookId;
266
+ return true;
267
+ },
268
+ },
269
+ };
124
270
  }
125
271
  async webhook() {
126
272
  const req = this.getRequestObject();
127
273
  const event = this.getNodeParameter('event');
274
+ const secret = this.getNodeParameter('signingSecret', '') || '';
128
275
  const bodyData = req.body;
276
+ if (secret) {
277
+ // The RAW body, not `JSON.stringify(req.body)`: the HMAC is over the
278
+ // bytes that left the dispatcher, and re-serializing changes escapes
279
+ // and ordering.
280
+ if (typeof req.readRawBody === 'function')
281
+ await req.readRawBody();
282
+ const rawBody = req.rawBody;
283
+ const signature = req.headers[exports.SIGNATURE_HEADER];
284
+ // Fails CLOSED: without the raw body no verification is possible, and
285
+ // accepting anyway would turn the secret field into theatre.
286
+ if (!Buffer.isBuffer(rawBody) || typeof signature !== 'string' || !isValidSignature(rawBody, signature, secret)) {
287
+ return {
288
+ webhookResponse: {
289
+ status: 401,
290
+ body: 'Invalid signature',
291
+ },
292
+ };
293
+ }
294
+ }
129
295
  if (event !== '*' && bodyData.event !== event) {
130
296
  return {
131
297
  webhookResponse: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-nodes-pilot-status",
3
- "version": "1.3.0",
3
+ "version": "2.2.0",
4
4
  "description": "n8n node for Pilot Status API",
5
5
  "keywords": [
6
6
  "n8ncommunity",
@@ -18,7 +18,8 @@
18
18
  "prepublishOnly": "npm run build"
19
19
  },
20
20
  "files": [
21
- "dist"
21
+ "dist",
22
+ "CHANGELOG.md"
22
23
  ],
23
24
  "n8n": {
24
25
  "n8nNodesApiVersion": 1,
@@ -40,4 +41,4 @@
40
41
  "ts-jest": "^29.4.6",
41
42
  "typescript": "^5.0.0"
42
43
  }
43
- }
44
+ }