// LinkSpin link-domain pool (2026-10-10): the short link domains in siteConfig().linkDomains, each assigned to a
// CHANNEL (email / messaging / social / reserve) so a domain that burns on one channel never takes the others with
// it, plus safety checks every six hours (Google Safe Browsing when GSB_API_KEY is set, URIBL + SURBL DNS lists, a
// Telegram-like reachability probe). A domain flagged by GSB or listed by URIBL/SURBL is BURNED: it drops out of
// live() (no new links or pages are handed out on it; existing /r/ codes keep resolving) and the admin is told once.
// State: DATA_DIR/domains.json. Channel map: siteConfig().linkDomainChannels ("host:channel,host:channel" or an
// object); unset = first domain email, second messaging, third social, fourth email, fifth reserve.
'use strict';
const fs = require('fs');
const path = require('path');
const https = require('https');
const dns = require('dns').promises;
let DATA_DIR = null, siteConfig = () => ({}), saveSite = () => {}, notify = () => {}, gsbKey = () => '';
const CHANNELS = ['email', 'messaging', 'social', 'reserve'];
const LABEL = { email: 'Email', messaging: 'Messaging', social: 'Social', reserve: 'Reserve' };
const NOTE = { email: 'Email and safelist mailings', messaging: 'Telegram, WhatsApp and SMS', social: 'X, Facebook, forums and comments', reserve: 'Held back, never handed out' };
const DEFAULT_ORDER = ['email', 'messaging', 'social', 'email', 'reserve'];
const CHECK_EVERY = 6 * 60 * 60 * 1000;
const J = { db: null, FILE: () => path.join(DATA_DIR, 'domains.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, domains: {} }; } if (!this.db.domains) this.db.domains = {}; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db, null, 1)); } catch (e) {} } };
let timer = null;
function init(opts) {
DATA_DIR = opts.dataDir; siteConfig = opts.siteConfig || siteConfig; saveSite = opts.saveSite || saveSite; notify = opts.notify || notify;
gsbKey = opts.gsbKey || (() => String(process.env.GSB_API_KEY || '').trim());
J.load();
if (opts.schedule !== false) { setTimeout(() => checkAll().catch(() => {}), 2 * 60 * 1000); timer = setInterval(() => checkAll().catch(() => {}), CHECK_EVERY); if (timer.unref) timer.unref(); }
}
const norm = h => String(h || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/^www\./, '');
// the configured domains, www stripped and deduped, in the order Marty listed them
function configured() { const seen = new Set(); const out = []; for (const raw of String(siteConfig().linkDomains || '').split(',')) { const h = norm(raw); if (h && !seen.has(h)) { seen.add(h); out.push(h); } } return out; }
function channelMap() {
const raw = siteConfig().linkDomainChannels; const map = {};
if (raw && typeof raw === 'object') { for (const [k, v] of Object.entries(raw)) if (CHANNELS.includes(v)) map[norm(k)] = v; }
else for (const part of String(raw || '').split(',')) { const [k, v] = part.split(':').map(x => String(x || '').trim().toLowerCase()); if (k && CHANNELS.includes(v)) map[norm(k)] = v; }
return map;
}
function channelOf(host, idx, map) { map = map || channelMap(); return map[host] || DEFAULT_ORDER[idx] || 'reserve'; }
function stateOf(host) { return J.db.domains[host] || { checkedAt: 0, gsb: 'unknown', uribl: 'unknown', surbl: 'unknown', reach: 'unknown', burned: false, burnedAt: 0, reason: '' }; }
// every configured domain with its channel and last check
function all() { const map = channelMap(); return configured().map((host, i) => Object.assign({ host, channel: channelOf(host, i, map), label: LABEL[channelOf(host, i, map)], note: NOTE[channelOf(host, i, map)] }, stateOf(host))); }
// the domains that may be handed out: not burned, not reserve (opts.includeReserve keeps reserve ones)
function live(opts) { return all().filter(d => !d.burned && ((opts && opts.includeReserve) || d.channel !== 'reserve')).map(d => d.host); }
// for the member Links screen: live hosts with the channel they are meant for
function hosts() { return all().filter(d => !d.burned && d.channel !== 'reserve').map(d => ({ host: d.host, channel: d.channel, label: d.label, note: d.note })); }
function isBurned(host) { return !!stateOf(norm(host)).burned; }
function setChannel(host, channel) {
host = norm(host); if (!configured().includes(host)) return { error: 'That domain is not in linkDomains.' };
if (!CHANNELS.includes(channel)) return { error: 'Channel must be one of ' + CHANNELS.join(', ') + '.' };
const map = channelMap(); const list = configured(); for (let i = 0; i < list.length; i++) if (!map[list[i]]) map[list[i]] = channelOf(list[i], i, map);
map[host] = channel;
saveSite({ linkDomainChannels: list.map(h => h + ':' + map[h]).join(',') });
return { ok: true, domains: all() };
}
// -- checks
function gsbLookup(host) {
const key = gsbKey(); if (!key) return Promise.resolve('unknown');
return new Promise(resolve => {
const body = JSON.stringify({ client: { clientId: 'linkspin', clientVersion: '1.0' }, threatInfo: { threatTypes: ['MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE'], platformTypes: ['ANY_PLATFORM'], threatEntryTypes: ['URL'], threatEntries: [{ url: 'https://' + host + '/' }, { url: 'http://' + host + '/' }] } });
const rq = https.request({ hostname: 'safebrowsing.googleapis.com', path: '/v4/threatMatches:find?key=' + encodeURIComponent(key), method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, res => {
let d = ''; res.on('data', c => d += c); res.on('end', () => { if (res.statusCode !== 200) return resolve('unknown'); try { const j = JSON.parse(d || '{}'); resolve(Array.isArray(j.matches) && j.matches.length ? 'flagged' : 'clean'); } catch (e) { resolve('unknown'); } });
});
rq.on('timeout', () => { rq.destroy(); resolve('unknown'); }); rq.on('error', () => resolve('unknown')); rq.end(body);
});
}
// an answer means listed, NXDOMAIN means clean, anything else is unknown. 127.0.0.1 is the lists' "query refused /
// public resolver blocked" code, not a listing, so it is unknown too.
async function dnsList(host, zone) {
try { const a = await dns.resolve4(host + '.' + zone); if (!a.length) return 'clean'; if (a.every(ip => ip === '127.0.0.1')) return 'unknown'; return 'listed'; }
catch (e) { return (e && (e.code === 'ENOTFOUND' || e.code === 'ENODATA')) ? 'clean' : 'unknown'; }
}
// did the domain answer a Telegram-like fetch of its front door (preview bots must be able to reach it)
function reach(host) {
return new Promise(resolve => {
const rq = https.get({ hostname: host, path: '/', headers: { 'User-Agent': 'TelegramBot (like TwitterBot)', Accept: 'text/html,*/*' }, timeout: 8000 }, res => { res.resume(); resolve('ok:' + res.statusCode); });
rq.on('timeout', () => { rq.destroy(); resolve('unknown'); }); rq.on('error', () => resolve('unknown'));
});
}
async function check(host) {
host = norm(host); if (!configured().includes(host)) return { error: 'That domain is not in linkDomains.' };
const [gsb, uribl, surbl, rch] = await Promise.all([gsbLookup(host), dnsList(host, 'multi.uribl.com'), dnsList(host, 'multi.surbl.org'), reach(host)]);
const prev = stateOf(host); const reasons = [];
if (gsb === 'flagged') reasons.push('Google Safe Browsing flagged it'); if (uribl === 'listed') reasons.push('listed on URIBL'); if (surbl === 'listed') reasons.push('listed on SURBL');
const burnedNow = reasons.length > 0;
const rec = Object.assign({}, prev, { checkedAt: Date.now(), gsb, uribl, surbl, reach: rch });
// a burned domain stays burned when the lists come clean again: lists flap, and putting it back is an admin decision (clear())
if (burnedNow) { rec.reason = reasons.join(', '); if (!prev.burned) { rec.burned = true; rec.burnedAt = Date.now(); rec.notified = false; } }
J.db.domains[host] = rec; J.save();
if (rec.burned && !rec.notified) {
rec.notified = true; J.save();
const list = all(); const alive = list.filter(d => !d.burned && d.channel !== 'reserve').map(d => d.host);
const ch = list.find(d => d.host === host); const text = '⚠️ LinkSpin · link domain ' + host + ' (' + (ch ? ch.label : '') + ' channel) is BURNED: ' + rec.reason + '. It is out of the pool for new links and pages; existing /r/ links still resolve. Live domains now: ' + (alive.join(', ') || 'none') + '. Admin > Link domains to review or clear.';
try { await notify(text, host, rec); } catch (e) {}
}
return { ok: true, domain: Object.assign({ host }, rec) };
}
async function checkAll() { const out = []; for (const h of configured()) { try { out.push(await check(h)); } catch (e) { out.push({ host: h, error: e.message }); } } return out; }
// admin override: a list came clean again or the flag was a mistake; the domain goes back into the pool
function clear(host) { host = norm(host); const rec = stateOf(host); rec.burned = false; rec.burnedAt = 0; rec.reason = ''; rec.notified = false; J.db.domains[host] = rec; J.save(); return { ok: true, domains: all() }; }
// admin can also pull a domain by hand (a complaint, a flap elsewhere) without waiting for a list
function burn(host, why) { host = norm(host); if (!configured().includes(host)) return { error: 'That domain is not in linkDomains.' }; const rec = stateOf(host); rec.burned = true; rec.burnedAt = Date.now(); rec.reason = String(why || 'pulled by admin').slice(0, 200); rec.notified = true; J.db.domains[host] = rec; J.save(); return { ok: true, domains: all() }; }
module.exports = { init, CHANNELS, LABEL, NOTE, all, live, hosts, isBurned, setChannel, check, checkAll, clear, burn, configured };