1d5dd057e0
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
193 lines
18 KiB
JavaScript
193 lines
18 KiB
JavaScript
'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' | <refusal code> }], 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, '<').replace(/>/g, '>');
|
|
const html = '<div style="font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.55;color:#222;max-width:560px">' + P.map((p, i) => i === P.length - 1 ? '<p style="font-size:12px;color:#888;margin-top:24px">' + esc(p) + '</p>' : '<p>' + esc(p).replace(esc(link), '<a href="' + esc(link) + '">' + esc(link) + '</a>') + '</p>').join('') + '</div>';
|
|
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 };
|