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
+2 -2
View File
@@ -76,7 +76,7 @@ const CANNED = [
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
{ 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 Overview. Buy here: https://instantadpay.com/my#buy. 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 Promo tools; 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 Overview. Buy here: https://instantadpay.com/my#buy. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
{ id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'],
re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
@@ -214,7 +214,7 @@ function passTiersFact() {
}
// 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 InstantAdPay (https://instantadpay.com), a membership advertising platform.
+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 };
+12 -1
View File
@@ -576,6 +576,17 @@
</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.
@@ -618,6 +629,6 @@
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></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.js?v=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-kits.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();
})();
+61
View File
@@ -46,4 +46,65 @@
}
window.FUEL.loadRefuelCard = loadRefuelCard;
loadRefuelCard(); setInterval(loadRefuelCard, 300000);
// ---- the Refuel Kit (Promo tools): this month's members-only banners, with your @name and a QR to your link ----
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
const IAP_SIZES = ['728x90', '300x250', '468x60', '160x600'];
let kitData = null;
async function render(month, size, variant) {
const r = await (await fetch('/api/my/kits/render', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ month, size, variant }) })).json();
if (r.error) throw new Error(r.error);
return r;
}
// prefill the banner form under Campaigns with the kit image and the member's own link
function useInCampaign(r, month) {
const m = document.querySelector('.bo-menu [data-pane="campaigns"]'); if (m) m.click();
setTimeout(() => {
const set = (id, v, ev) => { const el = $(id); if (!el) return; el.value = v; el.dispatchEvent(new Event(ev || 'input', { bubbles: true })); };
set('cType', 'banner', 'change'); set('cSize', r.size, 'change');
set('cName', 'Refuel Kit ' + month + ' ' + r.size); set('cImage', r.abs); if (kitData && kitData.link) set('cTarget', kitData.link);
const el = $('cName'); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
say('Banner form filled with your kit banner and your link. Set a budget and launch.', 'ok');
}, 250);
}
function kitHtml(k, d) {
const head = '<div class="card-head"><h3>Refuel Kit: ' + esc(k.label) + (k.theme ? ' &middot; ' + esc(k.theme) : '') + '</h3><span class="sub">' + (k.unlocked ? 'yours' : 'locked') + '</span></div>';
if (!k.unlocked) return head + '<p class="small">Members-only banners for ' + esc(k.label) + '. Your next counted refuel unlocks them: a package of $20+ here, or $25+ on LinkSpin' + (d.nextRefuel ? ' (your refuel day: ' + esc(d.nextRefuel) + ')' : '') + '.</p>';
return head + '<p class="small">Five banners with your ' + esc(d.name || 'name') + ' and a QR code to your own link drawn on each one. They stay yours after the month ends.' + (k.gif ? ' Your streak also unlocks the animated version.' : '') + '</p>'
+ '<div class="kit-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px">'
+ k.sizes.filter(s => s.ready).map(s => '<div class="kit-cell" data-month="' + esc(k.month) + '" data-size="' + s.size + '" style="border:1px solid var(--line,#2a4650);border-radius:8px;padding:8px;min-width:0">'
+ '<div class="small muted">' + s.size + (s.size === '1200x630' ? ' (social posts)' : '') + '</div><div class="kit-img" style="margin:6px 0;min-height:30px"></div>'
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small" type="button" data-kit="make">Make mine</button>'
+ (k.gif && s.size !== '1200x630' ? '<button class="btn small sec" type="button" data-kit="gif">Animated</button>' : '') + '</div></div>').join('')
+ '</div>';
}
function cellReady(cell, r, month) {
const box = cell.querySelector('.kit-img');
box.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 small sec" href="' + esc(r.url) + '" download>Download</a>'
+ '<button class="btn small sec" type="button" data-kit="copy">Copy image link</button>'
+ (IAP_SIZES.includes(r.size) ? '<button class="btn small" type="button" data-kit="use">Use in an IAP banner campaign</button>' : '') + '</div>';
box.querySelector('[data-kit="copy"]').addEventListener('click', () => { try { navigator.clipboard.writeText(r.abs); say('Image link copied.', 'ok'); } catch (e) { say(r.abs); } });
const u = box.querySelector('[data-kit="use"]'); if (u) u.addEventListener('click', () => useInCampaign(r, month));
}
async function loadKitCard() {
const card = $('rkCard'); if (!card) return;
try {
const d = await (await fetch('/api/my/kits', { cache: 'no-store' })).json();
kitData = d;
if (!d || !d.on || !d.kits || !d.kits.length) { card.hidden = true; return; }
card.innerHTML = d.kits.slice(0, 3).map(k => '<div class="rk-kit" style="margin-bottom:14px">' + kitHtml(k, d) + '</div>').join('')
+ (d.customNote ? '<p class="small"><b>Custom banners credit:</b> ' + esc(d.customNote) + '</p>' : '')
+ '<p class="small muted">Ad credits buy delivery only. No banner may promise income.</p>';
card.hidden = false;
card.querySelectorAll('.kit-cell button[data-kit]').forEach(b => b.addEventListener('click', async () => {
const cell = b.closest('.kit-cell'); b.disabled = true; const was = b.textContent; b.textContent = 'Drawing your banner...';
try { cellReady(cell, await render(cell.dataset.month, cell.dataset.size, b.dataset.kit === 'gif' ? 'gif' : 'still'), cell.dataset.month); }
catch (e) { say(e.message, 'err'); }
b.disabled = false; b.textContent = was;
}));
} catch (e) { card.hidden = true; }
}
window.FUEL.loadKitCard = loadKitCard;
loadKitCard();
})();
+2 -1
View File
@@ -798,6 +798,7 @@
</div>
<div class="pane" id="pane-promo" hidden>
<div class="card" id="rkCard" hidden aria-live="polite"></div>
<div class="card" id="promoLinks">
<div class="card-head"><h3>Your links</h3><span class="sub">one invite link, eight front doors</span></div>
<div class="promo-strip" style="padding:0 0 12px">
@@ -1218,7 +1219,7 @@
<script src="/assets/promo.js?v=20261016p"></script>
<script src="/assets/support.js?v=20261016a"></script>
<script src="/assets/my.js?v=20261024rf"></script>
<script src="/assets/fuel.js?v=20261024rf"></script>
<script src="/assets/fuel.js?v=20261024kit"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+113
View File
@@ -0,0 +1,113 @@
// Refuel Kit (kit.js) with the real refuel.js entitlement, throwaway data, placeholder art from public/banners, real ffmpeg.
// Run: node qa/refuel-kit.test.cjs (skips the render checks when ffmpeg or a font is missing)
'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); }
const ct = (day, hour) => { const [y, m, d] = day.split('-').map(Number); return Date.UTC(y, m - 1, d, (hour == null ? 12 : hour) + 6); };
let ffmpegOk = true; try { execSync('ffmpeg -version', { stdio: 'ignore' }); } catch (e) { ffmpegOk = false; }
function dims(buf) {
if (buf[0] === 0x89) return [buf.readUInt32BE(16), buf.readUInt32BE(20)];
if (buf.slice(0, 3).toString() === 'GIF') return [buf.readUInt16LE(6), buf.readUInt16LE(8)];
for (let i = 2; i < buf.length - 9;) { if (buf[i] !== 0xff) { i++; continue; } const m = buf[i + 1]; const len = buf.readUInt16BE(i + 2); if (m >= 0xc0 && m <= 0xc3) return [buf.readUInt16BE(i + 7), buf.readUInt16BE(i + 5)]; i += 2 + len; }
return null;
}
function world(cfg) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kit-'));
const W = { dir, cfg: Object.assign({ refuelStreak: '1' }, cfg || {}) };
const marks = fresh('marks.js'); marks.init({});
W.R = fresh('refuel.js');
W.R.init({ dataDir: dir, db: require(path.join(ROOT, 'db.js')), marks, siteConfig: () => W.cfg, accounts: { byMemberId: async () => null, byEmail: async e => ({ email: e }) },
ads: { addEarned: async () => {} }, message: async () => {}, featuredPerDay: () => 40 });
W.K = fresh('kit.js');
W.K.init({ dataDir: dir, program: 'iap', publicDir: path.join(ROOT, 'public'), siteUrl: 'https://instantadpay.com',
entitled: async email => { const v = await W.R.view(email, W.now); return v && v.on ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel, today: v.today } : { on: false }; },
linkFor: async email => email === 'nouser@x.test' ? null : { username: 'mike', link: 'https://instantadpay.com/join/mike' } });
W.buy = (tx, day, cents) => W.R.record({ site: 'iap', email: 'm@x.test', tx, cents: cents || 2000, credits: cents || 2000, ts: ct(day) });
return W;
}
(async () => {
await t('admin: month format, sizes, file type; release needs all five sizes; placeholder art fills all five', async () => {
const W = world();
assert.ok(W.K.saveKit({ month: '2026-13' }).error);
assert.ok(W.K.saveKit({ month: '2026-11', theme: 'Harvest' }).ok);
assert.ok(W.K.uploadBase('2026-11', '999x1', Buffer.alloc(64), 'image/png').error);
assert.ok(W.K.uploadBase('2026-11', '728x90', Buffer.from('not an image at all, honestly, no...........'), 'image/png').error);
assert.ok(/all five sizes/.test(W.K.saveKit({ month: '2026-11', released: true }).error));
const r = W.K.usePlaceholder('2026-11'); assert.deepStrictEqual(r.sizes, W.K.ORDER);
assert.ok(W.K.saveKit({ month: '2026-11', released: true }).ok);
const k = W.K.listKits()[0]; assert.ok(k.released && k.complete && k.theme === 'Harvest');
});
await t('switch off: no kits for anyone', async () => {
const W = world({ refuelStreak: '0' }); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true });
assert.deepStrictEqual(await W.K.myKits('m@x.test'), { on: false });
assert.ok((await W.K.renderFor('m@x.test', '2026-11', '728x90')).error);
});
await t('locked until the next counted refuel; unlocked by a refuel in that Central month; drafts never shown', async () => {
const W = world(); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true }); W.K.usePlaceholder('2026-12');
W.now = ct('2026-11-03');
let mk = await W.K.myKits('m@x.test'); assert.strictEqual(mk.kits.length, 1); assert.strictEqual(mk.kits[0].unlocked, false);
assert.ok(/next counted refuel/.test((await W.K.renderFor('m@x.test', '2026-11', '728x90')).error));
await W.buy('0x1', '2026-11-03');
mk = await W.K.myKits('m@x.test'); assert.ok(mk.kits[0].unlocked); assert.strictEqual(mk.kits[0].gif, false); assert.strictEqual(mk.link, 'https://instantadpay.com/join/mike');
});
await t('a Pit Stop does not unlock a kit; the next counted refuel does; kits stay usable after the month; a missed month stops only new kits', async () => {
const W = world();
for (const m of ['2026-11', '2026-12', '2027-02']) { W.K.usePlaceholder(m); W.K.saveKit({ month: m, released: true }); }
await W.buy('0x1', '2026-11-20'); // unlocks November
await W.buy('0x2', '2026-12-05'); // a Pit Stop: not a refuel, December stays locked
W.now = ct('2026-12-06'); let mk = await W.K.myKits('m@x.test');
assert.deepStrictEqual(mk.kits.map(k => [k.month, k.unlocked]), [['2026-12', false], ['2026-11', true]], // February is released early but waits for its month
JSON.stringify(mk.kits.map(k => [k.month, k.unlocked])));
await W.buy('0x3', '2026-12-17'); // counted refuel in December: unlocks December
W.now = ct('2027-02-10'); mk = await W.K.myKits('m@x.test'); // January missed (free miss), February not refueled yet
assert.deepStrictEqual(mk.kits.map(k => [k.month, k.unlocked]), [['2027-02', false], ['2026-12', true], ['2026-11', true]], JSON.stringify(mk.kits.map(k => [k.month, k.unlocked])));
});
await t('animated version from a 3-month streak; BannerKitAI custom-banner credit from 6 months (entitlement + note only)', async () => {
const W = world(); let day = '2026-06-02';
const months = [];
for (let k = 1; k <= 6; k++) { const m = day.slice(0, 7); months.push(m); W.K.usePlaceholder(m); W.K.saveKit({ month: m, released: true }); await W.buy('t' + k, day); day = new Date(ct(day) + 30 * 864e5).toISOString().slice(0, 10); }
W.now = ct(day); const mk = await W.K.myKits('m@x.test');
const by = Object.fromEntries(mk.kits.map(k => [k.month, k]));
assert.strictEqual(by[months[1]].gif, false); assert.strictEqual(by[months[2]].gif, true); assert.strictEqual(by[months[5]].custom, true); assert.strictEqual(by[months[4]].custom, false);
assert.strictEqual(mk.customCredits.length, 1); assert.ok(/BannerKitAI/.test(mk.customNote));
assert.ok(/3-month streak/.test((await W.K.renderFor('m@x.test', months[1], '300x250', 'gif')).error));
});
if (!ffmpegOk || !require(path.join(ROOT, 'kit.js')).font()) { console.log('skip render checks: ffmpeg or font missing'); }
else {
await t('personalized renders: every size at its exact dimensions, @name + QR drawn (differs from the base), cached, served by unguessable name', async () => {
const W = world(); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true }); await W.buy('0x1', '2026-11-03'); W.now = ct('2026-11-04');
for (const size of W.K.ORDER) {
const r = await W.K.renderFor('m@x.test', '2026-11', size);
assert.ok(r.ok, size + ' ' + r.error); const buf = fs.readFileSync(r.file);
assert.deepStrictEqual(dims(buf), W.K.SIZES[size], size + ' dims');
assert.ok(/^\/kitimg\/[a-f0-9]{28}\.(png|jpg)$/.test(r.url)); assert.ok(r.abs.startsWith('https://instantadpay.com/kitimg/'));
assert.ok(W.K.servePath(r.url.slice(8)));
const again = await W.K.renderFor('m@x.test', '2026-11', size); assert.strictEqual(again.url, r.url, 'cached');
}
assert.strictEqual(W.K.servePath('0000000000000000000000000000.png'), null);
assert.strictEqual(W.K.servePath('../kits.json'), null);
});
await t('animated GIF at month 3: three-frame loop at the exact size', async () => {
const W = world(); let day = '2026-09-02';
for (let k = 1; k <= 3; k++) { W.K.usePlaceholder(day.slice(0, 7)); W.K.saveKit({ month: day.slice(0, 7), released: true }); await W.buy('g' + k, day); if (k < 3) day = new Date(ct(day) + 30 * 864e5).toISOString().slice(0, 10); }
W.now = ct(day);
const r = await W.K.renderFor('m@x.test', day.slice(0, 7), '300x250', 'gif');
assert.ok(r.ok, r.error); const buf = fs.readFileSync(r.file); assert.strictEqual(buf.slice(0, 6).toString(), 'GIF89a'); assert.deepStrictEqual(dims(buf), [300, 250]);
assert.ok(buf.includes(Buffer.from('NETSCAPE2.0')), 'loops');
});
await t('admin preview renders without any member', async () => {
const W = world(); W.K.usePlaceholder('2026-11');
const r = await W.K.preview('2026-11', '160x600', 'yourname'); assert.ok(r.ok, r.error); assert.deepStrictEqual(dims(fs.readFileSync(r.file)), [160, 600]);
});
}
console.log('\n' + (n - fails) + '/' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+3
View File
@@ -192,6 +192,8 @@ function decide(rec, p, c) {
kind = 'pitstop';
g(site, 'pitstop', pctOf(p.credits, pct), 'Pit Stop: +' + pct + '% (half your +' + cur + '% streak rate) on your ' + usd(p.cents) + ' package', { ref: 'rfpit:' + site + ':' + p.tx, pct, month: k });
}
// the Refuel Kit: a counted refuel unlocks the kit of its Central-time month, remembered with the streak month it came at
if (kind === 'refuel') { rec.kits = rec.kits || {}; const m = day.slice(0, 7); if (!rec.kits[m]) rec.kits[m] = rec.cycle ? rec.cycle.n : 1; }
if (kind === 'refuel' && c.dayPromo && c.dayPct > 0 && day.slice(8) === '01') g(site, 'refuelday', pctOf(p.credits, c.dayPct), 'Refuel Day (the 1st): +' + c.dayPct + '% on your ' + usd(p.cents) + ' package', { ref: 'rfday:' + site + ':' + p.tx, pct: c.dayPct });
// badges: Engine Started at the first counted refuel ever (Marty 2026-10-24), then 3, 6 and 12 months in a row
const badges = [];
@@ -376,6 +378,7 @@ async function view(email, now) {
next: windowOpen ? { month: next, single: rateSingle(next), both: rateBoth(next) } : { month: cy.n, secondEngine: rateBoth(cy.n) },
pitStop: cy && !windowOpen ? { pct: curRate / 2, iap: !cy.pit.iap && !!cy.sites.iap, linkspin: !cy.pit.linkspin && !!cy.sites.linkspin, usedIap: !!cy.pit.iap, usedLinkspin: !!cy.pit.linkspin } : null,
freeMiss: { available: freeOk, usedDay: rec.freeMissDay }, misses: rec.misses.slice(0, 6), badges: Object.keys(rec.badges || {}),
kits: rec.kits || {},
minUsd: { iap: c.minIap / 100, linkspin: c.minLs / 100 }, ladder: { single: SINGLE, both: BOTH }, refuelDay1: c.dayPromo ? c.dayPct : 0,
};
}
+37 -1
View File
@@ -73,7 +73,8 @@ const starter = require('./starter'); // member welcome offer from the games (20
const wednesday = require('./wednesday'); // Wired Wednesday: +25% on $10+ packs, wired into a visits campaign (2026-09-29)
const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked Sat-Thu by solo + video (2026-09-26)
const refill = require('./refill');
const refuel = require('./refuel'); // the Monthly Refuel streak, one per member across InstantAdPay + LinkSpin (Fuel Your Offers, 2026-10-24); switch refuelStreak, default off
const refuel = require('./refuel');
const kit = require('./kit'); // the Refuel Kit: monthly members-only banner sets, personalized per member (Fuel Your Offers stage 3, 2026-10-24) // the Monthly Refuel streak, one per member across InstantAdPay + LinkSpin (Fuel Your Offers, 2026-10-24); switch refuelStreak, default off
const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20)
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
@@ -602,6 +603,9 @@ async function boot() {
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
badge: (email, key) => postBadgeOnce(email, key, 'Monthly Refuel'),
feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); } });
kit.init({ dataDir: DATA_DIR, program: 'iap', publicDir: PUBLIC_DIR, siteUrl: 'https://instantadpay.com',
entitled: async email => { const v = await refuel.view(email); return v && v.on ? { 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: 'https://instantadpay.com/join/' + tok } : null; } });
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 120000);
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 10 * 60 * 1000);
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
@@ -4728,6 +4732,22 @@ const server = http.createServer(async (req, res) => {
}
// Campaigns > Conversion tracking: the member's goals and counts live on LinkSpin; these proxy the signed calls
// -- Monthly Refuel (2026-10-24): the member's refuel day, streak, next bonus and Pit Stop status ({ on:false } while switched off)
// -- the Refuel Kit (2026-10-24): personalized banners are public by URL (ad networks load them), 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 });
}
if (p === '/api/my/refuel' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
@@ -5010,6 +5030,22 @@ const server = http.createServer(async (req, res) => {
v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email };
return json(res, 200, v);
}
// -- 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: settings, members on a streak, grants by kind, recent outbox rows
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refuel.stats());