Files
vbb/safety.js

140 lines
8.5 KiB
JavaScript

// Link + image checks for posted banners (Downline Banners' safety.js, sized for VBB).
// Links: https only, a real public hostname, no shorteners, and (when probed) a page that answers and allows frames.
// Images: a real PNG/JPG/GIF at exactly 125x125 (or 250x250 retina) and at most 100 KB. An https image address is
// fetched once, checked the same way and stored as an upload, so the splash never hotlinks someone else's server.
const net = require('net');
const dns = require('dns');
const https = require('https');
const MAX_UPLOAD = 100 * 1024;
const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i;
// shorteners and redirectors hide where a click goes; a member link must show its real destination
const REDIRECTORS = /(^|\.)(bit\.ly|tinyurl\.com|t\.co|goo\.gl|is\.gd|cutt\.ly|ow\.ly|rebrand\.ly|shorturl\.at|rb\.gy|s\.id|t\.ly|v\.gd|bl\.ink|tiny\.cc)$/i;
function checkLink(raw, what) {
what = what || 'Link';
const s = String(raw || '').trim();
if (!s) return { error: what + ' is empty.' };
if (s.length > 600) return { error: what + ' is too long (600 characters max).' };
if (/[\s<>"'`\\]/.test(s)) return { error: what + ' has spaces or characters a web address cannot have.' };
let u; try { u = new URL(s); } catch (e) { return { error: what + ' is not a valid web address.' }; }
if (u.protocol !== 'https:') return { error: what + ' must start with https://' };
if (u.username || u.password) return { error: what + ' cannot contain a username or password.' };
const h = u.hostname.toLowerCase().replace(/\.$/, '');
if (net.isIP(h.replace(/^\[|\]$/g, ''))) return { error: what + ' must use a domain name, not an IP address.' };
if (!h.includes('.') || BAD_HOST.test(h)) return { error: what + ' must point to a public website.' };
if (!/^[a-z0-9.-]+$/.test(h) && !/^xn--/.test(h)) return { error: what + ' has an unusual domain name.' };
if (REDIRECTORS.test(h)) return { error: 'Use the real destination, not a link shortener.' };
if (u.port && !['443', ''].includes(u.port)) return { error: what + ' must use the normal https port.' };
return { ok: true, url: u.toString() };
}
function imageInfo(buf) {
if (!buf || buf.length < 24) return null;
if (buf.slice(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
return { type: 'png', ext: '.png', w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
if (buf.slice(0, 6).toString('latin1') === 'GIF87a' || buf.slice(0, 6).toString('latin1') === 'GIF89a')
return { type: 'gif', ext: '.gif', w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) };
if (buf[0] === 0xff && buf[1] === 0xd8) {
let i = 2;
while (i + 9 < buf.length) {
if (buf[i] !== 0xff) { i++; continue; }
const m = buf[i + 1];
if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { type: 'jpg', ext: '.jpg', h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) };
if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue; }
i += 2 + buf.readUInt16BE(i + 2);
}
return { type: 'jpg', ext: '.jpg', w: 0, h: 0 };
}
return null;
}
function checkImage(buf) {
if (!buf || !buf.length) return { error: 'No file received.' };
if (buf.length > MAX_UPLOAD) return { error: 'That file is ' + Math.ceil(buf.length / 1024) + ' KB. The limit is 100 KB.' };
const info = imageInfo(buf);
if (!info) return { error: 'Use a PNG, JPG or GIF image.' };
const ok = (info.w === 125 && info.h === 125) || (info.w === 250 && info.h === 250);
if (!ok) return { error: 'The image is ' + info.w + 'x' + info.h + '. It must be 125x125 (or 250x250).' };
return { ok: true, info };
}
// ---- outbound requests only to public addresses (the DNS answer used for the connection is the one checked) ----
function privateIp(ip) {
if (net.isIPv4(ip)) {
const [a, b] = ip.split('.').map(Number);
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31)
|| (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
}
const s = ip.toLowerCase();
if (s.startsWith('::ffff:')) return privateIp(s.slice(7));
return s === '::' || s === '::1' || s.startsWith('fc') || s.startsWith('fd') || s.startsWith('fe80') || s.startsWith('ff');
}
// Node 20's https agent asks for every address (opts.all, for happy eyeballs) and expects an array back; answering with one
// address broke every link check (2026-11-15: no text ad could be posted). Answer in the shape asked for, private ones refused.
function safeLookup(host, opts, cb) {
if (typeof opts === 'function') { cb = opts; opts = {}; }
dns.lookup(host, Object.assign({}, opts, { all: true }), (err, list) => {
if (err) return cb(err);
if (!list.length || list.some(a => privateIp(a.address))) return cb(new Error('private address'));
if (opts && opts.all) return cb(null, list);
cb(null, list[0].address, list[0].family);
});
}
// GET with a size cap, a timeout and no redirects followed (a redirect is reported so the caller can decide)
function get(url, maxBytes, timeoutMs) {
return new Promise(resolve => {
let done = false; const fin = v => { if (!done) { done = true; resolve(v); } };
let req;
try {
req = https.get(url, { lookup: safeLookup, timeout: timeoutMs || 5000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; VBBCheck/1.0; +https://viralbannerblitz.com)', Accept: '*/*' } }, res => {
const out = { status: res.statusCode, headers: res.headers, location: res.headers.location || null };
if (!maxBytes) { res.destroy(); return fin(out); }
const ch = []; let n = 0;
res.on('data', c => { n += c.length; if (n > maxBytes) { res.destroy(); return fin(Object.assign(out, { tooBig: true })); } ch.push(c); });
res.on('end', () => fin(Object.assign(out, { body: Buffer.concat(ch) })));
res.on('error', () => fin(Object.assign(out, { error: 'read' })));
});
req.on('timeout', () => { req.destroy(); fin({ error: 'timeout' }); });
req.on('error', e => fin({ error: /private address/.test(e.message) ? 'private' : 'unreachable' }));
} catch (e) { fin({ error: 'unreachable' }); }
});
}
// does this response allow being shown inside a frame on another site?
function frameVerdict(headers) {
const h = k => String(headers[k] || '').toLowerCase();
if (h('x-frame-options')) return false;
const fa = /frame-ancestors([^;]*)/.exec(h('content-security-policy'));
return !(fa && !/\*|https:/.test(fa[1]));
}
// the target link must answer and allow frames (traffic exchanges and the splash preview show sites in a frame). Up to 3 redirects.
async function probeLink(url) {
let cur = url;
for (let hop = 0; hop < 4; hop++) {
const r = await get(cur, 0, 6000);
if (r.error === 'private') return { error: 'That link points to a private network address.' };
if (r.error) return { error: 'We could not reach that link. Check it opens in your browser and try again.' };
if (r.status >= 300 && r.status < 400 && r.location) {
let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { error: 'That link redirects somewhere invalid.' }; }
const c = checkLink(next, 'The page your link redirects to'); if (c.error) return c;
cur = c.url; continue;
}
if (r.status >= 400) return { error: 'That link answered with an error (' + r.status + '). Use a page that loads.' };
if (!frameVerdict(r.headers)) return { error: 'That site does not allow being shown in a frame, so it cannot rotate here. Use a page that allows frames (most landing pages and LinkSpin links do).' };
return { ok: true };
}
return { error: 'That link redirects too many times.' };
}
// an https image address: fetched once, checked like an upload. -> { ok, buf, info } or { error }
async function fetchImage(url) {
const r = await get(url, MAX_UPLOAD, 6000);
if (r.error === 'private') return { error: 'That image address points to a private network address.' };
if (r.error) return { error: 'We could not download that image. Check the address or upload the file instead.' };
if (r.tooBig) return { error: 'That image is over 100 KB.' };
if (r.status !== 200) return { error: 'The image address answered ' + r.status + '. Use a direct link to the image file, or upload it.' };
const c = checkImage(r.body); if (c.error) return c;
return { ok: true, buf: r.body, info: c.info };
}
module.exports = { checkLink, checkImage, imageInfo, frameVerdict, probeLink, fetchImage, privateIp, MAX_UPLOAD };