// 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 };