224 lines
9.5 KiB
JavaScript
224 lines
9.5 KiB
JavaScript
'use strict';
|
|
|
|
// Tests without installing anything: a small stand-in for the Zapier "z" object.
|
|
// Offline checks always run. Live checks run only with TEST_API_KEY (a sandbox_ key) and TEST_API_URL.
|
|
// TEST_API_URL=https://api.example.test TEST_API_KEY=sandbox_... node test/run.js
|
|
|
|
const assert = require('assert');
|
|
const crypto = require('crypto');
|
|
const https = require('https');
|
|
const Module = require('module');
|
|
|
|
// zapier-platform-core is not installed here: answer its version only.
|
|
const load = Module._load;
|
|
Module._load = function (request, parent, isMain) {
|
|
if (request === 'zapier-platform-core') return { version: '15.19.0' };
|
|
return load.apply(this, arguments);
|
|
};
|
|
|
|
const config = require('../lib/config');
|
|
const app = require('../index');
|
|
const hooks = require('../lib/hooks');
|
|
const { compact, toList } = require('../lib/http');
|
|
|
|
class ZError extends Error {
|
|
constructor(message, code, status) {
|
|
super(message);
|
|
this.code = code;
|
|
this.status = status;
|
|
}
|
|
}
|
|
class Throttled extends Error {
|
|
constructor(message, delay) {
|
|
super(message);
|
|
this.delay = delay;
|
|
}
|
|
}
|
|
|
|
const makeZ = (bundle) => {
|
|
const z = {
|
|
errors: { Error: ZError, ThrottledError: Throttled, ExpiredAuthError: ZError },
|
|
request: (req) =>
|
|
new Promise((resolve, reject) => {
|
|
app.beforeRequest.forEach((fn) => fn(req, z, bundle));
|
|
const url = new URL(req.url);
|
|
Object.keys(req.params || {}).forEach((k) => {
|
|
if (req.params[k] !== undefined) url.searchParams.set(k, req.params[k]);
|
|
});
|
|
const body = req.body !== undefined ? JSON.stringify(req.body) : null;
|
|
const r = https.request(url, { method: req.method || 'GET', headers: req.headers }, (res) => {
|
|
let content = '';
|
|
res.on('data', (c) => (content += c));
|
|
res.on('end', () => {
|
|
let data;
|
|
try {
|
|
data = JSON.parse(content);
|
|
} catch (e) {
|
|
data = undefined;
|
|
}
|
|
const response = { status: res.statusCode, content, data, getHeader: (h) => res.headers[h.toLowerCase()] };
|
|
try {
|
|
app.afterResponse.forEach((fn) => fn(response, z, bundle));
|
|
resolve(response);
|
|
} catch (e) {
|
|
reject(e);
|
|
}
|
|
});
|
|
});
|
|
r.on('error', reject);
|
|
if (body) r.write(body);
|
|
r.end();
|
|
}),
|
|
};
|
|
return z;
|
|
};
|
|
|
|
const results = [];
|
|
const check = async (name, fn) => {
|
|
try {
|
|
await fn();
|
|
results.push(['ok', name]);
|
|
} catch (e) {
|
|
results.push(['FAIL', name + ': ' + e.message]);
|
|
}
|
|
};
|
|
|
|
(async () => {
|
|
// Offline
|
|
await check('app shape', () => {
|
|
assert.strictEqual(app.version, '1.0.0');
|
|
assert.deepStrictEqual(Object.keys(app.creates).sort(), ['add_email_contact', 'create_dns_record', 'send_email', 'send_sms']);
|
|
assert.deepStrictEqual(Object.keys(app.searches).sort(), ['domain_availability', 'whois']);
|
|
['account_event', 'email_event'].forEach((k) => {
|
|
const op = app.triggers[k].operation;
|
|
assert.strictEqual(op.type, 'hook');
|
|
['performSubscribe', 'performUnsubscribe', 'perform', 'performList'].forEach((f) => assert.strictEqual(typeof op[f], 'function'));
|
|
});
|
|
Object.values(app.creates).forEach((c) =>
|
|
c.operation.inputFields.forEach((f) => {
|
|
if (f.dynamic) assert.ok(app.triggers[f.dynamic.split('.')[0]], 'dropdown ' + f.dynamic);
|
|
})
|
|
);
|
|
});
|
|
await check('compact and toList', () => {
|
|
assert.deepStrictEqual(compact({ a: '', b: null, c: [], d: {}, e: 0, f: 'x' }), { e: 0, f: 'x' });
|
|
assert.deepStrictEqual(toList('a@x.co, b@y.co'), ['a@x.co', 'b@y.co']);
|
|
assert.strictEqual(toList(''), undefined);
|
|
});
|
|
await check('webhook signature', () => {
|
|
const secret = 'whsec_test';
|
|
const raw = '{"event":"sms.sent","created_at":"2026-11-27T10:00:00+02:00","data":{"id":"1"}}';
|
|
const t = Math.floor(Date.now() / 1000);
|
|
const v1 = crypto.createHmac('sha256', secret).update(t + '.' + raw).digest('hex');
|
|
assert.ok(hooks.signatureIsValid(secret, raw, 't=' + t + ',v1=' + v1, 300));
|
|
assert.ok(!hooks.signatureIsValid(secret, raw + ' ', 't=' + t + ',v1=' + v1, 300));
|
|
assert.ok(!hooks.signatureIsValid(secret, raw, 't=' + (t - 1000) + ',v1=' + v1, 300));
|
|
const bundle = {
|
|
inputData: { events: ['sms.sent'] },
|
|
subscribeData: { secret },
|
|
cleanedRequest: JSON.parse(raw),
|
|
rawRequest: { content: raw, headers: { 'Http-X-Webhook-Signature': 't=' + t + ',v1=' + v1 } },
|
|
};
|
|
assert.strictEqual(hooks.receive(makeZ(bundle), bundle).length, 1);
|
|
bundle.rawRequest.headers['Http-X-Webhook-Signature'] = 't=' + t + ',v1=00';
|
|
assert.strictEqual(hooks.receive(makeZ(bundle), bundle).length, 0);
|
|
bundle.subscribeData = {};
|
|
bundle.inputData.events = ['sms.failed'];
|
|
assert.strictEqual(hooks.receive(makeZ(bundle), bundle).length, 0);
|
|
});
|
|
|
|
// Live, against a Sandbox key
|
|
const key = process.env.TEST_API_KEY;
|
|
if (key && process.env.TEST_API_URL) {
|
|
config.API_URL = process.env.TEST_API_URL.replace(/\/+$/, '');
|
|
const bundle = (inputData) => ({ authData: { apiKey: key }, inputData: inputData || {}, meta: {} });
|
|
const run = (op, inputData) => {
|
|
const b = bundle(inputData);
|
|
return op(makeZ(b), b);
|
|
};
|
|
await check('live: auth test', async () => {
|
|
const d = await run(app.authentication.test);
|
|
assert.strictEqual(d.mode, 'sandbox', 'use a sandbox_ key for tests');
|
|
assert.ok(app.authentication.connectionLabel({}, { inputData: d }));
|
|
});
|
|
await check('live: bad key gives a clear 401', async () => {
|
|
const b = { authData: { apiKey: 'sandbox_invalid' }, inputData: {} };
|
|
await assert.rejects(app.authentication.test(makeZ(b), b), /not valid/);
|
|
});
|
|
await check('live: whois', async () => {
|
|
const r = await run(app.searches.whois.operation.perform, { domain: 'https://www.example.co.ao/', language: 'en' });
|
|
assert.strictEqual(r[0].domain, 'example.co.ao');
|
|
assert.ok(['available', 'registered', 'unknown'].indexOf(r[0].status) !== -1);
|
|
});
|
|
await check('live: whois unsupported extension', async () => {
|
|
await assert.rejects(run(app.searches.whois.operation.perform, { domain: 'example.zzqq' }), /extension_not_supported|not available/);
|
|
});
|
|
await check('live: availability', async () => {
|
|
const r = await run(app.searches.domain_availability.operation.perform, { domain: 'example.co.ao' });
|
|
assert.strictEqual(r[0].domain, 'example.co.ao');
|
|
});
|
|
await check('live: dropdowns', async () => {
|
|
const s = await run(app.triggers.sms_sender_list.operation.perform);
|
|
assert.ok(Array.isArray(s) && s.length >= 1);
|
|
assert.ok(Array.isArray(await run(app.triggers.email_group_list.operation.perform)));
|
|
assert.ok(Array.isArray(await run(app.triggers.domain_list.operation.perform)));
|
|
});
|
|
await check('live: send SMS (simulated)', async () => {
|
|
const r = await run(app.creates.send_sms.operation.perform, { number: '923123456', text: 'Zapier app test.' });
|
|
assert.ok(r.id && r.simulated === true, JSON.stringify(r).slice(0, 200));
|
|
});
|
|
await check('live: send SMS invalid number gives 422', async () => {
|
|
await assert.rejects(run(app.creates.send_sms.operation.perform, { number: '12', text: 'x' }), (e) => e.status === 422);
|
|
});
|
|
await check('live: send email (simulated or clear error)', async () => {
|
|
try {
|
|
const r = await run(app.creates.send_email.operation.perform, {
|
|
from: process.env.TEST_EMAIL_FROM || 'noreply@example.com',
|
|
to: 'joao.fernandes@example.com',
|
|
subject: 'Zapier app test',
|
|
text: 'Hello.',
|
|
});
|
|
assert.ok(r.id, JSON.stringify(r).slice(0, 200));
|
|
} catch (e) {
|
|
assert.ok(e.status === 422 || e.status === 403, e.message);
|
|
}
|
|
});
|
|
await check('live: add contact (simulated)', async () => {
|
|
const r = await run(app.creates.add_email_contact.operation.perform, { email: 'zapier-test@example.com', name: 'João Fernandes' });
|
|
assert.ok(r, 'empty answer');
|
|
});
|
|
await check('live: DNS record (simulated or clear error)', async () => {
|
|
try {
|
|
const r = await run(app.creates.create_dns_record.operation.perform, {
|
|
domain: process.env.TEST_DNS_DOMAIN || 'example.co.ao',
|
|
type: 'TXT',
|
|
name: 'zapier-test',
|
|
value: 'zapier-app-test',
|
|
});
|
|
assert.ok(r, 'empty answer');
|
|
} catch (e) {
|
|
assert.ok([403, 404, 409, 422].indexOf(e.status) !== -1, e.message);
|
|
}
|
|
});
|
|
await check('live: webhook subscribe and unsubscribe (simulated)', async () => {
|
|
const op = app.triggers.account_event.operation;
|
|
const b = bundle({ events: ['domain.registered'] });
|
|
b.targetUrl = 'https://hooks.zapier.com/hooks/standard/0/test/';
|
|
const sub = await op.performSubscribe(makeZ(b), b);
|
|
assert.strictEqual(sub.url, b.targetUrl);
|
|
assert.deepStrictEqual(sub.events, ['domain.registered']);
|
|
b.subscribeData = sub;
|
|
const un = await op.performUnsubscribe(makeZ(b), b);
|
|
assert.strictEqual(typeof un.deleted, 'boolean');
|
|
});
|
|
await check('live: sample lists', async () => {
|
|
assert.ok((await run(app.triggers.account_event.operation.performList, {})).length >= 1);
|
|
assert.ok((await run(app.triggers.email_event.operation.performList, {})).length >= 1);
|
|
});
|
|
} else {
|
|
results.push(['skip', 'live checks (set TEST_API_URL and TEST_API_KEY)']);
|
|
}
|
|
|
|
results.forEach((r) => console.log(r[0].padEnd(5), r[1]));
|
|
process.exit(results.some((r) => r[0] === 'FAIL') ? 1 : 0);
|
|
})();
|