Refuel Kit on LinkSpin (Fuel Your Offers stage 3, Marty approved 2026-10-24): kit.js (same file as InstantAdPay) with LinkSpin's own art, entitlement from InstantAdPay's streak record through refuel.status (view.kits: month -> streak month at unlock). Ads screen Refuel Kit panel (fuel.js?v=20261024kit): Make mine, Download, Copy image link, animated at a 3-month streak, and "Load into my Banner Spin" (kitspin.js): each Banner Spin size in the kit goes into one of the member's Banner Spins of that size with room, or a new one while the tier allows (the reason is shown when it does not); the personalized file is copied into uploads like a normal Banner Spin upload, labelled "Refuel Kit <month>", target = the member's own link; loading twice adds nothing twice; files over 150 KB are refused plainly. /kitimg/<hmac> public serving, admin Settings > Refuel Kit (upload, placeholder art, preview, release), raster copies of the LinkSpin placeholder banners (public/banners/linkspin-<size>.png, from the existing SVGs) for the placeholder kit. Behind the refuelStreak switch. Chatbot CANNED + FACTS mention the kit. qa/refuel-kit.test.cjs 5 checks against the real bannerspin.js. Note: qa kb retrieval has 2 pre-existing misses (spin links vs Banner Spin, PropellerAds postback), same before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-24 05:44:40 -05:00
parent 7bcde25116
commit 4749d711f4
14 changed files with 473 additions and 6 deletions
+2 -2
View File
@@ -42,7 +42,7 @@ const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|
const CANNED = [
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen. Buy here: https://linkspin.app/credits. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in the Ads screen (with a Load into my Banner Spin button); they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen. Buy here: https://linkspin.app/credits. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
{ id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a ticket?'], tags: ['support', 'help', 'ticket', 'contact'],
re: SUPPORT_RE, handoff: true,
a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' },
@@ -151,7 +151,7 @@ function seeds() {
// ---- facts for the AI fallback ----
// the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24)
let REFUEL_ON = () => false;
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
function systemPrompt(kbBlock) {
return `You are the assistant on LinkSpin (${SITE_URL}), a link rotator, page builder and advertising network for marketers, a Crypto Team Build Network property.
+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 };
+38
View File
@@ -0,0 +1,38 @@
// "Load into my Banner Spin" for the Refuel Kit (2026-10-24). Each Banner Spin size in an unlocked kit goes into one of the
// member's Banner Spins of that size that has room, or into a new Banner Spin when the member's tier allows one more.
// The banner is the member's own personalized file (copied into uploads like a normal Banner Spin upload, so health checks,
// moderation and Member content treat it the same), labelled "Refuel Kit <month>", the target their own link.
// Loading the same kit twice does not add it twice.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
async function load(d) { // { kit, bannerspin, content, uploadsDir, email, month, variant, sizes }
const { kit, bannerspin, email, month } = d;
const mk = await kit.myKits(email); const k = mk.on && 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.' };
const t = await bannerspin.tierFor(email); if (!t.ok) return { error: t.reason, status: 403 };
const want = Array.isArray(d.sizes) && d.sizes.length ? d.sizes.map(String) : k.sizes.filter(x => x.ready).map(x => x.size);
const label = 'Refuel Kit ' + month; const results = [];
for (const size of want.filter(z => bannerspin.SIZES[z] && k.sizes.some(x => x.size === z && x.ready))) {
const mine = await bannerspin.list(email);
const has = mine.find(x => x.size === size && x.banners.some(b => b.label === label));
if (has) { results.push({ size, spinId: has.id, spin: has.name, already: true }); continue; }
const r = await kit.renderFor(email, month, size, d.variant === 'gif' && k.gif ? 'gif' : 'still');
if (r.error) { results.push({ size, error: r.error }); continue; }
if (r.bytes > bannerspin.MAX_BYTES) { results.push({ size, error: 'The ' + size + ' file is over 150 KB, so Banner Spin cannot take it. Use the still version.' }); continue; }
let spin = mine.find(x => x.size === size && x.banners.length < t.banners && !x.adminOff), created = false;
if (!spin) { const c = await bannerspin.create(email, { name: 'Refuel Kit ' + size, size, fallback: mk.link || '' }); if (c.error) { results.push({ size, error: c.error }); continue; } spin = c.spin; created = true; }
const name = crypto.randomBytes(12).toString('hex') + '.' + r.ext;
fs.writeFileSync(path.join(d.uploadsDir, name), fs.readFileSync(r.file));
const mime = { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[r.ext];
try { if (d.content) d.content.noteUpload(name, email, r.bytes, mime, ''); } catch (e) {}
bannerspin.noteImage(email, name, r.w, r.h, r.bytes, mime);
const add = await bannerspin.addBanner(email, spin.id, { image: '/uploads/' + name, target: mk.link, label });
results.push(add.error ? { size, error: add.error } : { size, spinId: spin.id, spin: spin.name, created });
}
return { ok: true, results };
}
module.exports = { load };
+12 -1
View File
@@ -480,6 +480,17 @@
</div>
</div>
<div class="pane" id="pane-settings" hidden>
<div class="card" id="kitCard">
<div class="card-head"><h3>Refuel Kit</h3><span class="sub" id="kitSub">monthly members-only banners: unlocked by a counted refuel (needs refuelStreak on)</span></div>
<p class="small muted">Five base images per month for this site's own program: 728x90, 300x250, 468x60, 160x600, 1200x630. Each member's @name and a QR to their own link are drawn on top: keep the right end clear on 728x90 and 468x60 (QR) with room for the name left of it, the bottom-right corner on 300x250 and 1200x630, and the bottom 170 px on 160x600. No income claims in any banner. Release on the 1st; a member unlocks the month's kit with their next counted refuel.</p>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center"><input id="kitMonth" placeholder="YYYY-MM" style="max-width:110px"><input id="kitTheme" placeholder="Theme (e.g. Harvest)" style="max-width:240px">
<button class="btn small" id="kitSave" type="button">Save kit</button><button class="btn small sec" id="kitPlaceholder" type="button">Use placeholder art (public/banners)</button></p>
<div id="kitSizes"></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px">Preview <select id="kitPrevSize"></select><input id="kitPrevName" placeholder="username" style="max-width:160px"><label class="small"><input type="checkbox" id="kitPrevGif" style="width:auto"> animated</label><button class="btn small sec" id="kitPreview" type="button">Preview</button></p>
<div id="kitPrevBox"></div>
<div id="kitList" class="small"></div>
<div id="kitBox"></div>
</div>
<div class="card">
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
<p class="small muted">One card per email. Placeholders fill in per reader: click a chip to drop it where your cursor is.
@@ -524,6 +535,6 @@
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script>
<script src="/assets/admin.js?v=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
</body>
</html>
+2 -1
View File
@@ -65,6 +65,7 @@
<div class="tbl cl"><div class="hd"><span>Campaign</span><span>Creative</span><span>Budget</span><span class="r">Views</span><span class="r">Clicks</span><span>Status</span><span></span></div><div id="rows"></div><div class="ft" id="foot"></div></div>
<div class="side">
<div class="panel" id="rfPanel" hidden style="padding:0" aria-live="polite"><div class="ph"><h3>Monthly Refuel</h3><span class="meta" id="rfMeta"></span></div><div style="padding:12px 16px 14px;font-size:13px" class="ink2" id="rfBody"></div></div>
<div class="panel" id="rkPanel" hidden style="padding:0" aria-live="polite"><div class="ph"><h3>Refuel Kit</h3><span class="meta">members-only banners</span></div><div style="padding:12px 16px 14px;font-size:13px" class="ink2" id="rkBody"></div></div>
<div class="panel"><h2>Earn credits</h2><div class="gauge" id="earnGauge"><i></i><i></i><i></i><i></i><i></i></div><div class="muted" id="earnLine" style="margin-top:8px">loading</div><div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px"><button class="btn blue" type="button" id="earnNext">View an ad</button><button class="btn" type="button" id="earnClaim" hidden>Claim</button></div><div class="muted" id="earnNote" style="margin-top:8px"></div></div>
<div class="panel"><h2>Where your ads run</h2><div class="where ink2"><div><b>Banner</b><span>the ad viewer here, every member zone on outside sites, and the partner network</span></div><div><b>Text</b><span>the ad viewer and the partner network</span></div><div><b>Login</b><span id="loginWhere">full screen to every member right after they sign in, for a flat 30-day slot of purchased credits</span></div></div><div class="muted" id="rateLine" style="margin-top:10px"></div></div>
<div class="panel" hidden><h2>Credit activity</h2><div id="creditLog" class="ink2" style="font-size:13px"></div></div>
@@ -74,6 +75,6 @@
</div>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/ads-screen.js?v=20261023q"></script>
<script src="/assets/fuel.js?v=20261024rf"></script>
<script src="/assets/fuel.js?v=20261024kit"></script>
</body>
</html>
+40
View File
@@ -0,0 +1,40 @@
// Admin > Settings > Refuel Kit (2026-10-24). The SAME file ships in InstantAdPay and LinkSpin. Upload one month's base art
// (five sizes, this site's own program), preview the personalization (@name + QR to the member's link), then release it.
// Keep the QR corner and the name strip clear in the art (see the layout note on the card).
(function () {
const $ = id => document.getElementById(id);
if (!$('kitBox')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const say = m => { $('kitSub').textContent = m; };
const api = async (url, opt) => { const r = await fetch(url, Object.assign({ cache: 'no-store' }, opt || {})); const j = await r.json().catch(() => ({})); if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status)); return j; };
const post = (url, body) => api(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
const nextMonth = () => { const d = new Date(); const ct = new Date(d.toLocaleString('en-US', { timeZone: 'America/Chicago' })); ct.setDate(1); ct.setMonth(ct.getMonth() + 1); return ct.getFullYear() + '-' + String(ct.getMonth() + 1).padStart(2, '0'); };
let sizes = [];
async function load() {
try {
const d = await api('/api/admin/kits'); sizes = d.sizes;
if (!$('kitMonth').value) $('kitMonth').value = nextMonth();
$('kitList').innerHTML = d.kits.length ? d.kits.map(k => '<div style="border:1px solid var(--line,#ccd);border-radius:8px;padding:10px;margin:8px 0">'
+ '<b>' + esc(k.label) + '</b> ' + (k.theme ? '&middot; ' + esc(k.theme) + ' ' : '') + '<span class="small muted">(' + esc(k.month) + ')</span> '
+ (k.released ? '<span class="badge">released</span>' : '<span class="badge amber">draft</span>') + '<div class="small" style="margin:6px 0">'
+ k.sizes.map(s => s.size + ': ' + (s.ready ? 'ready' : '<b>missing</b>')).join(' &middot; ') + '</div>'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small sec" type="button" data-kedit="' + esc(k.month) + '" data-theme="' + esc(k.theme) + '">Edit</button>'
+ '<button class="btn small' + (k.released ? ' sec' : '') + '" type="button" data-krel="' + esc(k.month) + '" data-on="' + (k.released ? '0' : '1') + '"' + (!k.complete && !k.released ? ' disabled title="upload all five sizes first"' : '') + '>' + (k.released ? 'Unrelease' : 'Release to members') + '</button></div></div>').join('') : '<p class="small muted">No kits yet.</p>';
$('kitList').querySelectorAll('[data-kedit]').forEach(b => b.addEventListener('click', () => { $('kitMonth').value = b.dataset.kedit; $('kitTheme').value = b.dataset.theme; say('editing ' + b.dataset.kedit); }));
$('kitList').querySelectorAll('[data-krel]').forEach(b => b.addEventListener('click', async () => { try { await post('/api/admin/kits', { month: b.dataset.krel, released: b.dataset.on === '1' }); load(); } catch (e) { say(e.message); } }));
$('kitSizes').innerHTML = sizes.map(s => '<label class="small" style="display:block;margin:4px 0">' + s + ' <input type="file" accept="image/png,image/jpeg,image/gif" data-ksize="' + s + '"></label>').join('');
$('kitSizes').querySelectorAll('[data-ksize]').forEach(inp => inp.addEventListener('change', async () => {
const f = inp.files && inp.files[0]; if (!f) return; const m = $('kitMonth').value.trim();
try { await api('/api/admin/kits/upload?month=' + encodeURIComponent(m) + '&size=' + inp.dataset.ksize, { method: 'POST', headers: { 'Content-Type': f.type }, body: f }); say(inp.dataset.ksize + ' uploaded for ' + m); load(); } catch (e) { say(e.message); }
}));
$('kitPrevSize').innerHTML = sizes.map(s => '<option>' + s + '</option>').join('');
} catch (e) { say('Could not load: ' + e.message); }
}
$('kitSave').addEventListener('click', async () => { try { await post('/api/admin/kits', { month: $('kitMonth').value.trim(), theme: $('kitTheme').value }); say('saved'); load(); } catch (e) { say(e.message); } });
$('kitPlaceholder').addEventListener('click', async () => { try { const r = await post('/api/admin/kits/placeholder', { month: $('kitMonth').value.trim() }); say('placeholder art: ' + r.sizes.join(', ')); load(); } catch (e) { say(e.message); } });
$('kitPreview').addEventListener('click', () => {
const q = 'month=' + encodeURIComponent($('kitMonth').value.trim()) + '&size=' + encodeURIComponent($('kitPrevSize').value) + '&username=' + encodeURIComponent($('kitPrevName').value || 'yourname') + ($('kitPrevGif').checked ? '&variant=gif' : '') + '&t=' + Date.now();
$('kitPrevBox').innerHTML = '<img alt="preview" style="max-width:100%;border:1px solid #ccd" src="/api/admin/kits/preview?' + q + '">';
});
load();
})();
+45
View File
@@ -38,4 +38,49 @@
}
window.FUEL.loadRefuel = load;
load(); setInterval(load, 300000);
// ---- the Refuel Kit: members-only LinkSpin banners with your @name and a QR to your link ----
const post = async (url, body) => { const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) }); const j = await r.json().catch(() => ({})); if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status)); return j; };
const note = (el, m) => { if (el) el.textContent = m; };
function kitHtml(k, d) {
const head = '<div style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap"><b>' + esc(k.label) + (k.theme ? ' &middot; ' + esc(k.theme) : '') + '</b><span class="muted">' + (k.unlocked ? 'yours' : 'locked') + '</span></div>';
if (!k.unlocked) return head + '<p class="muted" style="margin:6px 0 0">Your next counted refuel unlocks it: $25+ here or $20+ on InstantAdPay' + (d.nextRefuel ? ' (refuel day ' + esc(d.nextRefuel) + ')' : '') + '.</p>';
return head + '<p class="muted" style="margin:6px 0">Your ' + esc(d.name || 'name') + ' and a QR to your link on every banner. Yours to keep after the month.</p>'
+ '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px"><button class="btn pri" type="button" data-kbs="' + esc(k.month) + '">Load into my Banner Spin</button>'
+ (k.gif ? '<label class="muted" style="display:flex;gap:4px;align-items:center"><input type="checkbox" data-kgif="' + esc(k.month) + '"> animated</label>' : '') + '</div>'
+ '<div class="muted" data-kres="' + esc(k.month) + '" role="status"></div>'
+ '<div style="display:grid;gap:8px">' + k.sizes.filter(s => s.ready).map(s => '<div data-kcell data-month="' + esc(k.month) + '" data-size="' + s.size + '" style="border:1px solid var(--line);border-radius:6px;padding:8px;min-width:0">'
+ '<div style="display:flex;justify-content:space-between;gap:6px;align-items:center"><span class="mono" style="font-size:11px">' + s.size + '</span><button class="btn" type="button" data-kmake>Make mine</button></div><div data-kimg style="margin-top:6px"></div></div>').join('') + '</div>';
}
async function loadKits() {
const panel = $('rkPanel'); if (!panel) return;
try {
const d = await (await fetch('/api/my/kits', { cache: 'no-store' })).json();
if (!d || !d.on || !d.kits || !d.kits.length) { panel.hidden = true; return; }
$('rkBody').innerHTML = d.kits.slice(0, 3).map(k => '<div style="margin-bottom:14px">' + kitHtml(k, d) + '</div>').join('')
+ (d.customNote ? '<p class="muted"><b>Custom banners credit:</b> ' + esc(d.customNote) + '</p>' : '') + '<p class="muted" style="margin:0">Ad credits buy delivery only. No banner may promise income.</p>';
panel.hidden = false;
panel.querySelectorAll('[data-kbs]').forEach(b => b.addEventListener('click', async () => {
const m = b.dataset.kbs; const out = panel.querySelector('[data-kres="' + m + '"]'); const g = panel.querySelector('[data-kgif="' + m + '"]');
b.disabled = true; note(out, 'Drawing your banners and loading them...');
try {
const r = await post('/api/my/kits/bannerspin', { month: m, variant: g && g.checked ? 'gif' : 'still' });
note(out, r.results.map(x => x.size + ': ' + (x.error ? x.error : x.already ? 'already in "' + x.spin + '"' : (x.created ? 'new Banner Spin "' : 'added to "') + x.spin + '"')).join(' | ') + ' (see Banner Spin under Links)');
} catch (e) { note(out, e.message); }
b.disabled = false;
}));
panel.querySelectorAll('[data-kmake]').forEach(b => b.addEventListener('click', async () => {
const cell = b.closest('[data-kcell]'); b.disabled = true;
try {
const g = panel.querySelector('[data-kgif="' + cell.dataset.month + '"]');
const r = await post('/api/my/kits/render', { month: cell.dataset.month, size: cell.dataset.size, variant: g && g.checked && cell.dataset.size !== '1200x630' ? 'gif' : 'still' });
cell.querySelector('[data-kimg]').innerHTML = '<img src="' + esc(r.url) + '" alt="Your ' + esc(r.size) + ' Refuel Kit banner" style="max-width:100%;height:auto;display:block"><div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:6px"><a class="btn" href="' + esc(r.url) + '" download>Download</a><button class="btn" type="button" data-kcopy="' + esc(r.abs) + '">Copy image link</button></div>';
const c = cell.querySelector('[data-kcopy]'); c.addEventListener('click', () => { try { navigator.clipboard.writeText(c.dataset.kcopy); c.textContent = 'Copied'; } catch (e) {} });
} catch (e) { cell.querySelector('[data-kimg]').textContent = e.message; }
b.disabled = false;
}));
} catch (e) { panel.hidden = true; }
}
window.FUEL.loadKits = loadKits;
loadKits();
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

+1 -1
View File
@@ -85,6 +85,6 @@
<script src="/assets/wallet.js?v=20261021a"></script>
<script src="/assets/cr-shell.js?v=20261023c"></script>
<script src="/assets/credits-screen.js?v=20261019pos"></script>
<script src="/assets/fuel.js?v=20261024rf"></script>
<script src="/assets/fuel.js?v=20261024kit"></script>
</body>
</html>
+69
View File
@@ -0,0 +1,69 @@
// Refuel Kit on LinkSpin: kit.js (shared with InstantAdPay) + kitspin.js "Load into my Banner Spin" against the REAL
// bannerspin.js, throwaway data, LinkSpin placeholder art. Entitlement is stubbed here (InstantAdPay's refuel.js decides it;
// qa/refuel.test.cjs covers that path). Run: node qa/refuel-kit.test.cjs
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
const { execSync } = require('child_process');
const ROOT = path.join(__dirname, '..');
let fails = 0, n = 0;
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 2).join(' | ')); } }
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
let qrcode = null; for (const p of ['qrcode', path.join(ROOT, '..', '..', 'onchain-ad-membership', 'site', 'node_modules', 'qrcode')]) { try { qrcode = require(p); break; } catch (e) {} }
let ffmpegOk = true; try { execSync('ffmpeg -version', { stdio: 'ignore' }); } catch (e) { ffmpegOk = false; }
if (!qrcode || !ffmpegOk) { console.log('skip: needs ffmpeg and the qrcode package (here or in the InstantAdPay repo)'); process.exit(0); }
function world(opts) {
opts = opts || {};
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-kit-')); const up = path.join(dir, 'uploads'); fs.mkdirSync(up);
const W = { dir, up, months: Object.assign({}, opts.months || { '2026-11': 1 }), ownBuy: opts.ownBuy !== false };
W.BS = fresh('bannerspin.js'); W.BS.init({ dataDir: dir, uploadsDir: up, schedule: false, facts: async () => ({ ownBuy: W.ownBuy, buyers: 0 }), rotator: { findMine: () => null } });
W.K = fresh('kit.js');
W.K.init({ dataDir: dir, program: 'linkspin', publicDir: path.join(ROOT, 'public'), siteUrl: 'https://linkspin.app', qrcode,
entitled: async () => ({ on: true, months: W.months, today: '2026-11-10' }),
linkFor: async () => ({ username: 'sam', link: 'https://linkspin.app/join/sam' }) });
W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', theme: 'Harvest', released: true });
W.load = b => require(path.join(ROOT, 'kitspin.js')).load(Object.assign({ kit: W.K, bannerspin: W.BS, uploadsDir: up, email: 's@x.test', month: '2026-11' }, b || {}));
return W;
}
(async () => {
await t('LinkSpin art only: the placeholder kit is the LinkSpin banners', async () => {
const W = world(); const k = W.K.listKits()[0];
assert.strictEqual(k.program, 'linkspin'); assert.ok(k.complete);
const base = fs.readFileSync(path.join(W.dir, 'kits', '2026-11', '728x90.png')); assert.ok(base.equals(fs.readFileSync(path.join(ROOT, 'public', 'banners', 'linkspin-728x90.png'))));
});
await t('locked kit and locked Banner Spin tier both refuse', async () => {
const W = world({ months: {} }); assert.ok(/next counted refuel/.test((await W.load()).error));
const W2 = world({ ownBuy: false }); const r = await W2.load(); assert.strictEqual(r.status, 403); assert.ok(/\$25/.test(r.error));
});
await t('Starter tier: uses an existing Banner Spin of the right size, creates new ones while the tier allows, says why when it cannot; 1200x630 is not a Banner Spin size', async () => {
const W = world();
const own = await W.BS.create('s@x.test', { name: 'My leaderboard', size: '728x90' }); assert.ok(own.ok);
const r = await W.load();
const by = Object.fromEntries(r.results.map(x => [x.size, x]));
assert.deepStrictEqual(Object.keys(by).sort(), ['160x600', '300x250', '468x60', '728x90']);
assert.strictEqual(by['728x90'].spinId, own.spin.id); assert.strictEqual(by['728x90'].created, false);
const made = r.results.filter(x => x.created).length; const refused = r.results.filter(x => x.error);
assert.strictEqual(made, 1, 'Starter holds 2 Banner Spins: one existed, one more created'); assert.strictEqual(refused.length, 2); assert.ok(/Starter tier holds 2/.test(refused[0].error));
const spins = await W.BS.list('s@x.test'); const b = spins.find(s => s.id === own.spin.id).banners[0];
assert.strictEqual(b.label, 'Refuel Kit 2026-11'); assert.strictEqual(b.target, 'https://linkspin.app/join/sam'); assert.ok(/^\/uploads\/[a-f0-9]{24}\.png$/.test(b.image));
assert.ok(fs.existsSync(path.join(W.up, b.image.slice(9)))); assert.strictEqual(b.w, 728); assert.ok(b.bytes <= W.BS.MAX_BYTES);
});
await t('loading the same kit twice adds nothing twice', async () => {
const W = world(); await W.BS.create('s@x.test', { name: 'L', size: '728x90' }); await W.BS.create('s@x.test', { name: 'M', size: '300x250' });
await W.load({ sizes: ['728x90', '300x250'] }); const r2 = await W.load({ sizes: ['728x90', '300x250'] });
assert.ok(r2.results.every(x => x.already));
const spins = await W.BS.list('s@x.test'); assert.deepStrictEqual(spins.map(s => s.banners.length), [1, 1]);
});
await t('the animated version (month 3+) loads as a GIF within the 150 KB Banner Spin limit, or is refused plainly', async () => {
const W = world({ months: { '2026-11': 3 } }); await W.BS.create('s@x.test', { name: 'R', size: '300x250' });
const r = await W.load({ sizes: ['300x250'], variant: 'gif' }); const x = r.results[0];
if (x.error) assert.ok(/150 KB/.test(x.error), x.error);
else { const b = (await W.BS.list('s@x.test'))[0].banners[0]; assert.ok(/\.gif$/.test(b.image)); }
});
console.log('\n' + (n - fails) + '/' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+46 -1
View File
@@ -66,7 +66,9 @@ const postbacks = require('./postbacks'); // outbound + inbound conversion postb
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
const refill = require('./refill');
const refuel = require('./refuel'); // Monthly Refuel streak, LinkSpin side: reports $25+ packages to InstantAdPay (the source of truth), applies its grants (2026-10-24) // refill notices: low / out / idle, one message per owner, conversions tracked (2026-10-24)
const refuel = require('./refuel');
const kit = require('./kit');
const kitspin = require('./kitspin'); // Refuel Kit -> Banner Spin loader // the Refuel Kit: monthly members-only LinkSpin banner sets, personalized per member (2026-10-24) // Monthly Refuel streak, LinkSpin side: reports $25+ packages to InstantAdPay (the source of truth), applies its grants (2026-10-24) // refill notices: low / out / idle, one message per owner, conversions tracked (2026-10-24)
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
@@ -635,6 +637,9 @@ async function boot() {
// a week later if credits sit idle; one email + one on-site notice per owner, every send watched for what they did next
refuel.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, marks, mailer, drip, siteUrl: SITE_URL, iapBase: IAP_BASE,
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [to], subject, html, 'notice'); } });
kit.init({ dataDir: DATA_DIR, program: 'linkspin', publicDir: PUBLIC_DIR, siteUrl: SITE_URL,
entitled: async email => { const v = await refuel.status(email); return v && v.on && !v.error ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel || null, today: v.today || null } : { on: false }; },
linkFor: async email => { const a = await accounts.byEmail(email); if (!a) return null; const tok = a.username || a.code; return tok ? { username: a.username || null, link: SITE_URL + '/join/' + tok } : null; } });
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 75000);
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 60 * 1000);
refill.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, siteUrl: SITE_URL, houseOwner: ads.HOUSE_OWNER, streakLine: email => refuel.streakLine(email),
@@ -3823,6 +3828,22 @@ const server = http.createServer(async (req, res) => {
passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length },
wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status() });
}
// -- Refuel Kit admin: kits as data (month, theme, five base images), placeholder art from public/banners, personalization preview
if (p === '/api/admin/kits' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, { kits: kit.listKits(), sizes: kit.ORDER }); }
if (p === '/api/admin/kits' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const r = kit.saveKit(await readBody(req)); return json(res, r.error ? 400 : 200, r); }
if (p === '/api/admin/kits/placeholder' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, kit.usePlaceholder(String(b.month || ''))); }
if (p === '/api/admin/kits/upload' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
let buf; try { buf = await readRaw(req, 3 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large (3 MB max).' }); }
const r = kit.uploadBase(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), buf, req.headers['content-type']);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/kits/preview' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await kit.preview(String(u.searchParams.get('month') || ''), String(u.searchParams.get('size') || ''), String(u.searchParams.get('username') || 'yourname').replace(/[^a-z0-9_]/gi, '').slice(0, 24), u.searchParams.get('variant') === 'gif' ? 'gif' : 'still');
if (r.error) return json(res, 400, r);
res.writeHead(200, { 'Content-Type': { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[r.ext], 'Cache-Control': 'no-store' }); return fs.createReadStream(r.file).pipe(res);
}
if (p === '/api/admin/refuel' && req.method === 'GET') { // Monthly Refuel, LinkSpin side: switch, link to InstantAdPay, reports waiting to go
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, refuel.adminView());
@@ -3831,6 +3852,30 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.tick());
}
// -- the Refuel Kit (2026-10-24): personalized banners are public by URL, rendered only for entitled members
if (p.startsWith('/kitimg/') && (req.method === 'GET' || req.method === 'HEAD')) {
const f = kit.servePath(p.slice(8)); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); }
res.writeHead(200, { 'Content-Type': f.mime, 'Cache-Control': 'public, max-age=86400', 'Access-Control-Allow-Origin': '*' });
return req.method === 'HEAD' ? res.end() : fs.createReadStream(f.file).pipe(res);
}
if (p === '/api/my/kits' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
return json(res, 200, await kit.myKits(s.email));
}
if (p === '/api/my/kits/render' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await kit.renderFor(s.email, String(b.month || ''), String(b.size || ''), b.variant === 'gif' ? 'gif' : 'still');
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, url: r.url, abs: r.abs, size: r.size, variant: r.variant, bytes: r.bytes });
}
// "Load into my Banner Spin": each Banner Spin size in the kit goes into one of the member's Banner Spins of that size with
// room, or a new one when the tier allows; the banner is the member's personalized file, the target their own link
if (p === '/api/my/kits/bannerspin' && req.method === 'POST') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await kitspin.load({ kit, bannerspin, content, uploadsDir: UPLOADS_DIR, email: s.email, month: String(b.month || ''), variant: b.variant, sizes: b.sizes });
return json(res, r.error ? (r.status || 400) : 200, r);
}
if (p === '/api/my/refuel' && req.method === 'GET') { // the member's Refuel card, from InstantAdPay's record ({ on:false } while switched off)
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });