Files
instantadpay/qa/site-invite.test.mjs
T

211 lines
23 KiB
JavaScript

// Sponsor invite emails for other network sites (siteinvite.js, 2026-11-21). No server: the real module with in-memory accounts and
// a capturing mailer on a throwaway dir. node qa/site-invite.test.mjs
// Covers: the signature, directs only, once ever (and a replayed rid), who is never mailed, both daily caps, the pause switch,
// the note and link checks, a failed send can be retried, no email address in any answer, the fixed wording.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const require = createRequire(path.join(SITE, 'package.json'));
delete process.env.DATABASE_URL;
let fails = 0, passes = 0; const ok = (c, l, x) => { console.log((c ? 'PASS ' : 'FAIL ') + l + (x !== undefined && !c ? ' ' + String(typeof x === 'string' ? x : JSON.stringify(x)).slice(0, 500) : '')); if (c) passes++; else fails++; };
const SI = require(path.join(SITE, 'siteinvite.js')), prohibited = require(path.join(SITE, 'prohibited.js'));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'siteinv-'));
// ---- the bench: sponsor "ann" with directs, one level-2 member, and every kind of person who must not be mailed ----
const A = {};
const add = (username, sponsor, x) => { const email = username + '@mail.test'; A[email] = Object.assign({ email, username, sponsorRef: sponsor || '', lastSeen: 1, memberId: 0, joinedVia: null, address: null }, x || {}); return A[email]; };
add('ann', '', { address: '0x' + 'a'.repeat(40) });
for (let i = 1; i <= 30; i++) add('d' + String(i).padStart(2, '0'), 'ann');
add('bob', 'ann'); add('carl', 'bob'); // carl is level 2 under ann
add('optout', 'ann'); add('flagged', 'ann'); add('gone', 'ann'); add('shell', 'ann', { joinedVia: 'hub', lastSeen: 0 }); add('never', 'ann', { lastSeen: 0 });
add('typo', 'ann'); A['typo@mail.test'].email = 'typo@gmial.com'; A['typo@gmial.com'] = A['typo@mail.test']; delete A['typo@mail.test'];
add('zed', ''); for (let i = 1; i <= 3; i++) add('z' + i, 'zed');
const accounts = {
byEmail: async e => A[String(e).toLowerCase()] || null,
byUsername: async u => Object.values(A).find(a => a.username.toLowerCase() === String(u).toLowerCase()) || null,
byAddress: async w => Object.values(A).find(a => a.address === w) || null,
positionByAddress: async () => null,
isUnclaimedShell: a => !!a && ['linkspin', 'btc4hits', 'hub'].includes(a.joinedVia) && !a.lastSeen && !a.memberId,
sponsorOf: async e => { const a = A[String(e).toLowerCase()]; return a && a.sponsorRef ? Object.values(A).find(x => x.username === a.sponsorRef) || null : null; },
async isDownlineOf(s, m, depth = 3) { let cur = String(m).toLowerCase(); for (let i = 0; i < depth; i++) { const sp = await this.sponsorOf(cur); if (!sp) return false; if (sp.email === s) return true; cur = sp.email; } return false; },
downline: async (e, depth) => { const a = A[e]; return a ? [{ level: 1, members: Object.values(A).filter(x => x.sponsorRef === a.username) }] : []; }
};
const sent = []; let failNext = false, unsub = new Set(['optout@mail.test']);
const mailer = { hasKey: () => true, send: async (...args) => { if (failNext) { failNext = false; throw new Error('sendgrid 500'); } if (unsub.has(args[0])) return false; sent.push(args); return true; } };
let conf = {}, now = Date.parse('2026-11-21T15:00:00Z');
const init = () => SI.init({ dataDir: dir, accounts, mailer, prohibited, siteConfig: () => conf, secret: 's'.repeat(40), linkHosts: 'clickvidpro.com', clock: () => now, gapMs: 0,
hooks: { excluded: em => em === 'flagged@mail.test', excludedPerson: async em => (em === 'gone@mail.test' ? 'erased' : em.endsWith('@gmial.com') ? 'mistyped email domain' : unsub.has(em) ? 'unsubscribed from email' : null) } });
await init();
const L = u => 'https://clickvidpro.com/p/abc123/' + u + 'xxxx';
const send = (items, x) => SI.handle('send', Object.assign({ rid: 'rid-' + Math.random().toString(36).slice(2) + 'abcdef', site: 'videoappincome', sender: { email: 'ann@mail.test' }, items }, x || {}));
// ---- signature ----
{
const raw = JSON.stringify({ site: 'videoappincome' }), ts = String(Date.now());
ok(SI.verify({ 'x-invite-ts': ts, 'x-invite-sig': SI.sign(ts, raw) }, raw).body, 'a correctly signed call is accepted');
ok(SI.verify({ 'x-invite-ts': ts, 'x-invite-sig': SI.sign(ts, raw + ' ') }, raw).status === 401, 'a changed body is refused');
const old = String(Date.now() - 6 * 60000); ok(SI.verify({ 'x-invite-ts': old, 'x-invite-sig': SI.sign(old, raw) }, raw).status === 401, 'a call older than 5 minutes is refused');
ok(SI.verify({}, raw).status === 401, 'an unsigned call is refused');
}
// ---- eligible ----
{
const r = await SI.handle('eligible', { site: 'videoappincome', sender: { email: 'ann@mail.test' } });
const st = Object.fromEntries(r.directs.map(d => [d.username, d.state]));
ok(r.ok && r.sender === 'ann' && st.d01 === 'ok' && st.bob === 'ok', 'directs who can be mailed are listed as ok', r);
ok(!('carl' in st), 'a level 2 member is not listed');
ok(['optout', 'flagged', 'gone', 'shell', 'never', 'typo'].every(u => st[u] === 'no'), 'unsubscribed, flagged, erased, never signed in and mistyped-domain directs are "no"', st);
ok(!/@/.test(JSON.stringify(r)), 'no email address in the answer');
ok(r.left.sender === 25 && r.left.network === 200, 'both daily allowances start full', r.left);
const w = await SI.handle('eligible', { site: 'videoappincome', sender: { wallet: '0x' + 'A'.repeat(40) } }); ok(w.ok && w.sender === 'ann', 'the sender can be found by wallet');
ok((await SI.handle('eligible', { site: 'videoappincome', sender: { email: 'nobody@mail.test' } })).code === 'sender', 'an unknown sender is refused');
ok((await SI.handle('eligible', { site: 'othersite', sender: { email: 'ann@mail.test' } })).code === 'site', 'an unknown site is refused');
}
// ---- send: the rules ----
{
const body = { rid: 'rid-first-0001', site: 'videoappincome', sender: { email: 'ann@mail.test' }, items: [{ username: 'd01', link: L('d01') }, { username: 'carl', link: L('carl') }, { username: 'optout', link: L('o') }, { username: 'shell', link: L('s') }, { username: 'ann', link: L('a') }, { username: 'd02', link: 'https://evil.example/p/abc123' }, { username: 'ghost', link: L('g') }, { username: 'd01', link: L('d01') }] };
const r = await SI.handle('send', body), st = r.results.map(x => x.status);
ok(r.ok && r.sent === 1 && st[0] === 'sent', 'a direct is mailed', r);
ok(st[1] === 'not your direct', 'a level 2 member is refused: directs only', st);
ok(st[2] === 'no' && st[3] === 'no' && st[4] === 'not your direct', 'unsubscribed, never-signed-in and the sender themself are refused', st);
ok(st[5] === 'bad link' && st[6] === 'no' && st[7] === 'duplicate', 'a link off the share domain, an unknown name and a repeat are refused', st);
ok(sent.length === 1 && sent[0][0] === 'd01@mail.test' && sent[0].length === 4, 'exactly one email, and never with the transactional flag', sent.length);
const [, subject, text, html] = sent[0];
ok(subject === 'ann made you a video' && text.startsWith('Hi d01,') && text.includes(L('d01')) && html.includes('href="' + L('d01') + '"'), 'subject, greeting and the personal video link are right');
ok(/I earn a share if you buy credits/.test(text) && /Nothing is promised/.test(text) && /one-time note sent through the network on their behalf/.test(text), 'the earning disclosure and the one-time footer are in the email');
ok(!/guarantee|passive income|\bearn \$/i.test(text), 'no income promise in the wording');
ok(!/@/.test(JSON.stringify(r)), 'no email address in the answer');
const again = await SI.handle('send', body); ok(again.already && sent.length === 1, 'the same request replayed sends nothing');
const r2 = await send([{ username: 'd01', link: L('d01') }]); ok(r2.results[0].status === 'sent before' && sent.length === 1, 'once ever: a second invite to the same person is refused');
const e = await SI.handle('eligible', { site: 'videoappincome', sender: { email: 'ann@mail.test' } }); ok(e.directs.find(d => d.username === 'd01').state === 'sent' && e.left.sender === 24, 'the list shows them as sent and the allowance drops', e.left);
}
// ---- the note ----
{
ok((await send([{ username: 'd02', link: L('d02') }], { note: 'See https://my-site.example for more' })).code === 'note', 'a note with a link is refused');
ok((await send([{ username: 'd02', link: L('d02') }], { note: 'This is guaranteed income.' })).code === 'note', 'a note that promises income is refused');
ok((await send([{ username: 'd02', link: L('d02') }], { note: 'x'.repeat(401) })).code === 'note', 'a note over 400 characters is refused');
const r = await send([{ username: 'd02', link: L('d02') }], { note: 'I used it for <b>my</b> banner site last night.' });
ok(r.sent === 1 && sent[sent.length - 1][2].includes('\n\nI used it for my banner site last night.\n\n'), 'a clean note goes in as its own paragraph, tags stripped');
}
// ---- a failed send can be retried; unsubscribed at the last second is not recorded ----
{
failNext = true; const r = await send([{ username: 'd03', link: L('d03') }]); ok(r.results[0].status === 'failed', 'a mail failure is reported');
const r2 = await send([{ username: 'd03', link: L('d03') }]); ok(r2.results[0].status === 'sent', 'and the same person can be tried again');
unsub.add('d04@mail.test'); const saveHook = unsub; const r3 = await send([{ username: 'd04', link: L('d04') }]); ok(r3.results[0].status === 'no', 'someone who unsubscribed is not mailed');
unsub.delete('d04@mail.test'); const r4 = await send([{ username: 'd04', link: L('d04') }]); ok(r4.results[0].status === 'sent', 'and no "sent" record was left behind for them');
}
// ---- caps, pause, batch size ----
{
ok((await send(Array.from({ length: 26 }, (_, i) => ({ username: 'd' + String(i + 1).padStart(2, '0'), link: L('x') })))).code === 'count', 'more than 25 in one request is refused');
const names = Array.from({ length: 25 }, (_, i) => 'd' + String(i + 5).padStart(2, '0')); // d05..d29: ann has sent 4 today, 21 left
const r = await send(names.map(u => ({ username: u, link: L(u) })));
ok(r.sent === 21 && r.results.filter(x => x.status === 'your daily limit').length === 4 && r.left.sender === 0, 'one sender stops at 25 a day', { sent: r.sent, left: r.left });
now += 24 * 3600000; const r2 = await send([{ username: 'd26', link: L('d26') }]); ok(r2.sent === 1, 'the next Central day the allowance is back');
conf = { siteInvitePerDay: 2 }; const z = await SI.handle('send', { rid: 'rid-zed-000001', site: 'videoappincome', sender: { email: 'zed@mail.test' }, items: ['z1', 'z2', 'z3'].map(u => ({ username: u, link: L(u) })) });
ok(z.sent === 1 && z.results.filter(x => x.status === 'network daily limit').length === 2, 'the all-senders daily cap stops everyone', z.results);
conf = { siteInvitesPaused: '1' }; ok((await send([{ username: 'd27', link: L('d27') }])).code === 'paused', 'the pause switch stops sending'); conf = {};
}
// ---- survives a restart: the once-ever record is on disk ----
{
await init(); const n = sent.length; const r = await send([{ username: 'd01', link: L('d01') }]);
ok(r.results[0].status === 'sent before' && sent.length === n, 'after a restart the once-ever rule still holds');
const v = await SI.adminView(); ok(v.on && v.recent.length > 20 && !/@/.test(JSON.stringify(v)), 'the admin view lists invites by username only');
}
// ---- the email-check code mail (a site's network gate) ----
{
const n = sent.length; let r = await SI.handle('code', { site: 'videoappincome', email: 'New.Person@Mail.test', code: '482913' });
const m = sent[sent.length - 1];
ok(r.ok && sent.length === n + 1 && m[0] === 'new.person@mail.test' && m[1] === '482913 is your Video App Income code' && m[2].startsWith('Your code is: 482913') && !/https?:/.test(m[2]), 'the code mail goes out with the code, the site name and no links', m && m.slice(0, 3));
ok(m[4] && m[4].transactional === true && m[4].fromName === 'Video App Income', 'it is sent as a requested (transactional) mail under the site name');
ok((await SI.handle('code', { site: 'videoappincome', email: 'not an email', code: '111111' })).code === 'email', 'a bad address is refused');
ok((await SI.handle('code', { site: 'videoappincome', email: 'a@mail.test', code: '12ab' })).code === 'email', 'a code that is not six digits is refused');
ok((await SI.handle('code', { site: 'videoappincome', email: 'x@mailinator.com', code: '111111' })).code === 'email', 'a throwaway address is refused');
ok((await SI.handle('code', { site: 'videoappincome', email: 'flagged@mail.test', code: '111111' })).code === 'email', 'a suspended or flagged address is refused');
ok((await SI.handle('code', { site: 'nosuchsite', email: 'a@mail.test', code: '111111' })).code === 'site', 'an unknown site is refused');
for (let i = 0; i < 4; i++) await SI.handle('code', { site: 'videoappincome', email: 'new.person@mail.test', code: '482913' });
r = await SI.handle('code', { site: 'videoappincome', email: 'new.person@mail.test', code: '482913' }); ok(r.code === 'limit', 'the sixth code to one address in an hour is refused', r);
}
// ---- a ready-made video about the site itself (kind 'promo', Marty 2026-11-21): the email must not say the sender made it ----
{
const own = SI.compose(SI.SITES.videoappincome, 'ann', 'd01', L('d01'), ''), pro = SI.compose(SI.SITES.videoappincome, 'ann', 'd01', L('d01'), '', 'promo');
ok(own.subject === 'ann made you a video' && own.text.includes("Here's one I made: " + L('d01')), 'their own video keeps the approved wording');
ok(pro.subject === 'ann sent you a video' && pro.text.includes("Here's a short video that shows how it works: " + L('d01')) && !/I made|made you/.test(pro.text + pro.subject), 'a ready-made video is never called the sender\'s own');
ok(pro.html.includes('href="' + L('d01') + '"'), 'the link is clickable in the ready-made version');
const strip = t => t.replace("Here's a short video that shows how it works: ", "Here's one I made: ");
ok(strip(pro.text) === own.text, 'every other word of the email is the same');
const n = sent.length, r = await SI.handle('send', { rid: 'rid-promo-000001', site: 'videoappincome', sender: { email: 'bob@mail.test' }, kind: 'promo', items: [{ username: 'carl', link: L('carl') }] });
if (r.ok && r.sent === 1) ok(sent.length === n + 1 && sent[n][1] === 'bob sent you a video' && /shows how it works/.test(sent[n][2]), 'the send call passes the kind through to the email', sent[n] && sent[n][1]);
else ok(false, 'promo send through the full path', r);
}
// ---- a second site, Podcast Commission Stack (2026-11-25): its own secret, the code mail only, Video App Income exactly as before ----
{
const PCS = 'podcastcommissionstack', VAI = 'videoappincome', pSecret = 'p'.repeat(40), vSecret = 's'.repeat(40);
const base = { dataDir: dir, accounts, mailer, prohibited, siteConfig: () => conf, secret: vSecret, linkHosts: 'clickvidpro.com', clock: () => now, gapMs: 0, hooks: { excluded: em => em === 'flagged@mail.test' } };
const signed = (body, secret) => { const raw = JSON.stringify(body), ts = String(Date.now()); return SI.verify({ 'x-invite-ts': ts, 'x-invite-sig': SI.sign(ts, raw, secret) }, raw); };
// the whole HTTP path: verify names the signing site, and that name goes to handle (server.js: handle(op, sg.body, sg.site))
const call = async (op, body, secret) => { const sg = signed(body, secret); return sg.body ? SI.handle(op, sg.body, sg.site) : sg; };
const vaiText = c => 'Your code is: ' + c + '\n\nEnter it in Video App Income to confirm your email. It works for 15 minutes. If you did not ask for it, ignore this email.\n\nVideo App Income is part of the Crypto Team Build Network. This email was sent by InstantAdPay, the mail service of the network.';
// before its secret is set, the new site cannot call at all and Video App Income is as it was
await SI.init(base); now += 24 * 3600000;
ok(signed({ site: PCS, email: 'a@mail.test', code: '111111' }, pSecret).status === 401, 'with no secret set for Podcast Commission Stack, a call signed for it is refused');
ok(signed({ site: VAI }, vSecret).site === VAI, 'and a Video App Income call is still accepted');
await SI.init(Object.assign({}, base, { secrets: { [PCS]: vSecret } }));
ok(signed({ site: PCS }, vSecret).site === VAI && (await call('code', { site: PCS, email: 'a@mail.test', code: '111111' }, vSecret)).code === 'site', 'the same secret given to both sites does not open the second site');
await SI.init(Object.assign({}, base, { secrets: { [PCS]: 'short' } }));
ok(signed({ site: PCS }, 'short').status === 401, 'a secret under 32 characters is not accepted for the second site');
// the env var, by its exact name
process.env.SITE_INVITE_SECRET_PCS = pSecret; await SI.init(base);
ok(signed({ site: PCS }, pSecret).site === PCS, 'SITE_INVITE_SECRET_PCS is the secret Podcast Commission Stack signs with');
delete process.env.SITE_INVITE_SECRET_PCS;
await SI.init(Object.assign({}, base, { secrets: { [PCS]: pSecret } }));
ok(signed({ site: PCS }, pSecret).site === PCS && signed({ site: VAI }, vSecret).site === VAI, 'each site is recognised by its own secret');
ok(signed({ site: PCS }, 'x'.repeat(40)).status === 401, 'a secret that belongs to neither site is refused');
// the code mail for the new site
let n = sent.length, r = await call('code', { site: PCS, email: 'Pod.Person@Mail.test', code: '730155' }, pSecret), m = sent[sent.length - 1];
ok(r.ok && sent.length === n + 1 && m[0] === 'pod.person@mail.test' && m[1] === '730155 is your Podcast Commission Stack code', 'the code mail goes out for Podcast Commission Stack', [r, m && m.slice(0, 2)]);
ok(m[2] === vaiText('730155').split('Video App Income').join('Podcast Commission Stack') && !/Video App Income|https?:/.test(m[2] + m[1]), 'its wording names Podcast Commission Stack, never Video App Income, and has no links', m[2]);
ok(m[3] == null && m[4] && m[4].transactional === true && m[4].fromName === 'Podcast Commission Stack', 'it is sent as a requested mail with the From name Podcast Commission Stack', m[4]);
ok((await call('code', { site: PCS, email: 'x@mailinator.com', code: '111111' }, pSecret)).code === 'email' && (await call('code', { site: PCS, email: 'flagged@mail.test', code: '111111' }, pSecret)).code === 'email' && (await call('code', { site: PCS, email: 'a@mail.test', code: '12ab' }, pSecret)).code === 'email', 'the same address and code checks apply to it');
// one site's secret never acts for the other
n = sent.length;
ok((await call('code', { site: PCS, email: 'b@mail.test', code: '111111' }, vSecret)).code === 'site', 'the Video App Income secret cannot send a Podcast Commission Stack code');
ok((await call('code', { site: VAI, email: 'b@mail.test', code: '111111' }, pSecret)).code === 'site', 'the Podcast Commission Stack secret cannot send a Video App Income code');
ok((await call('eligible', { site: VAI, sender: { email: 'ann@mail.test' } }, pSecret)).code === 'site' && (await call('send', { rid: 'rid-cross-000001', site: VAI, sender: { email: 'zed@mail.test' }, items: [{ username: 'z2', link: L('z2') }] }, pSecret)).code === 'site', 'nor reach the Video App Income invite calls');
ok(sent.length === n, 'and none of those sent an email');
// invite emails are not open to the new site, with its own secret or from inside the app
const before = (await SI.adminView()).recent.length;
r = await call('eligible', { site: PCS, sender: { email: 'ann@mail.test' } }, pSecret); ok(r.code === 'op' && !r.directs, 'Podcast Commission Stack cannot ask who is eligible for invites', r);
r = await call('send', { rid: 'rid-pcs-0000001', site: PCS, sender: { email: 'zed@mail.test' }, items: [{ username: 'z2', link: L('z2') }] }, pSecret); ok(r.code === 'op' && !r.results, 'or send invite emails', r);
ok((await SI.handle('send', { rid: 'rid-pcs-0000002', site: PCS, sender: { email: 'zed@mail.test' }, items: [{ username: 'z2', link: L('z2') }] })).code === 'op' && (await SI.handle('eligible', { site: PCS, sender: { email: 'ann@mail.test' } })).code === 'op', 'the same refusal without a signer');
ok((await SI.sample('owner@mail.test', PCS)).error === 'unknown site', 'and there is no sample invite for it');
ok(sent.length === n && (await SI.adminView()).recent.length === before, 'nothing was sent or recorded');
ok(SI.SITES[PCS].ops.join() === 'code' && !SI.SITES[VAI].ops && !SI.SITES[VAI].secretEnv, 'the site list: code only for the new site, Video App Income with no restriction and its original secret');
// Video App Income after the change: same words, same calls
n = sent.length; r = await call('code', { site: VAI, email: 'vai.person@mail.test', code: '204681' }, vSecret); m = sent[sent.length - 1];
ok(r.ok && sent.length === n + 1 && m[1] === '204681 is your Video App Income code' && m[2] === vaiText('204681') && m[4].transactional === true && m[4].fromName === 'Video App Income', 'the Video App Income code mail is word for word what it was', m && m.slice(1, 3));
r = await call('eligible', { site: VAI, sender: { email: 'zed@mail.test' } }, vSecret); ok(r.ok && r.sender === 'zed' && r.directs.length === 3, 'Video App Income can still ask who is eligible', r);
n = sent.length; r = await call('send', { rid: 'rid-vai-still-01', site: VAI, sender: { email: 'zed@mail.test' }, items: [{ username: 'z2', link: L('z2') }] }, vSecret);
ok(r.ok && r.sent === 1 && sent.length === n + 1 && sent[n][1] === 'zed made you a video' && sent[n].length === 4, 'and still send an invite email, worded as before', r);
ok((await call('code', { site: 'nosuchsite', email: 'a@mail.test', code: '111111' }, vSecret)).error === 'unknown site', 'an unknown site is refused as before');
// the limits are one count for both sites: nothing is doubled by adding a site
for (let i = 0; i < 2; i++) await call('code', { site: PCS, email: 'both@mail.test', code: '111111' }, pSecret);
for (let i = 0; i < 3; i++) await call('code', { site: VAI, email: 'both@mail.test', code: '111111' }, vSecret);
n = sent.length;
ok((await call('code', { site: PCS, email: 'both@mail.test', code: '111111' }, pSecret)).code === 'limit' && (await call('code', { site: VAI, email: 'both@mail.test', code: '111111' }, vSecret)).code === 'limit' && sent.length === n, 'five codes an hour to one address, counted across both sites');
now += 24 * 3600000; n = sent.length; let okN = 0;
for (let i = 0; i < 2000; i++) { const pcs = i % 2 === 0; if ((await call('code', { site: pcs ? PCS : VAI, email: 'day' + i + '@mail.test', code: '111111' }, pcs ? pSecret : vSecret)).ok) okN++; }
ok(okN === 2000 && sent.length === n + 2000, '2,000 codes in a day go out between the two sites', okN);
ok((await call('code', { site: PCS, email: 'over1@mail.test', code: '111111' }, pSecret)).code === 'limit' && (await call('code', { site: VAI, email: 'over2@mail.test', code: '111111' }, vSecret)).code === 'limit' && sent.length === n + 2000, 'and the 2,001st is refused for either site: the daily limit is still 2,000 in all');
}
fs.rmSync(dir, { recursive: true, force: true });
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);