diff --git a/health.js b/health.js
new file mode 100644
index 0000000..259d46c
--- /dev/null
+++ b/health.js
@@ -0,0 +1,149 @@
+// 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, '>');
+ const html = '
LinkSpin paused one destination in your link ' + esc(r.name) + ' (/r/' + esc(r.code) + ') because it failed three checks in a row.
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);
+}
+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 };
diff --git a/public/assets/links.js b/public/assets/links.js
index 1be0972..3704d58 100644
--- a/public/assets/links.js
+++ b/public/assets/links.js
@@ -7,6 +7,67 @@
const clicks7 = r => r.hits7 || 0;
const health = r => r.paused ? { cls: 'warn', t: 'PAUSED' } : !r.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE DESTINATION' } : { cls: 'ok', t: 'LIVE' };
+ // ── dayparting: grid = 7 strings of 24 chars '1'/'0', index 0 = Sunday; null = always on ──
+ const ALL = '1'.repeat(24), NONE = '0'.repeat(24);
+ const rowOf = (a, b) => { let s = ''; for (let h = 0; h < 24; h++) s += h >= a && h < b ? '1' : '0'; return s; };
+ const PRESETS = { always: null, business: [NONE, rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), NONE], evenings: new Array(7).fill(rowOf(17, 23)), weekends: [ALL, NONE, NONE, NONE, NONE, NONE, ALL] };
+ const ZONES = [['visitor', "Visitor's local time"], ['America/Chicago', 'Chicago (Central)'], ['America/New_York', 'New York (Eastern)'], ['America/Los_Angeles', 'Los Angeles (Pacific)'], ['Europe/London', 'London'], ['Europe/Berlin', 'Berlin'], ['Asia/Kolkata', 'India'], ['Asia/Manila', 'Manila'], ['Asia/Singapore', 'Singapore'], ['Australia/Sydney', 'Sydney']];
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ORDER = [1, 2, 3, 4, 5, 6, 0];
+ const ranges = s => { const out = []; let a = -1; for (let h = 0; h <= 24; h++) { const on = h < 24 && s[h] === '1'; if (on && a < 0) a = h; if (!on && a >= 0) { out.push(a + '-' + h); a = -1; } } return out.join(', '); };
+ function hoursText(hours) {
+ if (!hours || hours.every(s => s === ALL)) return 'Always on';
+ if (hours.every(s => s === hours[0])) return 'Every day ' + ranges(hours[0]);
+ const wk = [1, 2, 3, 4, 5], we = [0, 6], off = s => !s.includes('1');
+ if (wk.every(i => hours[i] === hours[1]) && we.every(i => off(hours[i]))) return 'Mon-Fri ' + ranges(hours[1]);
+ if (wk.every(i => off(hours[i])) && hours[0] === hours[6]) return 'Weekends' + (hours[6] === ALL ? '' : ' ' + ranges(hours[6]));
+ const n = hours.join('').split('1').length - 1; return 'Custom, ' + n + ' of 168 hours';
+ }
+ const tzText = tz => !tz || tz === 'visitor' ? "visitor's local time" : ((ZONES.find(z => z[0] === tz) || [])[1] || tz.split('/').pop().replace(/_/g, ' ')) + ' time';
+ const hoursChip = (hours, tz) => hoursText(hours) + (hours ? ', ' + tzText(tz) : '');
+ // the inline 7 x 24 editor. o = { hours, tz (undefined = no zone picker), heat (7x24 counts), best, onSave(hours, tz), onCancel }
+ function hoursEditor(host, o) {
+ let grid = (o.hours || new Array(7).fill(ALL)).map(s => s.split('')); let tz = o.tz || 'visitor';
+ const other = tz !== 'visitor' && !ZONES.some(z => z[0] === tz);
+ const max = o.heat ? Math.max(1, ...o.heat.map(d => Math.max(...d))) : 0;
+ host.innerHTML = '
' + (o.best ? (o.best.ready ? 'Your best hours are the top quarter of weekday-hour cells by unique visitors over the last 30 days (' + fmt(o.best.hits) + ' clicks). Tinted cells show where your clicks land.' : '"Use my best hours" unlocks after ' + fmt(o.best.need) + ' clicks in 30 days; ' + fmt(o.best.hits) + ' so far.') : '') + '
Macros in a destination are filled per visitor: {clickid} {subid} {s1}…{s5} {source} {country} {device} {lsid}. Example: https://tracker.example/?cid={clickid}&src={source}
-
+
+
-
Clicks by hour, UTC, all time
0006121823
Hour rules (open a destination only at set hours) come in the next pass; this is where they will live.
+
Hours this link is on
Outside these hours visitors go to the fallback. Each destination can have its own hours too (the clock button on its row). Tap a cell to flip it, drag to paint, or start from a preset.