103 lines
3.7 KiB
JavaScript
103 lines
3.7 KiB
JavaScript
'use strict';
|
|
|
|
const crypto = require('crypto');
|
|
const { api } = require('./http');
|
|
|
|
// The API keeps one webhook address per account for each kind of notification.
|
|
// A Zap only takes it over when it is empty, and only removes it when it is still its own.
|
|
|
|
const hostOf = (url) => {
|
|
try {
|
|
return new URL(url).host;
|
|
} catch (e) {
|
|
return 'another address';
|
|
}
|
|
};
|
|
|
|
const subscribe = (path, defaultEvents) => async (z, bundle) => {
|
|
const events = (bundle.inputData.events && bundle.inputData.events.length ? bundle.inputData.events : defaultEvents).slice();
|
|
const current = await api(z, { path });
|
|
if (current && current.url && current.url !== bundle.targetUrl) {
|
|
throw new z.errors.Error(
|
|
'This account already sends these notifications to ' + hostOf(current.url) +
|
|
'. The API keeps one address per account, so this Zap would replace it. ' +
|
|
'Remove that webhook first (DELETE ' + path + ' or turn off the other Zap), then turn this Zap on again.',
|
|
'webhook_in_use',
|
|
409
|
|
);
|
|
}
|
|
const saved = await api(z, {
|
|
method: 'PUT',
|
|
path,
|
|
body: { url: bundle.targetUrl, events, rotate_secret: true },
|
|
});
|
|
return {
|
|
url: bundle.targetUrl,
|
|
events,
|
|
secret: saved && saved.secret ? saved.secret : null,
|
|
simulated: Boolean(saved && saved.simulated),
|
|
};
|
|
};
|
|
|
|
const unsubscribe = (path) => async (z, bundle) => {
|
|
const ours = bundle.subscribeData && bundle.subscribeData.url;
|
|
const current = await api(z, { path });
|
|
if (!current || !current.url || (ours && current.url !== ours)) {
|
|
return { deleted: false };
|
|
}
|
|
await api(z, { method: 'DELETE', path });
|
|
return { deleted: true };
|
|
};
|
|
|
|
const findHeader = (headers, name) => {
|
|
const wanted = name.toLowerCase();
|
|
const keys = Object.keys(headers || {});
|
|
for (let i = 0; i < keys.length; i++) {
|
|
const k = keys[i].toLowerCase().replace(/^http-/, '');
|
|
if (k === wanted) return headers[keys[i]];
|
|
}
|
|
return null;
|
|
};
|
|
|
|
// X-Webhook-Signature: t=<unix time>,v1=<hex>; v1 = HMAC-SHA256(secret, t + "." + raw body).
|
|
const signatureIsValid = (secret, raw, header, toleranceSeconds) => {
|
|
const parts = {};
|
|
String(header || '')
|
|
.split(',')
|
|
.forEach((p) => {
|
|
const i = p.indexOf('=');
|
|
if (i > 0) parts[p.slice(0, i).trim()] = p.slice(i + 1).trim();
|
|
});
|
|
const t = parseInt(parts.t, 10);
|
|
if (!t || !parts.v1 || !/^[0-9a-f]+$/i.test(parts.v1)) return false;
|
|
if (Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
|
|
const expected = crypto.createHmac('sha256', secret).update(t + '.' + raw).digest('hex');
|
|
const a = Buffer.from(expected, 'hex');
|
|
const b = Buffer.from(parts.v1, 'hex');
|
|
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
};
|
|
|
|
const toItem = (body) => {
|
|
const data = body.data || {};
|
|
const id = data.event_id || [body.event, data.id || data.service_id || data.domain || '', body.created_at || ''].join(':');
|
|
return Object.assign({ id: String(id), event: body.event, created_at: body.created_at }, { data });
|
|
};
|
|
|
|
// Runs when a notification arrives. Checks the signature when the secret and the raw body are there.
|
|
const receive = (z, bundle) => {
|
|
const body = bundle.cleanedRequest || {};
|
|
const secret = bundle.subscribeData && bundle.subscribeData.secret;
|
|
const raw = bundle.rawRequest && bundle.rawRequest.content;
|
|
if (secret && raw) {
|
|
const header = findHeader(bundle.rawRequest.headers, 'X-Webhook-Signature');
|
|
if (!signatureIsValid(secret, raw, header, 300)) {
|
|
return [];
|
|
}
|
|
}
|
|
if (!body.event) return [];
|
|
const chosen = bundle.inputData.events;
|
|
if (chosen && chosen.length && chosen.indexOf(body.event) === -1) return [];
|
|
return [toItem(body)];
|
|
};
|
|
|
|
module.exports = { subscribe, unsubscribe, receive, toItem, signatureIsValid };
|