From 6479eb180ff9a43791b5211157f5c450e1463ffd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E0=A4=95=E0=A4=BE=E0=A4=B0=E0=A4=A4=E0=A5=8B=E0=A4=AB?= =?UTF-8?q?=E0=A5=8D=E0=A4=AB=E0=A5=87=E0=A4=B2=E0=A4=B8=E0=A5=8D=E0=A4=95?= =?UTF-8?q?=E0=A5=8D=E0=A4=B0=E0=A4=BF=E0=A4=AA=E0=A5=8D=E0=A4=9F=E2=84=A2?= Date: Tue, 10 Oct 2023 15:19:05 +0200 Subject: [PATCH] fix(Webhook Node): Backward compatible form-data parsing for non-array files (#7385) Fixes https://community.n8n.io/t/possible-bug-0-added-to-end-of-files-sent-via-webhook/31169 --- packages/cli/src/WebhookHelpers.ts | 16 +++++++++++----- .../cli/test/integration/webhooks.api.test.ts | 19 ++++++++++--------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/packages/cli/src/WebhookHelpers.ts b/packages/cli/src/WebhookHelpers.ts index bd3f1d156b974..cea4ae21af58d 100644 --- a/packages/cli/src/WebhookHelpers.ts +++ b/packages/cli/src/WebhookHelpers.ts @@ -190,6 +190,15 @@ export function encodeWebhookResponse( return response; } +const normalizeFormData = (values: Record) => { + for (const key in values) { + const value = values[key]; + if (Array.isArray(value) && value.length === 1) { + values[key] = value[0]; + } + } +}; + /** * Executes a webhook */ @@ -310,11 +319,8 @@ export async function executeWebhook( }); req.body = await new Promise((resolve) => { form.parse(req, async (err, data, files) => { - for (const key in data) { - if (Array.isArray(data[key]) && data[key].length === 1) { - data[key] = data[key][0]; - } - } + normalizeFormData(data); + normalizeFormData(files); resolve({ data, files }); }); }); diff --git a/packages/cli/test/integration/webhooks.api.test.ts b/packages/cli/test/integration/webhooks.api.test.ts index a5ec923f836f3..37ac3358ea259 100644 --- a/packages/cli/test/integration/webhooks.api.test.ts +++ b/packages/cli/test/integration/webhooks.api.test.ts @@ -116,20 +116,21 @@ describe('Webhook API', () => { .field('field1', 'value1') .field('field2', 'value2') .field('field2', 'value3') - .attach('file', Buffer.from('random-text')) + .attach('file1', Buffer.from('random-text')) + .attach('file2', Buffer.from('random-text')) + .attach('file2', Buffer.from('random-text')) .set('content-type', 'multipart/form-data'); expect(response.statusCode).toEqual(200); expect(response.body.type).toEqual('multipart/form-data'); - const { - data, - files: { - file: [file], - }, - } = response.body.body; + const { data, files } = response.body.body; expect(data).toEqual({ field1: 'value1', field2: ['value2', 'value3'] }); - expect(file.mimetype).toEqual('application/octet-stream'); - expect(readFileSync(file.filepath, 'utf-8')).toEqual('random-text'); + + expect(files.file1).not.toBeInstanceOf(Array); + expect(files.file1.mimetype).toEqual('application/octet-stream'); + expect(readFileSync(files.file1.filepath, 'utf-8')).toEqual('random-text'); + expect(files.file2).toBeInstanceOf(Array); + expect(files.file2.length).toEqual(2); }); });