// 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'); // Banner Spin (phase 3, 2026-10-20): the same pass also checks every live banner. Its IMAGE must load as an image // (PNG / GIF / JPEG / WebP by magic bytes, an uploaded file read from disk, a pasted one fetched) at the Banner Spin's size, // and its TARGET must pass check() above (a spin-link target only has to exist: its destinations are checked as spin // links). Same counters: three failing checks pause the banner (b.active = false, b.autoPaused), two clean passes resume // it, auto-paused ones are re-checked every 6 hours, and the last live banner of a Banner Spin is NEVER auto-paused. let rotator = null, DATA_DIR = null, notify = null, bannerspin = 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|
LinkSpin paused one destination in your link ' + esc(r.name) + ' (/r/' + esc(r.code) + ') because it failed three checks in a row.
' + '' + esc(d.url) + '
' + esc(d.health.note || d.health.state) + '
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.
'; 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); } // ── Banner Spin banners ── const MAGIC = buf => buf.length >= 12 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 ? 'image/png' : buf.length >= 6 && buf.slice(0, 4).toString('latin1') === 'GIF8' ? 'image/gif' : buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff ? 'image/jpeg' : buf.length >= 12 && buf.slice(0, 4).toString('latin1') === 'RIFF' && buf.slice(8, 12).toString('latin1') === 'WEBP' ? 'image/webp' : ''; async function headBytes(res, max) { if (!res.body) return Buffer.alloc(0); const reader = res.body.getReader(); const chunks = []; let n = 0; try { while (n < max) { const { done, value } = await reader.read(); if (done) break; chunks.push(Buffer.from(value)); n += value.length; } } catch (e) {} try { reader.cancel().catch(() => {}); } catch (e) {} return Buffer.concat(chunks); } // one banner image -> { state: ok | broken | size, note, w, h, ms } async function checkImage(src, size) { const t0 = Date.now(); const [W, H] = size || [0, 0]; const where = bannerspin && bannerspin.imageSource ? bannerspin.imageSource(src) : null; if (!where) return { state: 'broken', note: 'No image address', w: 0, h: 0, ms: 0 }; let buf, type = ''; if (where.file) { try { buf = fs.readFileSync(where.file); } catch (e) { return { state: 'broken', note: 'The uploaded image file is missing', w: 0, h: 0, ms: Date.now() - t0 }; } } else { try { const { res } = await follow(where.url, 'GET'); if (res.status >= 400 || res.status < 200) { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} return { state: 'broken', note: 'The image address answers HTTP ' + res.status, w: 0, h: 0, ms: Date.now() - t0 }; } type = String(res.headers.get('content-type') || '').toLowerCase(); buf = await headBytes(res, 65536); } catch (e) { return { state: 'broken', note: (e && e.name === 'AbortError') ? 'The image did not load in 10 s' : 'The image address could not be reached', w: 0, h: 0, ms: Date.now() - t0 }; } } const mime = MAGIC(buf); const ms = Date.now() - t0; if (!mime) return { state: 'broken', note: /^text\/html/.test(type) ? 'The image address returns a web page, not an image' : 'The file is not a readable image', w: 0, h: 0, ms }; const d = mime === 'image/webp' ? { w: 0, h: 0 } : bannerspin.dims(buf, mime); // a size mismatch is a warning, not a failure (2026-10-20): the builder allows it with a warning, so live banners must not be auto-paused for it if (d.w && d.h && W && (d.w !== W || d.h !== H)) return { state: 'ok', warn: 'size', note: 'The image is ' + d.w + 'x' + d.h + '; this Banner Spin is ' + W + 'x' + H, w: d.w, h: d.h, ms }; return { state: 'ok', note: d.w ? '' : 'Loads as an image (size not readable)', w: d.w, h: d.h, ms }; } // one banner target -> the spin-link check shape. A spin link only has to still exist. async function checkTarget(s, b) { if (b.link) { const r = rotator && rotator.rawRotations ? rotator.rawRotations().find(x => x.id === b.link && x.owner === s.owner) : null; return r ? { state: 'ok', code: 0, ms: 0, note: 'Spin link /r/' + r.code + ' (its pages are checked as spin links)' } : { state: 'dead', code: 0, ms: 0, note: 'The spin link this banner points at was deleted' }; } if (!b.target) return { state: 'dead', code: 0, ms: 0, note: 'No target set' }; return check(String(b.target).replace(/\{[a-z0-9_]{1,24}\}/gi, 'x')); // macros filled with a placeholder, like a real click would } // apply both results to the banner: counters, auto-pause (never the last live banner), auto-resume function applyBanner(s, b, img, tgt) { const prev = b.health || {}; const now = Date.now(); const bad = img.state !== 'ok' || failing(tgt.state); const fails = bad ? (prev.fails || 0) + 1 : 0, passes = bad ? 0 : (prev.passes || 0) + 1; const note = img.state !== 'ok' ? img.note : failing(tgt.state) ? (tgt.state === 'parked' ? 'Target is a parked page' : 'Target page is down') + (tgt.note ? ' (' + tgt.note + ')' : '') : tgt.state === 'slow' ? 'Target is slow' + (tgt.note ? ' (' + tgt.note + ')' : '') : ''; b.health = { state: img.state !== 'ok' ? 'image' : tgt.state, note, checkedAt: now, fails, passes, image: { state: img.state, note: img.note || '', w: img.w || 0, h: img.h || 0 }, target: { state: tgt.state, code: tgt.code || 0, ms: tgt.ms || 0, note: tgt.note || '' } }; if (b.active && !b.adminOff && fails >= FAILS_TO_PAUSE) { const others = s.banners.filter(x => x !== b && x.active && !x.adminOff); if (!others.length) { b.health.note = note + '. Kept live: it is the last live banner in this Banner Spin.'; return null; } b.active = false; b.autoPaused = now; b.health.passes = 0; L.add({ ev: 'pause', bs: s.id, b: b.id, url: b.image, state: b.health.state, note }); return { kind: 'paused', text: note + ', auto-paused ' + when(now) }; } if (!b.active && b.autoPaused && passes >= PASSES_TO_RESUME) { b.active = true; delete b.autoPaused; b.health.fails = 0; L.add({ ev: 'resume', bs: s.id, b: b.id, url: b.image, state: b.health.state }); return { kind: 'resumed', text: 'Back up, resumed ' + when(now) }; } return null; } async function tellBanner(s, b, change) { if (!notify || !change || change.kind !== 'paused') return; const esc = x => String(x).replace(/&/g, '&').replace(//g, '>'); const html = 'LinkSpin paused one banner in your Banner Spin ' + esc(s.name) + ' because it failed three checks in a row.
' + '' + esc(b.label || 'Banner ' + b.id) + '
' + esc((b.health && b.health.note) || '') + '
Your other banners keep rotating. If it comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the image or the target, or resume it yourself, under Links, Banner Spins.
'; try { await notify(s.owner, 'A banner in ' + s.name + ' was paused', html); } catch (e) {} } // the banner jobs for one pass. force = check auto-paused ones now too (admin "run checks"); onlyId = one Banner Spin function bannerJobs(force, onlyId, onChange) { if (!bannerspin || !bannerspin.rawSpins || (bannerspin.live && !bannerspin.live())) return []; const now = Date.now(); const jobs = []; for (const s of bannerspin.rawSpins()) { if (s.adminOff || (onlyId && s.id !== Number(onlyId))) continue; const size = bannerspin.SIZES[s.size]; for (const b of s.banners) { if (b.adminOff) continue; const due = (b.active) || (b.autoPaused && (force || !b.health || now - (b.health.checkedAt || 0) >= RECHECK_PAUSED)); if (!due) continue; jobs.push(async () => { const [img, tgt] = await Promise.all([checkImage(b.image, size), checkTarget(s, b)]); const ch = applyBanner(s, b, img, tgt); onChange(); if (ch) await tellBanner(s, b, ch); }); } } return jobs; } // admin "run the checks now" for Banner Spins (no once-a-minute limit; auto-paused banners are re-checked at once) let bannerRunning = false; async function checkBannerSpins(opts) { opts = opts || {}; if (bannerRunning) return { error: 'A check is already running.' }; bannerRunning = true; let n = 0; try { const jobs = bannerJobs(true, opts.id, () => { n++; }); await runAll(jobs); } finally { bannerRunning = false; if (n && bannerspin) bannerspin.save(); } return { ok: true, checked: n }; } 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, bn = 0; try { jobs.push(...bannerJobs(false, 0, () => { bn++; })); // Banner Spin banners, same pass, same 4-at-once limit 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(); if (bn && bannerspin) bannerspin.save(); } return { checked: n, banners: bn }; } // "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, checkImage, checkBannerSpins };