From dfd0b9dbed9bf5bcdef7a9cf039e54e59018940e Mon Sep 17 00:00:00 2001 From: martbost Date: Wed, 7 Oct 2026 13:24:50 -0500 Subject: [PATCH] Destination reachability: refuse a link whose host has no DNS record at save time; daily sweep pauses live ads whose host is dead two days running, notices the owner (in-app + opt-in email), one admin alert; Admin API /api/admin/reach (+/run, dry) (campaign #163 served lmgnow.co after the domain vanished) Co-Authored-By: Claude Fable 5.1 --- reach.js | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ server.js | 12 +++++ 2 files changed, 140 insertions(+) create mode 100644 reach.js diff --git a/reach.js b/reach.js new file mode 100644 index 0000000..68dea45 --- /dev/null +++ b/reach.js @@ -0,0 +1,128 @@ +// Destination reachability (Marty, 2026-10-07). +// +// Why this exists: campaign #163 (a login ad) pointed at lmgnow.co, a domain that had stopped +// existing. The Safe Browsing screen saw "could not resolve" and, by design, read that as +// UNKNOWN rather than unsafe, so the ad kept serving and 65 members tapped into a dead end. +// Links are checked when they are saved, but a destination can die later: a shortener domain +// lapses, a hosting account closes, a redirect vanishes. This module watches for that. +// +// Two jobs: +// check(url) at save time: a host with no DNS record is refused with a plain reason. +// run() daily: every live campaign's destination (and image) host is resolved. A host +// that does not resolve gets a strike for that Central-time day. Two strikes on +// different days = the campaign is paused, its owner gets an in-app notice (and an +// email when they opted in to updates), and Marty gets one admin alert. A host that +// resolves again clears its strikes. The advertiser's credits stay on the campaign; +// they fix the link and resume it themselves. +// +// What counts as "does not resolve": ENOTFOUND / ENODATA (the registry or the zone says no such +// name). Timeouts, SERVFAIL, EAI_AGAIN and the like are resolver trouble on our side and are never +// a strike: a flaky resolver must not pause anyone's ad. Same three-valued discipline as sbcheck. +'use strict'; + +const dns = require('dns').promises; + +let X = null; +const STATE = () => X.path.join(X.dataDir, 'reach.json'); +function load() { try { return JSON.parse(X.fs.readFileSync(STATE(), 'utf8')); } catch (e) { return { hosts: {}, paused: [], at: 0 }; } } +function save(d) { try { X.fs.writeFileSync(STATE(), JSON.stringify(d)); } catch (e) {} } +const DEAD = ['ENOTFOUND', 'ENODATA']; +const STRIKES_TO_PAUSE = 2; +const CONCURRENCY = 6; + +function init(deps) { X = deps; } +function hostOf(url) { try { return new URL(String(url)).hostname.replace(/^www\./, '').toLowerCase(); } catch (e) { return ''; } } +const dayKey = () => new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); +const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + +// 'ok' | 'dead' | 'unknown' (+ why) +async function resolve(host) { + try { const a = await dns.lookup(host, { all: true }); return a && a.length ? { verdict: 'ok' } : { verdict: 'dead', why: 'no address records' }; } + catch (e) { return DEAD.includes(e.code) ? { verdict: 'dead', why: e.code } : { verdict: 'unknown', why: e.code || e.message }; } +} + +// Save time. Only a definite "no such name" refuses; resolver trouble passes and the sweep retries. +async function check(url) { + const host = hostOf(url); + if (!host || (X && host === X.selfHost)) return { ok: true, verdict: 'skipped', host }; + const v = await resolve(host); + if (v.verdict === 'dead') { + return { ok: false, verdict: 'dead', host, reason: 'That address does not resolve: ' + host + ' has no DNS record right now (' + v.why + '). ' + + 'Check the spelling, or the domain may have expired. Members would land on a dead end.' }; + } + if (v.verdict === 'unknown') console.log('reach: could not resolve ' + host + ' at save time (' + v.why + '); the sweep will retry'); + return { ok: true, verdict: v.verdict, host }; +} + +async function mapLimit(items, n, fn) { const out = new Array(items.length); let i = 0; await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (i < items.length) { const k = i++; out[k] = await fn(items[k], k); } })); return out; } + +function ownerNotice(c, host, left) { + const subject = 'Your ad "' + String(c.name || '').slice(0, 60) + '" is paused: its link no longer resolves'; + const text = 'We paused your ' + c.type + ' ad "' + c.name + '" (#' + c.id + ').\n\n' + + 'Its link points at ' + host + ', and that domain has had no DNS record on two checks a day apart. Every member who tapped the ad was landing on a dead end, so we stopped sending them there.\n\n' + + 'Your credits are safe: the campaign still holds ' + left.toLocaleString('en-US') + ' unspent credits of its ' + Number(c.budget || 0).toLocaleString('en-US') + '.\n\n' + + 'To get going again: open Campaigns at ' + X.site + '/my#campaigns, edit the link on #' + c.id + ' to one that loads, and resume it. Nothing else changes.'; + const html = '

' + esc(text).replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

').replace(/\n/g, '
') + '

'; + return { subject, text, html }; +} + +// One pass over every live campaign. Returns what it saw; pauses only when a host is dead on two different days. +async function run(opts) { + const dry = !!(opts && opts.dry); + if (!X || !X.db || !X.db.enabled()) return { error: 'no database' }; + const rows = await X.db.q("SELECT id, type, owner_email, name, target_url, image_url, budget, spent, status FROM campaigns WHERE status='active'"); + const byHost = {}; + for (const c of rows) for (const u of [c.target_url, c.image_url]) { + const h = hostOf(u); if (!h || h === X.selfHost) continue; + const e = byHost[h] || (byHost[h] = { camps: [] }); + if (!e.camps.some(x => x.id === c.id)) e.camps.push(c); + } + const hosts = Object.keys(byHost); + const today = dayKey(), st = load(); st.hosts = st.hosts || {}; st.paused = st.paused || []; + const out = { day: today, hosts: hosts.length, dead: [], unknown: [], paused: [], failed: [], cleared: 0, dry }; + const verdicts = await mapLimit(hosts, CONCURRENCY, h => resolve(h)); + hosts.forEach((h, i) => { + const v = verdicts[i], rec = st.hosts[h] || { strikes: [] }; + if (v.verdict === 'ok') { if (rec.strikes.length) out.cleared++; delete st.hosts[h]; return; } + if (v.verdict === 'unknown') { out.unknown.push({ host: h, why: v.why }); return; } + if (!rec.strikes.includes(today)) rec.strikes.push(today); + rec.strikes = rec.strikes.slice(-7); rec.lastWhy = v.why; rec.at = Date.now(); st.hosts[h] = rec; + out.dead.push({ host: h, why: v.why, strikes: rec.strikes.length, days: rec.strikes.slice(), campaigns: byHost[h].camps.map(c => ({ id: c.id, type: c.type, name: c.name, owner: c.owner_email })) }); + }); + // the strike must have landed today AND on at least one earlier day + const due = out.dead.filter(d => d.strikes >= STRIKES_TO_PAUSE && d.days.includes(today)); + if (!dry) { + for (const d of due) for (const c of byHost[d.host].camps) { + try { + const r = await X.db.q("UPDATE campaigns SET status='paused' WHERE id=? AND status='active'", [c.id]); + if (!r || !r.affectedRows) continue; + out.paused.push(c.id); + const left = Math.max(0, Number(c.budget || 0) - Number(c.spent || 0)); + st.paused.push({ id: c.id, host: d.host, owner: c.owner_email, at: Date.now(), left }); + const n = ownerNotice(c, d.host, left); + try { if (X.message) await X.message(c.owner_email, n.subject, n.html); } catch (e) { console.error('reach notice', c.id, e.message); } + try { if (X.mailer && X.mailer.hasKey && X.mailer.hasKey() && X.optedIn && await X.optedIn(c.owner_email)) await X.mailer.send(c.owner_email, n.subject, n.text, n.html); } catch (e) { console.error('reach mail', c.id, e.message); } + } catch (e) { out.failed.push({ id: c.id, error: e.message }); console.error('reach could not pause #' + c.id + ': ' + e.message); } + } + st.paused = st.paused.slice(-200); st.at = Date.now(); st.last = { day: today, hosts: out.hosts, dead: out.dead.length, unknown: out.unknown.length, paused: out.paused.slice() }; save(st); + if (out.paused.length && X.alert) { + const lines = due.map(d => '' + esc(d.host) + ' (' + esc(d.why) + ', dead on ' + d.days.join(', ') + ')\n' + d.campaigns.filter(c => out.paused.includes(c.id)).map(c => ' #' + c.id + ' ' + c.type + ' "' + esc(c.name) + '" (' + esc(c.owner) + ')').join('\n')); + X.alert('\u{1F517} Advertiser destinations that no longer resolve\n\n' + lines.join('\n') + '\n\nPaused; each owner got a notice with the fix. Credits stay on the campaign.').catch(() => {}); + } + if (out.dead.length) console.log('reach: ' + out.dead.length + ' dead host(s) today: ' + out.dead.map(d => d.host + ' (' + d.strikes + ')').join(', ') + (out.paused.length ? '; paused ' + out.paused.join(', ') : '')); + if (out.unknown.length) console.log('reach: ' + out.unknown.length + ' host(s) could not be resolved this pass (not a strike): ' + out.unknown.map(u => u.host + ' (' + u.why + ')').join('; ')); + } + return out; +} + +function adminView() { const st = load(); return { at: st.at || 0, last: st.last || null, striking: Object.entries(st.hosts || {}).map(([host, r]) => ({ host, strikes: r.strikes, why: r.lastWhy })), paused: (st.paused || []).slice(-50).reverse() }; } + +// Daily. First pass four minutes after boot (past the deploy-overlap window; strikes are per day, so a second +// copy or a redeploy the same day cannot double-count). +function start() { + const tick = () => { run({}).catch(e => console.error('reach', e.message)); }; + setTimeout(tick, 4 * 60 * 1000); + setInterval(tick, 24 * 60 * 60 * 1000); +} + +module.exports = { init, check, run, start, adminView, hostOf }; diff --git a/server.js b/server.js index b017529..9b21ea3 100644 --- a/server.js +++ b/server.js @@ -38,6 +38,7 @@ const releases = require('./releases'); const ledger = require('./ledger'); const videosweep = require('./videosweep'); const sbcheck = require('./sbcheck'); +const reach = require('./reach'); const marks = require('./marks'); const feedgroup = require('./feedgroup'); // one proof-feed message per purchase: buyer, package, then the tier payouts // one-time claims shared across running instances (deploy overlap) // Google Safe Browsing screen on advertiser destinations const updates = require('./updates'); @@ -567,6 +568,13 @@ async function boot() { // Shares videosweep's alert path on purpose: it names members and their emails, admin only. sbcheck.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert }); sbcheck.start(); + // Destination reachability (2026-10-07): a link that resolved when saved can die later (campaign #163's + // lmgnow.co vanished and 65 members hit a dead end while Safe Browsing read 'cannot resolve' as unknown). + // Refuses a host with no DNS record at save time; pauses live ads whose host is dead two days running. + reach.init({ dataDir: DATA_DIR, fs, path, db, selfHost: 'instantadpay.com', alert: videosweepAlert, site: 'https://instantadpay.com', + message: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'), + mailer, optedIn: email => updates.optedIn(email) }); + reach.start(); toolkit.init({ dataDir: DATA_DIR, ads, accounts, siteConfig, coach, messages, promos, videomaker, chain }); updates.init({ dataDir: DATA_DIR, accounts, releases, mailer, drip, sendy, adminEmail: ADMIN_EMAIL }); audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'InstantAdPay: counter audit', text).catch(() => {}); } }); @@ -2717,6 +2725,8 @@ const server = http.createServer(async (req, res) => { return json(res, r.error ? 400 : 200, r); } if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); } + if (p === '/api/admin/reach' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, reach.adminView()); } + if (p === '/api/admin/reach/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await reach.run({ dry: !!(b && b.dry) })); } if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); } if (p === '/api/admin/tank' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); @@ -4045,6 +4055,7 @@ const server = http.createServer(async (req, res) => { } if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); } { const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); } + { const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); } // charge the best-funded of the member's positions (main + Qualified Start // wallets). A campaign burns from one member id, so the budget must fit inside it. const ids = (await myMemberIds(s)).ids; @@ -4235,6 +4246,7 @@ const server = http.createServer(async (req, res) => { // source pasted here would hand every viewer a black player exactly as #146 did. if (String(b.type) === 'video') { const vc = await videoCheck(b.videoUrl); if (!vc.ok) return json(res, 400, { error: vc.reason }); } { const sb = await sbcheck.check(b.targetUrl); if (!sb.ok) return json(res, 400, { error: sb.reason }); } + { const rc = await reach.check(b.targetUrl); if (!rc.ok) return json(res, 400, { error: rc.reason }); } if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { if (b.type === 'banner' || (b.type === 'login' && b.imageUrl)) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); } const fc = await frameCheck(b.targetUrl);