n8n/packages/nodes-base/nodes/Webhook.node.ts

449 lines
11 KiB
TypeScript
Raw Normal View History

2019-06-23 03:35:23 -07:00
import {
2020-03-20 14:47:47 -07:00
BINARY_ENCODING,
2019-06-23 03:35:23 -07:00
IWebhookFunctions,
} from 'n8n-core';
import {
IDataObject,
2019-12-21 17:03:24 -08:00
INodeExecutionData,
2019-06-23 03:35:23 -07:00
INodeTypeDescription,
INodeType,
IWebhookResponseData,
2019-06-23 03:35:23 -07:00
} from 'n8n-workflow';
import * as basicAuth from 'basic-auth';
import { Response } from 'express';
2020-02-06 08:21:25 -08:00
import { set } from 'lodash';
import * as fs from 'fs';
import * as formidable from 'formidable';
2019-06-23 03:35:23 -07:00
function authorizationError(resp: Response, realm: string, responseCode: number, message?: string) {
if (message === undefined) {
message = 'Authorization problem!';
if (responseCode === 401) {
message = 'Authorization is required!';
} else if (responseCode === 403) {
message = 'Authorization data is wrong!';
}
}
resp.writeHead(responseCode, { 'WWW-Authenticate': `Basic realm="${realm}"` });
resp.end(message);
return {
noWebhookResponse: true,
};
}
export class Webhook implements INodeType {
description: INodeTypeDescription = {
displayName: 'Webhook',
name: 'webhook',
group: ['trigger'],
version: 1,
description: 'Starts the workflow when a webhook got called.',
defaults: {
name: 'Webhook',
color: '#885577',
},
inputs: [],
outputs: ['main'],
credentials: [
{
name: 'httpBasicAuth',
required: true,
displayOptions: {
show: {
authentication: [
'basicAuth',
],
},
},
},
{
name: 'httpHeaderAuth',
required: true,
displayOptions: {
show: {
authentication: [
'headerAuth',
],
},
},
},
],
webhooks: [
{
name: 'default',
httpMethod: '={{$parameter["httpMethod"]}}',
responseCode: '={{$parameter["responseCode"]}}',
2019-08-28 08:16:09 -07:00
responseMode: '={{$parameter["responseMode"]}}',
responseData: '={{$parameter["responseData"]}}',
2019-06-23 03:35:23 -07:00
responseBinaryPropertyName: '={{$parameter["responseBinaryPropertyName"]}}',
responseContentType: '={{$parameter["options"]["responseContentType"]}}',
responsePropertyName: '={{$parameter["options"]["responsePropertyName"]}}',
2019-06-23 03:35:23 -07:00
path: '={{$parameter["path"]}}',
},
],
properties: [
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
name: 'Basic Auth',
value: 'basicAuth'
},
{
name: 'Header Auth',
value: 'headerAuth'
},
{
name: 'None',
value: 'none'
},
],
default: 'none',
description: 'The way to authenticate.',
},
{
displayName: 'HTTP Method',
name: 'httpMethod',
type: 'options',
options: [
{
name: 'GET',
value: 'GET',
},
{
name: 'POST',
value: 'POST',
},
],
default: 'GET',
description: 'The HTTP method to liste to.',
},
{
displayName: 'Path',
name: 'path',
type: 'string',
default: '',
placeholder: 'webhook',
2019-06-23 03:35:23 -07:00
required: true,
description: 'The path to listen to. Slashes("/") in the path are not allowed.',
2019-06-23 03:35:23 -07:00
},
{
displayName: 'Response Code',
name: 'responseCode',
type: 'number',
typeOptions: {
minValue: 100,
maxValue: 599,
},
default: 200,
description: 'The HTTP Response code to return',
},
2019-06-23 03:35:23 -07:00
{
2019-08-28 08:16:09 -07:00
displayName: 'Response Mode',
name: 'responseMode',
2019-06-23 03:35:23 -07:00
type: 'options',
options: [
{
name: 'On Received',
value: 'onReceived',
description: 'Returns directly with defined Response Code',
2019-06-23 03:35:23 -07:00
},
{
name: 'Last Node',
value: 'lastNode',
description: 'Returns data of the last executed node',
},
],
default: 'onReceived',
description: 'When and how to respond to the webhook.',
},
{
2019-08-28 08:16:09 -07:00
displayName: 'Response Data',
name: 'responseData',
2019-06-23 03:35:23 -07:00
type: 'options',
displayOptions: {
show: {
2019-08-28 08:16:09 -07:00
responseMode: [
2019-06-23 03:35:23 -07:00
'lastNode',
],
},
},
options: [
{
name: 'All Entries',
value: 'allEntries',
description: 'Returns all the entries of the last node. Always returns an array.',
},
{
name: 'First Entry JSON',
value: 'firstEntryJson',
description: 'Returns the JSON data of the first entry of the last node. Always returns a JSON object.',
},
{
name: 'First Entry Binary',
value: 'firstEntryBinary',
description: 'Returns the binary data of the first entry of the last node. Always returns a binary file.',
},
],
default: 'firstEntryJson',
description: 'What data should be returned. If it should return<br />all the itemsas array or only the first item as object.',
},
{
displayName: 'Property Name',
name: 'responseBinaryPropertyName',
type: 'string',
required: true,
default: 'data',
displayOptions: {
show: {
2019-08-28 08:16:09 -07:00
responseData: [
2019-06-23 03:35:23 -07:00
'firstEntryBinary'
],
},
},
description: 'Name of the binary property to return',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
options: [
{
displayName: 'Binary Data',
name: 'binaryData',
type: 'boolean',
displayOptions: {
show: {
'/httpMethod': [
'POST',
],
},
},
default: false,
description: 'Set to true if webhook will receive binary data.',
},
{
displayName: 'Binary Property',
name: 'binaryPropertyName',
type: 'string',
default: 'data',
required: true,
displayOptions: {
show: {
binaryData: [
true,
],
},
},
description: 'Name of the binary property to which to<br />write the data of the received file.',
},
{
displayName: 'Response Content-Type',
name: 'responseContentType',
type: 'string',
2019-12-21 17:03:24 -08:00
displayOptions: {
show: {
'/responseData': [
'firstEntryJson',
],
'/responseMode': [
'lastNode',
],
},
},
default: '',
placeholder: 'application/xml',
description: 'Set a custom content-type to return if another one as the "application/json" should be returned.',
},
{
displayName: 'Property Name',
name: 'responsePropertyName',
type: 'string',
2019-12-21 17:03:24 -08:00
displayOptions: {
show: {
'/responseData': [
'firstEntryJson',
],
'/responseMode': [
'lastNode',
],
},
},
default: 'data',
description: 'Name of the property to return the data of instead of the whole JSON.',
},
2019-12-21 12:36:08 -08:00
{
displayName: 'Raw Body',
name: 'rawBody',
type: 'boolean',
displayOptions: {
hide: {
binaryData: [
true,
],
},
},
2019-12-21 12:36:08 -08:00
default: false,
description: 'Raw body (binary)',
},
],
},
2019-06-23 03:35:23 -07:00
],
};
async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
const authentication = this.getNodeParameter('authentication') as string;
const options = this.getNodeParameter('options', {}) as IDataObject;
2019-06-23 03:35:23 -07:00
const req = this.getRequestObject();
const resp = this.getResponseObject();
const headers = this.getHeaderData();
const realm = 'Webhook';
if (authentication === 'basicAuth') {
// Basic authorization is needed to call webhook
const httpBasicAuth = this.getCredentials('httpBasicAuth');
if (httpBasicAuth === undefined || !httpBasicAuth.user || !httpBasicAuth.password) {
// Data is not defined on node so can not authenticate
return authorizationError(resp, realm, 500, 'No authentication data defined on node!');
}
const basicAuthData = basicAuth(req);
if (basicAuthData === undefined) {
// Authorization data is missing
return authorizationError(resp, realm, 401);
}
if (basicAuthData.name !== httpBasicAuth!.user || basicAuthData.pass !== httpBasicAuth!.password) {
// Provided authentication data is wrong
return authorizationError(resp, realm, 403);
}
} else if (authentication === 'headerAuth') {
// Special header with value is needed to call webhook
const httpHeaderAuth = this.getCredentials('httpHeaderAuth');
if (httpHeaderAuth === undefined || !httpHeaderAuth.name || !httpHeaderAuth.value) {
// Data is not defined on node so can not authenticate
return authorizationError(resp, realm, 500, 'No authentication data defined on node!');
}
const headerName = (httpHeaderAuth.name as string).toLowerCase();
const headerValue = (httpHeaderAuth.value as string);
if (!headers.hasOwnProperty(headerName) || (headers as IDataObject)[headerName] !== headerValue) {
// Provided authentication data is wrong
return authorizationError(resp, realm, 403);
}
}
2019-12-21 17:03:24 -08:00
// @ts-ignore
const mimeType = headers['content-type'] || 'application/json';
2020-02-06 08:21:25 -08:00
if (mimeType.includes('multipart/form-data')) {
const form = new formidable.IncomingForm();
return new Promise((resolve, reject) => {
form.parse(req, async (err, data, files) => {
const returnData: INodeExecutionData[] = this.helpers.returnJsonArray({
body: data,
headers,
query: this.getQueryData(),
});
2020-02-06 21:32:55 -08:00
for (const file of Object.keys(files)) {
2020-02-06 08:21:25 -08:00
const fileJson = files[file].toJSON() as IDataObject;
const [fileName, fileExtension] = (fileJson.name as string).split('.');
const fileContent = await fs.promises.readFile(files[file].path);
2020-03-20 12:00:52 -07:00
const buffer = Buffer.from(fileContent);
2020-02-06 08:21:25 -08:00
set(returnData[0], `binary[${fileName}]`, {
2020-03-20 14:47:47 -07:00
data: buffer.toString(BINARY_ENCODING),
2020-02-06 08:21:25 -08:00
mimeType: fileJson.type,
fileName: fileJson.name,
fileExtension,
2020-02-06 21:32:55 -08:00
});
2020-02-06 08:21:25 -08:00
}
resolve({
workflowData: [
returnData,
],
});
});
});
}
2019-12-21 17:03:24 -08:00
if (options.binaryData === true) {
2020-03-20 11:53:51 -07:00
return new Promise((resolve, reject) => {
const binaryPropertyName = options.binaryPropertyName || 'data';
2020-03-20 11:53:51 -07:00
const data: Buffer[] = [];
req.on('data', (chunk) => {
data.push(chunk);
});
req.on('end', async () => {
const returnItem: INodeExecutionData = {
binary: {},
json: {},
};
const returnData: IDataObject[] = [{ json: {} }];
2020-03-20 11:53:51 -07:00
set(returnData[0], `binary[${binaryPropertyName}]`, {
data: Buffer.concat(data).toString(BINARY_ENCODING),
2020-03-20 11:53:51 -07:00
mimeType: req.headers['content-type'],
});
returnItem.binary![binaryPropertyName as string] = await this.helpers.prepareBinaryData(Buffer.concat(data));
2020-03-20 11:53:51 -07:00
return resolve({
workflowData: [
[
returnItem
]
2020-03-20 11:53:51 -07:00
],
});
});
req.on('error', (err) => {
throw new Error(err.message);
});
});
}
2019-12-21 17:03:24 -08:00
const response: INodeExecutionData = {
2019-12-21 12:36:08 -08:00
json: {
2019-06-23 03:35:23 -07:00
body: this.getBodyData(),
headers,
query: this.getQueryData(),
2019-12-21 12:36:08 -08:00
},
};
if (options.rawBody) {
response.binary = {
2019-12-21 17:03:24 -08:00
data: {
// @ts-ignore
2020-03-20 14:47:47 -07:00
data: req.rawBody.toString(BINARY_ENCODING),
2019-12-21 17:03:24 -08:00
mimeType,
}
2019-12-21 12:36:08 -08:00
};
}
2019-06-23 03:35:23 -07:00
return {
workflowData: [
2019-12-21 12:36:08 -08:00
[
response,
],
2019-06-23 03:35:23 -07:00
],
};
}
}