207 linhas
7,9 KiB
TypeScript
207 linhas
7,9 KiB
TypeScript
// Generated from the OpenAPI specification. Do not edit by hand: regenerate.
|
|
import { createHmac, timingSafeEqual } from 'crypto';
|
|
import type {
|
|
IDataObject,
|
|
IHookFunctions,
|
|
IHttpRequestMethods,
|
|
IHttpRequestOptions,
|
|
INodeType,
|
|
INodeTypeDescription,
|
|
IWebhookFunctions,
|
|
IWebhookResponseData,
|
|
} from 'n8n-workflow';
|
|
import { NodeConnectionTypes, NodeOperationError } from 'n8n-workflow';
|
|
|
|
async function apiRequest(this: IHookFunctions, method: IHttpRequestMethods, path: string, body?: IDataObject): Promise<IDataObject> {
|
|
const c = await this.getCredentials('mozOutMzApi');
|
|
const base = String(c.baseUrl || 'https://api.mozout.co.mz').replace(/\/+$/, '');
|
|
const options: IHttpRequestOptions = {
|
|
method,
|
|
url: base + path,
|
|
headers: { Accept: 'application/json' },
|
|
json: true,
|
|
};
|
|
if (body) options.body = body;
|
|
return (await this.helpers.httpRequestWithAuthentication.call(this, 'mozOutMzApi', options)) as IDataObject;
|
|
}
|
|
|
|
/** X-Webhook-Signature: t=<unix>,v1=<hex>, HMAC-SHA256 of t + "." + raw body. */
|
|
function verifySignature(raw: Buffer, header: string, secret: string, tolerance: number): boolean {
|
|
let t = '';
|
|
const v1: string[] = [];
|
|
for (const item of header.split(',')) {
|
|
const i = item.indexOf('=');
|
|
if (i <= 0) continue;
|
|
const k = item.slice(0, i).trim();
|
|
const v = item.slice(i + 1).trim();
|
|
if (k === 't' && !t) t = v;
|
|
if (k === 'v1') v1.push(v);
|
|
}
|
|
if (!/^\d+$/.test(t)) return false;
|
|
if (tolerance > 0 && Math.abs(Date.now() / 1000 - Number(t)) > tolerance) return false;
|
|
const expected = createHmac('sha256', secret).update(Buffer.concat([Buffer.from(`${t}.`, 'utf8'), raw])).digest('hex');
|
|
return v1.some((s) => s.length === expected.length && timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
|
|
}
|
|
|
|
export class MozOutMzTrigger implements INodeType {
|
|
description: INodeTypeDescription = {
|
|
displayName: 'MozOut Mozambique Trigger',
|
|
name: 'mozOutMzTrigger',
|
|
icon: 'file:mozout-mz.svg',
|
|
group: ['trigger'],
|
|
version: 1,
|
|
subtitle: '={{($parameter["events"] || []).join(", ")}}',
|
|
description: 'Starts the workflow when the account sends an event: domains, services, SMS deliveries and the reseller program',
|
|
defaults: { name: 'MozOut Mozambique Trigger' },
|
|
inputs: [],
|
|
outputs: [NodeConnectionTypes.Main],
|
|
credentials: [{ name: 'mozOutMzApi', required: true }],
|
|
webhooks: [{ name: 'default', httpMethod: 'POST', responseMode: 'onReceived', path: 'webhook' }],
|
|
properties: [
|
|
{
|
|
displayName:
|
|
'The account has one webhook address, shared with the SMS delivery events. Activating this workflow saves the n8n address there and replaces the one before. n8n must be reachable over HTTPS on port 443.',
|
|
name: 'notice',
|
|
type: 'notice',
|
|
default: '',
|
|
},
|
|
{
|
|
displayName: 'Events',
|
|
name: 'events',
|
|
type: 'multiOptions',
|
|
required: true,
|
|
default: [],
|
|
options: [
|
|
{
|
|
"name": "sms.sent",
|
|
"value": "sms.sent",
|
|
"description": "An SMS was delivered to the network"
|
|
},
|
|
{
|
|
"name": "sms.failed",
|
|
"value": "sms.failed",
|
|
"description": "An SMS failed"
|
|
},
|
|
{
|
|
"name": "reseller.credit_low",
|
|
"value": "reseller.credit_low",
|
|
"description": "Reseller credit is low"
|
|
},
|
|
{
|
|
"name": "reseller.level_changed",
|
|
"value": "reseller.level_changed",
|
|
"description": "The Agency changed"
|
|
},
|
|
{
|
|
"name": "domain.registered",
|
|
"value": "domain.registered",
|
|
"description": "Domain registered"
|
|
},
|
|
{
|
|
"name": "domain.registration_failed",
|
|
"value": "domain.registration_failed",
|
|
"description": "Domain registration failed"
|
|
},
|
|
{
|
|
"name": "service.created",
|
|
"value": "service.created",
|
|
"description": "Service created"
|
|
}
|
|
],
|
|
description: 'The events that start this workflow',
|
|
},
|
|
{
|
|
displayName: 'Options',
|
|
name: 'options',
|
|
type: 'collection',
|
|
placeholder: 'Add Option',
|
|
default: {},
|
|
options: [
|
|
{
|
|
displayName: 'Check Signature',
|
|
name: 'checkSignature',
|
|
type: 'boolean',
|
|
default: true,
|
|
description: 'Whether to refuse events without a valid X-Webhook-Signature',
|
|
},
|
|
{
|
|
displayName: 'Tolerance (Seconds)',
|
|
name: 'tolerance',
|
|
type: 'number',
|
|
default: 300,
|
|
description: 'Refuse signatures older than this',
|
|
},
|
|
],
|
|
},
|
|
],
|
|
};
|
|
|
|
webhookMethods = {
|
|
default: {
|
|
async checkExists(this: IHookFunctions): Promise<boolean> {
|
|
const url = this.getNodeWebhookUrl('default');
|
|
const staticData = this.getWorkflowStaticData('node');
|
|
try {
|
|
const res = await apiRequest.call(this, 'GET', '/v1/webhooks');
|
|
const w = (res.data || {}) as IDataObject;
|
|
if (w.url !== url || !staticData.secret) return false;
|
|
const wanted = this.getNodeParameter('events', []) as string[];
|
|
const saved = (w.events || []) as string[];
|
|
return wanted.length === saved.length && wanted.every((e) => saved.includes(e));
|
|
} catch (error) {
|
|
return false;
|
|
}
|
|
},
|
|
async create(this: IHookFunctions): Promise<boolean> {
|
|
const url = this.getNodeWebhookUrl('default');
|
|
const events = this.getNodeParameter('events', []) as string[];
|
|
if (!events.length) throw new NodeOperationError(this.getNode(), 'Choose at least one event.');
|
|
const res = await apiRequest.call(this, 'PUT', '/v1/webhooks', { url, events, rotate_secret: true });
|
|
const secret = ((res.data || {}) as IDataObject).secret;
|
|
if (!secret) throw new NodeOperationError(this.getNode(), 'The API did not return the webhook secret.');
|
|
const staticData = this.getWorkflowStaticData('node');
|
|
staticData.secret = String(secret);
|
|
staticData.url = url;
|
|
return true;
|
|
},
|
|
async delete(this: IHookFunctions): Promise<boolean> {
|
|
const url = this.getNodeWebhookUrl('default');
|
|
const staticData = this.getWorkflowStaticData('node');
|
|
try {
|
|
const res = await apiRequest.call(this, 'GET', '/v1/webhooks');
|
|
if (((res.data || {}) as IDataObject).url === url) {
|
|
await apiRequest.call(this, 'DELETE', '/v1/webhooks');
|
|
}
|
|
} catch (error) {
|
|
return false;
|
|
}
|
|
delete staticData.secret;
|
|
delete staticData.url;
|
|
return true;
|
|
},
|
|
},
|
|
};
|
|
|
|
async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
|
|
const options = this.getNodeParameter('options', {}) as IDataObject;
|
|
const body = this.getBodyData() as IDataObject;
|
|
if (options.checkSignature !== false) {
|
|
const secret = String(this.getWorkflowStaticData('node').secret || '');
|
|
const req = this.getRequestObject() as unknown as { rawBody?: Buffer };
|
|
const header = String(this.getHeaderData()['x-webhook-signature'] || '');
|
|
const raw = req.rawBody ?? Buffer.from(JSON.stringify(body));
|
|
const tolerance = options.tolerance === undefined ? 300 : Number(options.tolerance);
|
|
if (!secret || !verifySignature(raw, header, secret, tolerance)) {
|
|
const res = this.getResponseObject();
|
|
res.status(401).json({ error: 'invalid_signature' });
|
|
return { noWebhookResponse: true };
|
|
}
|
|
}
|
|
const events = this.getNodeParameter('events', []) as string[];
|
|
const event = String(body.event || '');
|
|
if (event && event !== 'webhook.test' && events.length && !events.includes(event)) {
|
|
return { webhookResponse: { received: true, ignored: true } };
|
|
}
|
|
return { workflowData: [this.helpers.returnJsonArray(body)] };
|
|
}
|
|
}
|