Refuel Kit (Fuel Your Offers stage 3, Marty approved 2026-10-24): monthly members-only banner sets for InstantAdPay, unlocked by the member's next counted refuel. kit.js (the same file ships in LinkSpin): kits as data in DATA_DIR/kits (month, theme, released, one base image each for 728x90 300x250 468x60 160x600 1200x630, this site's own program only); a counted refuel unlocks the kit of its Central month (refuel.js now keeps rec.kits month -> streak month, exposed in view.kits); kits stay usable after their month, a missed refuel only stops new ones, a kit released early waits for its month. Server-side personalization per member with ffmpeg (badge renderer approach): @username on a dark strip + a QR code (qrcode package) to their own /join link at fixed spots per size; cached in DATA_DIR/kits/out and served publicly at /kitimg/<hmac>.png|jpg|gif (only files rendered for entitled members; names cannot be guessed and change with the art). Streak month 3+ adds an animated GIF (three-frame loop), month 6+ records a BannerKitAI custom-banners credit (entitlement + note, no integration). Member: Promo tools Refuel Kit card (fuel.js?v=20261024kit): Make mine, Animated, Download, Copy image link, "Use in an IAP banner campaign" (opens Campaigns and prefills banner type, size, name, image URL and the member's link). Admin: Settings > Refuel Kit (admin-kits.js): month + theme, upload the five sizes, "Use placeholder art (public/banners)", preview with any username (still or animated), release (needs all five sizes). Behind the refuelStreak switch (myKits { on:false } while off). Chatbot CANNED + FACTS mention the kit. No paid image APIs; placeholder art = existing public/banners. qa/refuel-kit.test.cjs 8 checks (admin validation, switch, unlock by month, Pit Stop does not unlock, kits persist, GIF at 3, credit at 6, exact render sizes for all five, GIF loop, cache, unguessable serving, preview).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-24 05:44:27 -05:00
parent 6cc868d10a
commit 50337bfbbc
9 changed files with 488 additions and 5 deletions
+218
View File
@@ -0,0 +1,218 @@
// The Refuel Kit (Fuel Your Offers stage 3, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
// LinkSpin; each site keeps ITS OWN program's kits (InstantAdPay art promotes InstantAdPay, LinkSpin art promotes
// LinkSpin, never mixed).
//
// A kit is one month's members-only banner set: { month 'YYYY-MM', theme, released, sizes 728x90 300x250 468x60 160x600
// 1200x630 } with one base image per size, stored as data in DATA_DIR/kits/ (kits.json + <month>/<size>.<ext>).
// Admin uploads the base art and previews the personalization; nothing here generates art (real art is Marty's).
//
// Who gets which kit: a counted refuel (the streak in refuel.js, InstantAdPay is the source of truth) unlocks the kit
// of the Central-time month it landed in. The entitlement arrives as { months: { 'YYYY-MM': streakMonthAtUnlock } }
// from opts.entitled(email). Kits stay usable after their month; missing a refuel only stops NEW kits.
// streak month 3+ at unlock an animated GIF version of each banner size
// streak month 6+ at unlock a "custom banners" credit for BannerKitAI: the entitlement and a note only, no integration
//
// Personalized on the server per member: their @username and a QR code to their own link are drawn onto each banner
// with ffmpeg (the badge renderer's approach). Rendered files are cached in DATA_DIR/kits/out/<hash>.<ext> and served
// publicly at /kitimg/<hash>.<ext> (ad networks and IAP banner campaigns load them by URL); the hash is an HMAC of
// member + kit + size + variant + base-art version, so it cannot be guessed and changes when the art changes.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const SIZES = { '728x90': [728, 90], '300x250': [300, 250], '468x60': [468, 60], '160x600': [160, 600], '1200x630': [1200, 630] };
const ORDER = ['728x90', '300x250', '468x60', '160x600', '1200x630'];
// where the QR and the name go on each size: q = QR box (x, y, side), t = name (x expr, y expr, font px)
const LAYOUT = {
'728x90': { q: ['W-84', 6, 78], t: ['W-96-tw', 'H-30', 18] },
'468x60': { q: ['W-58', 4, 52], t: ['W-68-tw', 'H-24', 14] },
'300x250': { q: ['W-82', 'H-82', 76], t: ['8', 'H-30', 16] },
'160x600': { q: ['(W-120)/2', 'H-128', 120], t: ['(W-tw)/2', 'H-160', 16] },
'1200x630': { q: ['W-212', 'H-212', 182], t: ['32', 'H-66', 34] },
};
let X = {}, DIR = null, OUT = null, FILE = null, SALT = null;
const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
const norm = e => String(e || '').trim().toLowerCase();
function init(opts) {
X = opts || {}; DIR = path.join(X.dataDir, 'kits'); OUT = path.join(DIR, 'out'); FILE = path.join(DIR, 'kits.json');
try { fs.mkdirSync(OUT, { recursive: true }); } catch (e) {}
const sf = path.join(DIR, 'salt'); try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (e) {}
if (!SALT) { SALT = crypto.randomBytes(16).toString('hex'); try { fs.writeFileSync(sf, SALT, { flag: 'wx' }); } catch (e) { try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (er) {} } }
}
const program = () => X.program === 'linkspin' ? 'linkspin' : 'iap';
const brand = () => program() === 'linkspin' ? 'LinkSpin' : 'InstantAdPay';
function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.kits = s.kits || {}; s.credits = s.credits || {}; return s; } catch (e) { return { kits: {}, credits: {} }; } }
function save(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s, null, 1)); fs.renameSync(tmp, FILE); }
const ctMonth = ts => new Date(ts || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }).slice(0, 7);
const monthLabel = m => new Date(Date.UTC(Number(m.slice(0, 4)), Number(m.slice(5, 7)) - 1, 15)).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
// ---- admin: the kits ---------------------------------------------------------------------------------
function baseFile(month, size) {
const d = path.join(DIR, month);
for (const ext of ['png', 'jpg', 'gif']) { const f = path.join(d, size + '.' + ext); if (fs.existsSync(f)) return f; }
return null;
}
function kitView(k) {
const sizes = ORDER.map(s => { const f = baseFile(k.month, s); return { size: s, ready: !!f, v: f ? Math.round(fs.statSync(f).mtimeMs) : 0 }; });
return { month: k.month, label: monthLabel(k.month), theme: k.theme || '', released: !!k.released, program: program(), sizes, complete: sizes.every(x => x.ready), updated: k.updated || 0 };
}
function listKits() { const s = load(); return Object.values(s.kits).sort((a, b) => b.month.localeCompare(a.month)).map(kitView); }
function saveKit(b) {
const month = String(b.month || ''); if (!MONTH_RE.test(month)) return { error: 'Month as YYYY-MM.' };
const s = load(); const k = s.kits[month] || { month, theme: '', released: false, created: Date.now() };
if (b.theme != null) k.theme = String(b.theme).trim().slice(0, 80);
if (b.released != null) {
if (b.released && !kitView(k).complete) return { error: 'Upload all five sizes before releasing the kit.' };
k.released = !!b.released;
}
if (b.remove) { delete s.kits[month]; save(s); return { ok: true, removed: true }; }
k.updated = Date.now(); s.kits[month] = k; save(s);
return { ok: true, kit: kitView(k) };
}
const MAGIC = { png: b => b[0] === 0x89 && b[1] === 0x50, jpg: b => b[0] === 0xff && b[1] === 0xd8, gif: b => b.slice(0, 3).toString() === 'GIF' };
function uploadBase(month, size, buf, mime) {
if (!MONTH_RE.test(String(month))) return { error: 'Month as YYYY-MM.' };
if (!SIZES[size]) return { error: 'Size must be one of ' + ORDER.join(', ') + '.' };
const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' }[String(mime || '').split(';')[0].trim()];
if (!ext || !buf || buf.length < 32 || !MAGIC[ext](buf)) return { error: 'Use a PNG, JPG or GIF file.' };
const d = path.join(DIR, month); fs.mkdirSync(d, { recursive: true });
for (const e of ['png', 'jpg', 'gif']) { try { fs.unlinkSync(path.join(d, size + '.' + e)); } catch (er) {} }
fs.writeFileSync(path.join(d, size + '.' + ext), buf);
const s = load(); if (!s.kits[month]) s.kits[month] = { month, theme: '', released: false, created: Date.now() }; s.kits[month].updated = Date.now(); save(s);
return { ok: true, kit: kitView(s.kits[month]) };
}
// placeholder art for tests and previews: the program's existing banners from public/banners (no paid image APIs)
function usePlaceholder(month) {
const pre = program() === 'linkspin' ? 'linkspin-' : 'iap-';
const pick = { '728x90': [pre + '728x90.png'], '300x250': [pre + '300x250.png'], '468x60': [pre + '468x60.png'], '160x600': [pre + '160x600.png'],
'1200x630': program() === 'linkspin' ? ['linkspin-og-1200x630.png'] : ['iap-hero-1200x630.png', 'iap-advertise-earn-1200x630.jpg'] };
const done = [];
for (const size of ORDER) {
const f = pick[size].map(n => path.join(X.publicDir, 'banners', n)).find(p => fs.existsSync(p)); if (!f) continue;
const buf = fs.readFileSync(f); const r = uploadBase(month, size, buf, /\.jpg$/.test(f) ? 'image/jpeg' : 'image/png'); if (r.ok) done.push(size);
}
return { ok: true, sizes: done, kit: kitView(load().kits[month] || { month }) };
}
// ---- the renderer ---------------------------------------------------------------------------------------
let FONT;
function font() {
if (FONT !== undefined) return FONT;
FONT = process.env.BADGE_FONT || null; if (FONT) return FONT;
const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/bold\.ttf$/i.test(e.name) || /DejaVuSans-Bold\.ttf$/.test(e.name)) return f; } return null; };
for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } }
if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf';
return FONT;
}
const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%');
function run(args, cwd) {
return new Promise(resolve => {
const p = spawn(X.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], cwd });
const out = []; let err = '';
p.stdout.on('data', c => out.push(c)); p.stderr.on('data', c => { err += c; });
p.on('error', e => resolve({ code: -1, err: e.message })); p.on('close', code => resolve({ code, out: Buffer.concat(out), err }));
});
}
// one personalized banner: base scaled to the exact size, QR (white quiet zone) and @name on a dark box
async function renderStill(base, size, name, link, stage, outFile) {
const [W, H] = SIZES[size]; const L = LAYOUT[size]; const F = font();
if (!F) return { error: 'No font for the renderer.' };
const qr = X.qrcode || require('qrcode'); // opts.qrcode: a test copy without node_modules
const qrFile = outFile + '.qr.png';
await qr.toFile(qrFile, link, { margin: 1, width: L.q[2], errorCorrectionLevel: 'M', color: { dark: '#000000', light: '#ffffff' } });
const winPath = /:/.test(F); const fontFile = winPath ? path.basename(F) : F;
const ex = v => String(v).replace(/W/g, String(W)).replace(/H/g, String(H));
const tx = String(L.t[0]).replace(/W/g, String(W)).replace(/tw/g, 'text_w'); const ty = ex(L.t[1]);
const showName = stage !== 0, showQr = stage === undefined || stage === 2;
const chain = ['[0:v]scale=' + W + ':' + H + ':flags=lanczos,setsar=1[b]'];
let last = 'b';
if (showQr) { chain.push('[1:v]scale=' + L.q[2] + ':' + L.q[2] + '[q]'); chain.push('[' + last + '][q]overlay=x=' + ex(L.q[0]) + ':y=' + ex(L.q[1]) + '[o]'); last = 'o'; }
if (showName && name) { chain.push('[' + last + ']drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=white:fontsize=" + L.t[2] + ':box=1:boxcolor=0x0b1418@0.72:boxborderw=6:x=' + tx + ':y=' + ty + '[n]'); last = 'n'; }
const args = ['-v', 'error', '-y', '-i', path.resolve(base), '-i', path.resolve(qrFile), '-filter_complex', chain.join(';'), '-map', '[' + last + ']', '-frames:v', '1'];
if (/\.jpg$/.test(outFile)) args.push('-q:v', '3');
args.push(path.resolve(outFile));
const r = await run(args, winPath ? path.dirname(F) : undefined);
try { fs.unlinkSync(qrFile); } catch (e) {}
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'Render failed: ' + String(r.err || '').slice(0, 200) };
return { ok: true };
}
// the animated version (streak month 3+): the banner, then the name, then the name and the QR, looping
async function renderGif(base, size, name, link, outFile) {
const frames = [0, 1, 2].map(i => outFile + '.f' + i + '.png');
for (let i = 0; i < 3; i++) { const r = await renderStill(base, size, name, link, i, frames[i]); if (r.error) return r; }
const list = outFile + '.txt';
fs.writeFileSync(list, frames.map((f, i) => "file '" + path.resolve(f).replace(/\\/g, '/') + "'\nduration " + (i === 2 ? 3 : 1)).join('\n') + "\nfile '" + path.resolve(frames[2]).replace(/\\/g, '/') + "'\n");
const r = await run(['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-filter_complex', 'split[a][b];[a]palettegen=max_colors=96[p];[b][p]paletteuse=dither=bayer', '-loop', '0', path.resolve(outFile)]);
for (const f of frames.concat(list)) { try { fs.unlinkSync(f); } catch (e) {} }
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'GIF render failed: ' + String(r.err || '').slice(0, 200) };
return { ok: true };
}
const hashOf = (email, month, size, variant, v) => crypto.createHmac('sha256', SALT).update([norm(email), program(), month, size, variant, v].join('|')).digest('hex').slice(0, 28);
function indexFile() { return path.join(OUT, 'index.json'); }
function noteIndex(h, meta) { let ix = {}; try { ix = JSON.parse(fs.readFileSync(indexFile(), 'utf8')); } catch (e) {} ix[h] = meta; const tmp = indexFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(ix)); fs.renameSync(tmp, indexFile()); }
// render (or reuse) one personalized file; returns { url, file, size, variant, w, h, bytes }
async function personal(who, month, size, variant) {
const base = baseFile(month, size); if (!base) return { error: 'That kit has no ' + size + ' art yet.' };
const v = Math.round(fs.statSync(base).mtimeMs);
const ext = variant === 'gif' ? 'gif' : size === '1200x630' ? 'jpg' : 'png';
const h = hashOf(who.email, month, size, variant, v + '|' + who.name + '|' + who.link);
const out = path.join(OUT, h + '.' + ext);
if (!fs.existsSync(out)) {
const tmp = path.join(OUT, h + '.' + process.pid + '.' + Date.now() + '.' + ext);
let r; try { r = variant === 'gif' ? await renderGif(base, size, who.name, who.link, tmp) : await renderStill(base, size, who.name, who.link, undefined, tmp); } catch (e) { r = { error: 'The banner renderer is not available: ' + e.message }; }
if (r.error) return r;
try { fs.renameSync(tmp, out); } catch (e) { try { fs.unlinkSync(tmp); } catch (er) {} }
noteIndex(h, { email: norm(who.email), month, size, variant, ts: Date.now() });
}
const [w, hh] = SIZES[size];
return { ok: true, url: '/kitimg/' + h + '.' + ext, abs: String(X.siteUrl || '').replace(/\/+$/, '') + '/kitimg/' + h + '.' + ext, file: out, size, variant, w, h: hh, bytes: fs.statSync(out).size, ext };
}
// public serving: only files already rendered for an entitled member
function servePath(name) { const m = /^([a-f0-9]{28})\.(png|jpg|gif)$/.exec(String(name || '')); if (!m) return null; const f = path.join(OUT, m[0]); return fs.existsSync(f) ? { file: f, mime: { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[m[2]] } : null; }
// ---- the member ------------------------------------------------------------------------------------------
async function whoOf(email) {
const w = await X.linkFor(norm(email)); if (!w || !w.link) return null;
return { email: norm(email), name: w.username ? '@' + w.username : '', link: w.link };
}
async function myKits(email) {
const ent = (await X.entitled(norm(email)).catch(() => null)) || null;
if (!ent || !ent.on) return { on: false };
const s = load(); const months = ent.months || {};
const nowMonth = String(ent.today || '').slice(0, 7) || ctMonth(); // a kit released early still waits for its month
const kits = Object.values(s.kits).filter(k => k.released && k.month <= nowMonth).sort((a, b) => b.month.localeCompare(a.month)).slice(0, 12).map(k => {
const streakAt = months[k.month] || 0; const unlocked = streakAt > 0;
return Object.assign(kitView(k), { unlocked, streakAt, gif: unlocked && streakAt >= 3, custom: unlocked && streakAt >= 6 });
});
// the BannerKitAI "custom banners" credit: an entitlement on record, nothing more yet
const customMonths = Object.entries(months).filter(([, k]) => k >= 6).map(([m]) => m);
if (customMonths.length) {
const e = norm(email); const have = s.credits[e] || {}; let changed = false;
for (const m of customMonths) if (!have[m]) { have[m] = { ts: Date.now(), used: false }; changed = true; }
if (changed) { s.credits[e] = have; save(s); }
}
const credits = Object.entries((s.credits[norm(email)] || {})).map(([m, c]) => ({ month: m, used: !!c.used }));
const cur = nowMonth; const who = await whoOf(email).catch(() => null);
return { on: true, program: program(), brand: brand(), link: who ? who.link : null, name: who ? who.name : null, current: cur, currentLabel: monthLabel(cur), unlockedCurrent: !!months[cur],
kits, customCredits: credits, customNote: credits.length ? 'Custom banners made for your own offer with BannerKitAI are coming. Your credit is saved on your account and will be honored when it opens.' : null,
nextRefuel: ent.nextRefuel || null };
}
async function renderFor(email, month, size, variant) {
const mk = await myKits(email); if (!mk.on) return { error: 'The Refuel Kit is not switched on.' };
const k = mk.kits.find(x => x.month === month); if (!k) return { error: 'No such kit.' };
if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' };
if (!SIZES[size]) return { error: 'No such size.' };
if (variant === 'gif' && !k.gif) return { error: 'The animated version comes with a 3-month streak.' };
const who = await whoOf(email); if (!who) return { error: 'Set a username first, so your banners carry your own link.' };
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
}
async function preview(month, size, username, variant) {
const link = String(X.siteUrl || '').replace(/\/+$/, '') + '/join/' + (username || 'yourname');
const who = { email: 'preview@' + program(), name: '@' + (username || 'yourname'), link };
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
}
module.exports = { init, SIZES, ORDER, LAYOUT, listKits, saveKit, uploadBase, usePlaceholder, myKits, renderFor, preview, servePath, ctMonth, monthLabel, font };