// Destination health checks (LinkSpin, 2026-10-10): every 30 minutes each ACTIVE destination of every rotation // (and the fallback) is fetched with a browser-like UA, HEAD first then GET when the server refuses HEAD or when // the page is HTML (the body is what tells a parked page from a live one). States: ok, slow (over 6 s), dead // (network error, timeout, 404/410/5xx), parked (parking-page signatures). Three failing checks in a row pause // the destination (d.active = false, d.autoPaused = when); a paused one is re-checked every 6 hours and comes back // on its own after two clean passes, but only when LinkSpin paused it, never when the owner did. The last live // destination of a rotation with no fallback is never paused: a redirect to something beats a dead end. // frameBlocked is informational: LinkSpin links run inside traffic-exchange frames, so the owner wants to know. // At most 4 requests in flight at once. A small event log (Central-time day keys) sits at DATA_DIR/health-log.json. const fs = require('fs'); const path = require('path'); let rotator = null, DATA_DIR = null, notify = null; const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36 LinkSpinHealth/1.0'; const TIMEOUT = 10000, SLOW = 6000, MAX_REDIRECTS = 5, PARALLEL = 4, FAILS_TO_PAUSE = 3, PASSES_TO_RESUME = 2; const RECHECK_PAUSED = 6 * 3600 * 1000, MANUAL_GAP = 60 * 1000; const PARKED = /domain is for sale|this domain (?:is|may be) for sale|parked free|sedoparking|sedo\.com\/search|buy this domain|godaddy\.com\/parked|hugedomains|afternic|\bdan\.com\b|parkingcrew|bodis\.com|domain parking|this domain has expired|\s*(?:default web page|welcome to nginx!?|apache2 .* default page|index of \/|website coming soon|domain default page)\s*<\/title>/i; const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const L = { file: () => path.join(DATA_DIR, 'health-log.json'), db: null, load() { try { this.db = JSON.parse(fs.readFileSync(this.file(), 'utf8')); } catch (e) { this.db = { events: [] }; } }, add(ev) { if (!this.db) this.load(); this.db.events.push(Object.assign({ ts: Date.now(), day: ctDay(Date.now()) }, ev)); if (this.db.events.length > 500) this.db.events = this.db.events.slice(-400); try { fs.writeFileSync(this.file(), JSON.stringify(this.db)); } catch (e) {} } }; function init(opts) { rotator = opts.rotator; DATA_DIR = opts.dataDir; notify = opts.notify || null; L.load(); } // one request with a hard timeout; returns the Response or throws async function req(url, method, signalMs) { const ac = new AbortController(); const t = setTimeout(() => ac.abort(), signalMs || TIMEOUT); try { return await fetch(url, { method, redirect: 'manual', signal: ac.signal, headers: { 'User-Agent': UA, Accept: 'text/html,application/xhtml+xml,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.8' } }); } finally { clearTimeout(t); } } // follow up to MAX_REDIRECTS by hand (so the chain is bounded and the final URL is known) async function follow(url, method) { let u = url, hops = 0, res; for (;;) { res = await req(u, method); if (res.status >= 300 && res.status < 400 && res.headers.get('location') && hops < MAX_REDIRECTS) { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} u = new URL(res.headers.get('location'), u).toString(); hops++; continue; } return { res, finalUrl: u, hops }; } } // read at most 64 KB of a body async function head64k(res) { if (!res.body) return ''; const reader = res.body.getReader(); const chunks = []; let n = 0; try { while (n < 65536) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.length; } } catch (e) {} try { reader.cancel().catch(() => {}); } catch (e) {} return Buffer.concat(chunks.map(c => Buffer.from(c))).toString('utf8'); } const frameBlocked = h => { const xfo = String(h.get('x-frame-options') || '').toLowerCase(); if (/deny|sameorigin/.test(xfo)) return true; const csp = String(h.get('content-security-policy') || '').toLowerCase(); const m = /frame-ancestors([^;]*)/.exec(csp); if (m) { const v = m[1].trim(); return !(v === '*' || /(^|\s)https?:(\s|$)|\*/.test(v)); } return false; }; // classify one URL -> { state, code, ms, note, frameBlocked, finalUrl } async function check(url) { const t0 = Date.now(); let out = { state: 'dead', code: 0, ms: 0, note: '', frameBlocked: false, finalUrl: url }; try { let { res, finalUrl } = await follow(url, 'HEAD'); let ms = Date.now() - t0; out.finalUrl = finalUrl; const ctype = () => String(res.headers.get('content-type') || '').toLowerCase(); let body = ''; if (res.status === 405 || res.status === 501 || res.status === 403 || (res.status >= 200 && res.status < 300 && /html/.test(ctype()))) { // the server refuses HEAD, or the page is HTML (we need the body to spot a parking page) try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} const t1 = Date.now(); const g = await follow(url, 'GET'); res = g.res; out.finalUrl = g.finalUrl; ms = Date.now() - t1; if (/html/.test(ctype())) body = await head64k(res); else { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} } } else { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} } out.code = res.status; out.ms = ms; out.frameBlocked = frameBlocked(res.headers); if (res.status === 404 || res.status === 410 || res.status >= 500) { out.state = 'dead'; out.note = 'HTTP ' + res.status; } else if (body && PARKED.test(body)) { out.state = 'parked'; out.note = 'Parked page'; } else if (res.status >= 200 && res.status < 400) { out.state = ms > SLOW ? 'slow' : 'ok'; out.note = ms > SLOW ? 'Slow, ' + (ms / 1000).toFixed(1) + ' s' : ''; } else { out.state = 'ok'; out.note = 'HTTP ' + res.status + ' to our checker (a bot wall, most likely); visitors may still get through'; } } catch (e) { out.ms = Date.now() - t0; out.state = 'dead'; out.note = (e && e.name === 'AbortError') ? 'No answer in 10 s' : ('Could not connect' + (e && e.cause && e.cause.code ? ' (' + e.cause.code + ')' : '')); } return out; } const failing = s => s === 'dead' || s === 'parked'; const when = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' }); // apply a fresh result to a destination record: counters, auto-pause, auto-resume. Returns a change note or null. function apply(r, d, c) { const prev = d.health || {}; const now = Date.now(); const fails = failing(c.state) ? (prev.fails || 0) + 1 : 0; const passes = failing(c.state) ? 0 : (prev.passes || 0) + 1; d.health = { state: c.state, code: c.code, ms: c.ms, checkedAt: now, fails, passes, note: c.note, frameBlocked: !!c.frameBlocked }; if (d.active && fails >= FAILS_TO_PAUSE) { const others = r.destinations.filter(x => x !== d && x.active); if (!others.length && !r.fallback) { d.health.note = (c.note || c.state) + '. Kept live: it is the only destination and there is no fallback.'; return null; } d.active = false; d.autoPaused = now; d.health.passes = 0; L.add({ ev: 'pause', r: r.id, d: d.id, url: d.url, state: c.state, note: c.note }); return { kind: 'paused', text: (c.state === 'parked' ? 'Parked page' : 'Dead page') + ', auto-paused ' + when(now) }; } if (!d.active && d.autoPaused && passes >= PASSES_TO_RESUME) { d.active = true; delete d.autoPaused; d.health.fails = 0; L.add({ ev: 'resume', r: r.id, d: d.id, url: d.url, state: c.state }); return { kind: 'resumed', text: 'Back up, resumed ' + when(now) }; } return null; } async function tell(r, d, change) { if (!notify || !change || change.kind !== 'paused' || /^demo:/.test(r.owner)) return; const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); const html = '<p>LinkSpin paused one destination in your link <b>' + esc(r.name) + '</b> (/r/' + esc(r.code) + ') because it failed three checks in a row.</p>' + '<p><span style="font-family:monospace">' + esc(d.url) + '</span><br>' + esc(d.health.note || d.health.state) + '</p>' + '<p>Visitors keep flowing to your other destinations' + (r.fallback ? ' and the fallback' : '') + '. If the page comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the address or resume it yourself under Links.</p>'; try { await notify(r.owner, 'A destination in ' + r.name + ' was paused', html); } catch (e) {} } // run a list of jobs, at most PARALLEL at once async function runAll(jobs) { let i = 0; const workers = new Array(Math.min(PARALLEL, jobs.length)).fill(0).map(async () => { while (i < jobs.length) { const j = jobs[i++]; try { await j(); } catch (e) {} } }); if (workers.length) await Promise.all(workers); } let running = false; // the scheduled pass: active destinations + fallbacks every time; auto-paused destinations when 6 h have gone by async function tick() { if (running || !rotator) return { skipped: true }; running = true; const now = Date.now(); const jobs = []; let changed = false, n = 0; try { for (const r of rotator.rawRotations()) { for (const d of r.destinations) { const due = d.active || (d.autoPaused && (!d.health || now - (d.health.checkedAt || 0) >= RECHECK_PAUSED)); if (!due) continue; jobs.push(async () => { const c = await check(d.url); const ch = apply(r, d, c); changed = true; n++; if (ch) await tell(r, d, ch); }); } if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; changed = true; }); } await runAll(jobs); } finally { running = false; if (changed) rotator.save(); } return { checked: n }; } // "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback const lastManual = new Map(); async function checkRotation(owner, id) { const r = rotator.findMine(owner, id); if (!r) return { error: 'No such rotation.' }; const last = lastManual.get(r.id) || 0; if (Date.now() - last < MANUAL_GAP) return { error: 'Checked less than a minute ago. Give it a moment.' }; lastManual.set(r.id, Date.now()); const jobs = r.destinations.map(d => async () => { const c = await check(d.url); const ch = apply(r, d, c); if (ch) await tell(r, d, ch); }); if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; }); await runAll(jobs); rotator.save(); return { ok: true, rotation: rotator.pub(r) }; } function recent() { if (!L.db) L.load(); return L.db.events.slice(-50).reverse(); } module.exports = { init, tick, check, checkRotation, recent };