diff --git a/chatbot.js b/chatbot.js index 78e2f68..5a08603 100644 --- a/chatbot.js +++ b/chatbot.js @@ -50,7 +50,7 @@ function key() { function enabled() { return !!key(); } // ---- canned answers: instant, free, always in voice ---- -const KNOWLEDGE_DATE = '2026-11-20'; // bump whenever the canned answers / prompt are brought up to date +const KNOWLEDGE_DATE = '2026-11-21'; // bump whenever the canned answers / prompt are brought up to date const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; const CANNED = [ // network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js) @@ -214,6 +214,9 @@ const CANNED = [ { id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'], re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i, a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' }, + { id: 'sponsor-video-invite', title: 'An email saying my sponsor made me a video', q: ['I got an email that my sponsor made me a video, is it real?', 'What is Video App Income?', 'How do I stop invite emails from my sponsor?'], tags: ['video app income', 'sponsor invite', 'invite email', 'made you a video'], + re: /(made (me|you) a video|video app income|videoappincome|invite(d)? (email|from my sponsor)|email from my sponsor)/i, + a: 'That email is real if it names your sponsor. Video App Income is another site in the network that makes short promo videos from a phone. A sponsor there can send each of their own direct referrals one invite, once, and it is delivered by InstantAdPay so it comes from an address you already know. It shows a video your sponsor made and says plainly that they earn a share if you buy credits there. Your first video there is free, nothing is promised, and you do not have to join. Your email address was not given to your sponsor or to Video App Income: InstantAdPay sent the note on their behalf. Each person gets this invite one time only. To stop all InstantAdPay emails except sign-in codes and receipts, use the Stop these emails link at the bottom of the message.' }, { id: 'who-invited', title: 'Who invited you? (naming your sponsor)', q: ['How do I add the person who invited me?', 'I joined without a link, can I name my sponsor?', 'What is the Who invited you card?'], tags: ['who invited you', 'invited', 'holding tank', 'no sponsor', 'sponsor link'], re: /(who invited|invited (me|by)|joined without a (link|sponsor)|forgot (the|my|to use).{0,12}(link|sponsor)|(add|name|set|enter|pick|choose) (my |a )?sponsor|nobody invited)/i, a: 'If you joined without a sponsor link, your Overview shows a Who invited you? card. Type the username of the person who invited you, confirm it, and they become your sponsor, here and on LinkSpin, and they get a notice. Do it before you switch on payouts or buy, because your sponsor locks on the contract at that point. It has to be a real member: not you, not someone in your own line, and not someone who has not switched on payouts with nobody above them who has (ask them to switch on first). Once you have a sponsor or a member number the card goes away. Nobody invited you? Tap Nobody invited me and stay in the holding tank; a small link on the Overview brings the card back while you are still there. Nothing on the site waits for your answer. New sign-ups cannot be adopted by hand for their first 24 hours, so you have a day to tell us before a member can pick you up.' }, diff --git a/qa/run.sh b/qa/run.sh index 097960e..c772ac9 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -79,6 +79,7 @@ elif [ "$MODE" = "member" ]; then node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825) + node qa/site-invite.test.mjs || status=1 # sponsor invite emails for other network sites: directs only, once ever, caps, never-mail list node qa/walletnudge.test.cjs || status=1 node qa/bixpay.test.cjs || status=1 node qa/profile-policy.test.cjs || status=1 @@ -90,6 +91,8 @@ elif [ "$MODE" = "weekend" ]; then node qa/weekend.e2e.mjs || status=1 # /weekend, Home strip, ribbon, feeds, builders key at test clocks (local copies + a fake hub) elif [ "$MODE" = "draft" ]; then node qa/draft-partner.test.mjs || status=1 +elif [ "$MODE" = "siteinvite" ]; then + node qa/site-invite.test.mjs || status=1 # sponsor invite emails for other network sites (siteinvite.js, 2026-11-21) elif [ "$MODE" = "theme" ]; then start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797 elif [ "$MODE" = "policy" ]; then diff --git a/qa/site-invite.test.mjs b/qa/site-invite.test.mjs new file mode 100644 index 0000000..2d29cf4 --- /dev/null +++ b/qa/site-invite.test.mjs @@ -0,0 +1,116 @@ +// 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 my 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'); +} +fs.rmSync(dir, { recursive: true, force: true }); +console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0); diff --git a/server.js b/server.js index bafb195..8834f79 100644 --- a/server.js +++ b/server.js @@ -58,6 +58,7 @@ const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07) const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15) const tankbatch = require('./tankbatch'); // holding tank batches (2026-11-15): switch tankBatches, default off +const siteinvite = require('./siteinvite'); // sponsor invite emails for other network sites (Video App Income, Marty approved 2026-11-20): signed eligible / send, needs SITE_INVITE_SECRET const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET) const loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event @@ -872,6 +873,11 @@ async function boot() { let jpeg = null; try { jpeg = fs.readFileSync(path.join(__dirname, 'public', 'banners', 'holding-tank-leads-1200x675.jpg')); } catch (e) {} if (jpeg && html.length <= 1024 && await telegramSendPhoto(chat, jpeg, html, topic)) return; await telegramSend(chat, html, topic); }, feed: async (who, what, level) => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; const clean = t => String(t || '').replace(/[<>&]/g, ''); await telegramSend(sc.telegramEchoChatId, '\u{1F91D} InstantAdPay ยท ' + clean(who) + ' just received ' + clean(what) + ' from the holding tank (' + clean(level) + ' level)', sc.telegramEchoTopicId); } } }).catch(e => console.error('tankbatch init', e.message)); } + // sponsor invite emails for other network sites (siteinvite.js, 2026-11-21): the same never-mail list the tank batches use + { let spamC = { at: 0, set: new Set() }; const spamSet = () => { if (Date.now() - spamC.at > 60000) { try { spamC = { at: Date.now(), set: new Set((((spamscan.view() || {}).last || {}).candidates || []).map(c => String(c.email || '').toLowerCase())) }; } catch (e) { spamC = { at: Date.now(), set: new Set() }; } } return spamC.set; }; + await siteinvite.init({ dataDir: DATA_DIR, accounts, mailer, siteConfig, prohibited, + hooks: { excluded: em => fraud.excluded(em), + excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; } } }).catch(e => console.error('siteinvite init', e.message)); } setTimeout(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 4 * 60 * 1000); // past the deploy overlap window setInterval(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 60 * 60 * 1000); setInterval(() => tankbatch.mailTick().catch(e => console.error('tankbatch mail', e.message)), 60 * 1000); // throttled batch emails (tankBatchEmailsPerDay, 8 AM to 8 PM CT) + spaced Telegram cards @@ -950,6 +956,7 @@ function siteConfig() { loginAdEveryHours: 3, // login ad: shown again on the next member page once the last finished view is this many hours old (Marty 2026-11-15) tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11 fiveXDraftCap: 10, // 5xYourTeam draft: open picks one coach may hold, its own cap (Marty 2026-11-15), never shared with tankAdoptCap or batches + ...siteinvite.DEFAULTS, // sponsor invite emails for other network sites (siteinvite.js): siteInvitesPaused '1' stops them; per-sender and all-senders daily caps ...tankbatch.DEFAULTS, // holding tank batches (tankbatch.js, Marty 2026-11-15): master switch tankBatches '0'; every number of the ladder, cadence and follow-up legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) @@ -3924,6 +3931,20 @@ const server = http.createServer(async (req, res) => { const r = await draftpartner.handle(op, sg.body); return json(res, r.error ? 400 : 200, r); } + // -- sponsor invite emails for other network sites (siteinvite.js, 2026-11-21): signed partner calls, SITE_INVITE_SECRET as X-Invite-Ts + X-Invite-Sig + if (p.startsWith('/api/partner/invite/') && req.method === 'POST') { + const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 64000) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); + const sg = siteinvite.verify(req.headers, raw); if (!sg.body) return json(res, sg.status, { error: sg.error }); + const op = p.slice('/api/partner/invite/'.length); + if (!['eligible', 'send'].includes(op)) return json(res, 404, { error: 'unknown op' }); + const r = await siteinvite.handle(op, sg.body); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/site-invites' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await siteinvite.adminView()); } + if (p === '/api/admin/site-invites/sample' && req.method === 'POST') { // one sample of the invite email to the admin address only + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); if (!ADMIN_EMAIL) return json(res, 400, { error: 'no admin email set' }); + return json(res, 200, await siteinvite.sample(ADMIN_EMAIL, 'videoappincome')); + } if (p === '/api/admin/draft' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await draftpartner.adminView()); diff --git a/siteinvite.js b/siteinvite.js new file mode 100644 index 0000000..cac69a7 --- /dev/null +++ b/siteinvite.js @@ -0,0 +1,192 @@ +'use strict'; +// Sponsor invite emails sent on behalf of another network site (first and only site: Video App Income). +// Marty approved 2026-11-20: directs only, the wording below, "IAP sends it" (the hub cannot send mail; this app already mails +// members from an authenticated domain). A sponsor on the other site picks directs and one of their own videos; that site asks +// here; this module decides who may be mailed and sends through mailer.send, so the opt-out rule, the unsubscribe link and the +// share-domain rewrite all apply (never `transactional`). +// +// POST /api/partner/invite/eligible { site, sender: { email?, wallet? } } +// -> { ok, sender: username, directs: [{ username, state: 'ok' | 'sent' | 'no' }], left: { sender, network }, paused } +// POST /api/partner/invite/send { rid, site, sender, items: [{ username, link }], note? } +// -> { ok, results: [{ username, status: 'sent' | }], sent, left } +// Signature: X-Invite-Ts (ms) + X-Invite-Sig = hex HMAC-SHA256(SITE_INVITE_SECRET, 'invite.v1.' + ts + '\n' + raw body), 5 minutes. +// +// The rules: +// - DIRECTS ONLY: each recipient is checked with accounts.isDownlineOf(sender, recipient, 1) at send time (the directs-only email +// rule of 2026-11-12: levels 2 and 3 belong to someone else's direct relationship) +// - ONCE EVER per site per recipient: the row in site_invites (unique site + recipient) is the claim, written before the send, so +// two copies of the app during a deploy cannot both send. A send that fails removes its row so it can be tried again. +// - never to: an account that has never signed in here (waiting / shell accounts), suspended or flagged members, the spam scan's +// suspects, erased members, anyone unsubscribed from email, throwaway or mistyped email domains, the sender themself +// - caps: siteInvitePerSender a Central day for one sender (default 25), siteInvitePerDay for all senders together (default 200); +// siteInvitesPaused '1' stops all sending +// - the other site never learns an email address: it gets usernames and a state, nothing else +// - the wording is fixed here. The sender may add one short note; it is refused if it has a link or trips the prohibited list. +// The video link must be a share page on an allowed host (SITE_INVITE_LINK_HOSTS). +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const db = require('./db'); + +const SITES = { videoappincome: { name: 'Video App Income' } }; +const THROWAWAY = new Set(['mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', 'grr.la', '10minutemail.com', 'tempmail.com', 'temp-mail.org', + 'yopmail.com', 'trashmail.com', 'getnada.com', 'maildrop.cc', 'dispostable.com', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'mohmal.com', 'emailondeck.com', + 'tempail.com', 'tempr.email', 'discard.email', 'spamgourmet.com', 'mailnesia.com', 'mytemp.email', 'tempmailo.com', 'burnermail.io', 'example.com', 'test.com']); +const DEFAULTS = { siteInvitesPaused: '0', siteInvitePerSender: 25, siteInvitePerDay: 200 }; +const TZ = 'America/Chicago'; +const lc = v => String(v || '').trim().toLowerCase(); + +let R = null; // { dataDir, accounts, mailer, siteConfig, prohibited, hooks: { excluded(email), excludedPerson(email) -> reason|null }, secret?, linkHosts?, clock?, gapMs? } +const clock = () => (R && R.clock ? R.clock() : Date.now()); +const SECRET = () => String((R && R.secret) || process.env.SITE_INVITE_SECRET || '').trim(); +const enabled = () => SECRET().length >= 32; +const hosts = () => String((R && R.linkHosts) || process.env.SITE_INVITE_LINK_HOSTS || 'clickvidpro.com').split(',').map(lc).filter(Boolean); +function cfg() { const sc = (R && R.siteConfig && R.siteConfig()) || {}; const n = (k, lo, hi) => { const v = Math.round(Number(sc[k] == null ? DEFAULTS[k] : sc[k])); return v >= lo && v <= hi ? v : DEFAULTS[k]; }; + return { paused: String(sc.siteInvitesPaused == null ? DEFAULTS.siteInvitesPaused : sc.siteInvitesPaused) === '1', perSender: n('siteInvitePerSender', 1, 500), perDay: n('siteInvitePerDay', 1, 5000) }; } +function dayStart(ts) { const o = {}; for (const p of new Intl.DateTimeFormat('en-US', { timeZone: TZ, hourCycle: 'h23', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(ts))) o[p.type] = Number(p.value); return ts - (o.hour * 60 + o.minute) * 60000 - (ts % 60000); } + +// ---- storage: MySQL site_invites when DATABASE_URL is set, else a JSON document (local QA) ---- +const J = { + st: null, FILE: () => path.join(R.dataDir, 'site-invites.json'), + load() { if (this.st) return this.st; try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; } if (!this.st || !Array.isArray(this.st.rows)) this.st = { rows: [] }; return this.st; }, + save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); }, + async claim(row) { const s = this.load(); if (s.rows.some(r => r.site === row.site && r.recipient === row.recipient)) return false; s.rows.push(Object.assign({}, row)); this.save(); return true; }, + async unclaim(site, recipient) { const s = this.load(); s.rows = s.rows.filter(r => !(r.site === site && r.recipient === recipient)); this.save(); }, + async mark(site, recipient, status) { const r = this.load().rows.find(x => x.site === site && x.recipient === recipient); if (r) { r.status = status; this.save(); } }, + async sentTo(site, emails) { const set = new Set(emails); return new Set(this.load().rows.filter(r => r.site === site && set.has(r.recipient)).map(r => r.recipient)); }, + async count(since, sender) { return this.load().rows.filter(r => r.ts >= since && (!sender || r.sender === sender)).length; }, + async byRid(rid) { return this.load().rows.filter(r => r.rid === rid).map(r => Object.assign({}, r)); }, + async recent(n) { return this.load().rows.slice(-(n || 100)).reverse().map(r => Object.assign({}, r)); } +}; +const rowP = r => ({ site: r.site, recipient: r.recipient, username: r.username, sender: r.sender, senderName: r.sender_name, link: r.link, rid: r.rid, ts: Number(r.ts), status: r.status }); +const Q = { + async claim(row) { const r = await db.q('INSERT IGNORE INTO site_invites (site,recipient,username,sender,sender_name,link,rid,ts,status) VALUES (?,?,?,?,?,?,?,?,?)', [row.site, row.recipient, row.username, row.sender, row.senderName, row.link, row.rid, row.ts, row.status]); return !!(r && r.affectedRows === 1); }, + async unclaim(site, recipient) { await db.q('DELETE FROM site_invites WHERE site=? AND recipient=?', [site, recipient]); }, + async mark(site, recipient, status) { await db.q('UPDATE site_invites SET status=? WHERE site=? AND recipient=?', [status, site, recipient]); }, + async sentTo(site, emails) { if (!emails.length) return new Set(); const out = new Set(); for (let i = 0; i < emails.length; i += 500) { const part = emails.slice(i, i + 500); for (const r of await db.q('SELECT recipient FROM site_invites WHERE site=? AND recipient IN (' + part.map(() => '?').join(',') + ')', [site].concat(part))) out.add(r.recipient); } return out; }, + async count(since, sender) { const r = sender ? await db.q('SELECT COUNT(*) n FROM site_invites WHERE ts>=? AND sender=?', [since, sender]) : await db.q('SELECT COUNT(*) n FROM site_invites WHERE ts>=?', [since]); return Number(r[0].n); }, + async byRid(rid) { return (await db.q('SELECT * FROM site_invites WHERE rid=?', [rid])).map(rowP); }, + async recent(n) { return (await db.q('SELECT * FROM site_invites ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); } +}; +const S = () => (db.enabled() ? Q : J); +async function ensureTables() { + if (!db.enabled()) return; + await db.q(`CREATE TABLE IF NOT EXISTS site_invites ( + id INT AUTO_INCREMENT PRIMARY KEY, site VARCHAR(40) NOT NULL, recipient VARCHAR(190) NOT NULL, username VARCHAR(40) NULL, sender VARCHAR(190) NOT NULL, sender_name VARCHAR(40) NULL, + link VARCHAR(300) NULL, rid VARCHAR(80) NULL, ts BIGINT NOT NULL, status VARCHAR(16) NOT NULL, + UNIQUE KEY once (site, recipient), KEY sender (sender, ts), KEY t (ts), KEY rid (rid) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // sponsor invite emails for other network sites: one row per recipient per site, ever +} +async function init(opts) { R = opts; J.st = null; await ensureTables(); } + +// ---- signature ---- +function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('invite.v1.' + ts + '\n' + raw).digest('hex'); } +function verify(headers, raw) { + if (!enabled()) return { status: 503, error: 'site invites not configured' }; + const ts = String(headers['x-invite-ts'] || ''), sig = String(headers['x-invite-sig'] || ''); + if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return { status: 401, error: 'stale' }; + const want = sign(ts, raw); + if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' }; + try { const b = JSON.parse(raw || '{}'); return b && typeof b === 'object' ? { body: b } : { status: 400, error: 'bad json' }; } catch (e) { return { status: 400, error: 'bad json' }; } +} + +// ---- who ---- +async function senderOf(s) { + const A = R.accounts; let a = null; + if (s && s.email) a = await A.byEmail(lc(s.email)); + if (!a && s && /^0x[0-9a-f]{40}$/.test(lc(s.wallet))) { a = await A.byAddress(lc(s.wallet)); if (!a && A.positionByAddress) { const p = await A.positionByAddress(lc(s.wallet)); if (p && p.email) a = await A.byEmail(p.email); } } + if (!a || !a.username) return null; + if (R.hooks && R.hooks.excluded && R.hooks.excluded(a.email)) return null; + return a; +} +// why this person cannot be mailed, or null. Reasons stay in this app (the other site only sees 'no'). +async function refusal(a, sender) { + if (!a || !a.email || !a.username) return 'no account'; + const em = lc(a.email); + if (em === lc(sender.email)) return 'self'; + if (R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a)) return 'never signed in'; + if (!a.lastSeen) return 'never signed in'; + const d = em.split('@')[1] || ''; if (!d || THROWAWAY.has(d)) return 'throwaway email'; + if (R.hooks && R.hooks.excluded && R.hooks.excluded(em)) return 'suspended or flagged'; + if (R.hooks && R.hooks.excludedPerson) { const why = await R.hooks.excludedPerson(em); if (why) return why; } + return null; +} +async function left(sender) { const c = cfg(), since = dayStart(clock()); return { sender: Math.max(0, c.perSender - await S().count(since, lc(sender.email))), network: Math.max(0, c.perDay - await S().count(since)) }; } + +// ---- the email (Marty approved the wording 2026-11-20). Plain text first; the HTML is the same words. ---- +function compose(site, sponsor, user, link, note) { + const P = [ + 'Hi ' + user + ',', + "It's " + sponsor + ', your sponsor on InstantAdPay. I\'ve started using a new app in our network called ' + site.name + ', and I wanted you to hear about it from me.', + ]; + if (note) P.push(note); + P.push('It makes short promo videos from your phone. You paste a link to whatever you promote, and about a minute and a half later you have a finished video with a voice, captions and music. No camera, no editing. Each video gets its own page that shows you who opened it and who tapped your button.', + "Your first video is free, so you can see if it's useful before spending anything. After that, videos cost credits, and a $10 pack makes 10 videos.", + "I'll be straight with you: I earn a share if you buy credits. That's how the app works for everyone, and you'd earn the same way from people you bring in. Nothing is promised, and plenty of people will just use it for the videos.", + "Here's one I made: " + link, + "You're already on my team, so if you join you'll be placed with me automatically. No link needed.", + sponsor, + "You're getting this because " + sponsor + ' is your sponsor in the Crypto Team Build Network. This is a one-time note sent through the network on their behalf.'); + const esc = t => String(t).replace(/&/g, '&').replace(//g, '>'); + const html = '
' + P.map((p, i) => i === P.length - 1 ? '

' + esc(p) + '

' : '

' + esc(p).replace(esc(link), '' + esc(link) + '') + '

').join('') + '
'; + return { subject: sponsor + ' made you a video', text: P.join('\n\n'), html }; +} +function cleanNote(n) { + const note = String(n || '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim(); + if (!note) return { note: '' }; + if (note.length > 400) return { error: 'Keep your note under 400 characters.' }; + const P = R.prohibited; + if (P && P.hasUrl && P.hasUrl(note)) return { error: 'Your note cannot contain a link. The email already carries your video.' }; + if (P && P.checkText) { const r = P.checkText(note, 'InstantAdPay'); if (r && r.error) return { error: r.error }; } + if (/\b(guarantee\w*|risk[ -]?free|passive income|get rich|double your)\b/i.test(note)) return { error: 'Your note cannot promise income or results.' }; + return { note }; +} +const linkOk = l => { try { const u = new URL(String(l)); return u.protocol === 'https:' && hosts().includes(u.hostname.toLowerCase()) && /^\/p\/[A-Za-z0-9]{4,20}(\/[A-Za-z0-9]{4,20})?$/.test(u.pathname) && !u.search && !u.hash; } catch (e) { return false; } }; + +// ---- the two calls ---- +async function eligible(b) { + const site = SITES[lc(b.site)]; if (!site) return { error: 'unknown site', code: 'site' }; + const sender = await senderOf(b.sender); if (!sender) return { error: 'The sender has no InstantAdPay account with a username.', code: 'sender' }; + const lv = await R.accounts.downline(sender.email, 1), kids = (lv[0] && lv[0].members) || []; + const sent = await S().sentTo(lc(b.site), kids.map(k => lc(k.email))), directs = []; + for (const k of kids) { if (!k.username) continue; directs.push({ username: k.username, state: sent.has(lc(k.email)) ? 'sent' : (await refusal(k, sender)) ? 'no' : 'ok' }); } + return { ok: true, sender: sender.username, directs, left: await left(sender), paused: cfg().paused }; +} +const sleep = ms => new Promise(r => setTimeout(r, ms)); +async function send(b) { + const siteId = lc(b.site), site = SITES[siteId]; if (!site) return { error: 'unknown site', code: 'site' }; + const rid = String(b.rid || ''); if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return { error: 'rid needed', code: 'rid' }; + const before = await S().byRid(rid); if (before.length) return { ok: true, already: true, results: before.map(r => ({ username: r.username, status: r.status })), sent: before.filter(r => r.status === 'sent').length }; + if (cfg().paused) return { error: 'Invites are paused right now.', code: 'paused' }; + if (!R.mailer || !R.mailer.hasKey()) return { error: 'Email is not available right now.', code: 'mail' }; + const sender = await senderOf(b.sender); if (!sender) return { error: 'The sender has no InstantAdPay account with a username.', code: 'sender' }; + const items = Array.isArray(b.items) ? b.items : []; if (!items.length || items.length > 25) return { error: 'Send 1 to 25 invites at a time.', code: 'count' }; + const cn = cleanNote(b.note); if (cn.error) return { error: cn.error, code: 'note' }; + const results = []; let sentN = 0; const seen = new Set(); + for (const it of items) { + const uname = String((it && it.username) || '').trim(), res = { username: uname, status: '' }; results.push(res); + if (seen.has(lc(uname))) { res.status = 'duplicate'; continue; } seen.add(lc(uname)); + if (!linkOk(it && it.link)) { res.status = 'bad link'; continue; } + const a = await R.accounts.byUsername(uname); if (!a) { res.status = 'no'; continue; } + if (!(await R.accounts.isDownlineOf(sender.email, a.email, 1))) { res.status = 'not your direct'; continue; } + if (await refusal(a, sender)) { res.status = 'no'; continue; } + const lf = await left(sender); if (lf.sender < 1) { res.status = 'your daily limit'; continue; } if (lf.network < 1) { res.status = 'network daily limit'; continue; } + const row = { site: siteId, recipient: lc(a.email), username: a.username, sender: lc(sender.email), senderName: sender.username, link: String(it.link), rid, ts: clock(), status: 'sending' }; + if (!(await S().claim(row))) { res.status = 'sent before'; continue; } + try { + const m = compose(site, sender.username, a.username, row.link, cn.note); + const okSent = await R.mailer.send(a.email, m.subject, m.text, m.html); + if (okSent === false) { await S().unclaim(siteId, row.recipient); res.status = 'no'; continue; } // unsubscribed between the check and the send + await S().mark(siteId, row.recipient, 'sent'); res.status = 'sent'; sentN++; + } catch (e) { console.error('site invite send', e.message); await S().unclaim(siteId, row.recipient).catch(() => {}); res.status = 'failed'; } + await sleep(R.gapMs == null ? 400 : R.gapMs); + } + console.log('site invite', siteId, 'from', sender.username, 'sent', sentN, 'of', items.length); + return { ok: true, results, sent: sentN, left: await left(sender) }; +} +async function handle(op, b) { if (op === 'eligible') return eligible(b || {}); if (op === 'send') return send(b || {}); return { error: 'unknown op' }; } +async function adminView() { const since = dayStart(clock()), c = cfg(); return { on: enabled(), paused: c.paused, perSender: c.perSender, perDay: c.perDay, today: await S().count(since), recent: (await S().recent(200)).map(r => ({ site: r.site, to: r.username, from: r.senderName, ts: r.ts, status: r.status, link: r.link })) }; } +// one sample to one address, for the owner to read before the feature opens. Not counted, not recorded. +async function sample(to, siteId) { const site = SITES[lc(siteId) || 'videoappincome']; if (!site) return { error: 'unknown site' }; const m = compose(site, 'yoursponsor', 'yourname', 'https://' + hosts()[0] + '/p/faceless', ''); await R.mailer.send(to, '[SAMPLE] ' + m.subject, m.text, m.html); return { ok: true, to, subject: m.subject, text: m.text }; } + +module.exports = { init, enabled, verify, sign, handle, adminView, sample, compose, cleanNote, linkOk, DEFAULTS, SITES };