Admin route: house Banner Spins on the admin's own account, logged (Marty 2026-11-16)
POST /api/admin/house-spins creates or updates Banner Spins on a house account (ADMIN_EMAIL or NETWORK_LINKS_OWNER) for house ads such as the Network Ad Space rows, through the same bannerspin.js calls the member Links screen uses (create, update, addBanner, updateBanner). Admin auth only (portal session or the admin key); no member session is read or minted. Every call, denied ones too, goes to the new admin action log (adminaudit.js: MySQL table admin_audit, JSONL without a database) with who, what and when; GET /api/admin/house-spins/log reads it. qa/housespins.test.mjs (in run.sh netsrc) covers auth, house-account only, member checks, idempotent repeat, prune, serving + click attribution, the log and no session minted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
// Admin action log (Marty 2026-11-16, "a named, logged admin route"): who did what, to what, and when, for admin routes that
|
||||
// change a member's things on their behalf (first user: /api/admin/house-spins). One row per call, denied calls included.
|
||||
// With MySQL (production) the rows live in table admin_audit; without it (local copies, QA) in DATA_DIR/admin-audit.jsonl.
|
||||
// Never holds a secret: callers pass a short summary, and anything that looks like a key or password is masked here too.
|
||||
// record({ who, action, target, ok, detail, ip }) list(limit) -> newest first
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
|
||||
let DATA_DIR = null, made = false;
|
||||
function init(opts) { DATA_DIR = opts.dataDir; }
|
||||
const FILE = () => path.join(DATA_DIR, 'admin-audit.jsonl');
|
||||
const clip = (s, n) => String(s == null ? '' : s).slice(0, n);
|
||||
// a value under a key like token/secret/password/key never lands in the log
|
||||
const scrub = o => JSON.parse(JSON.stringify(o == null ? null : o, (k, v) => (/pass|secret|token|apikey|api_key|authorization/i.test(k) ? '[masked]' : v)));
|
||||
|
||||
async function table() {
|
||||
if (made) return;
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS admin_audit (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, who VARCHAR(190) NOT NULL, action VARCHAR(80) NOT NULL,
|
||||
target VARCHAR(190) NOT NULL DEFAULT '', ok TINYINT NOT NULL DEFAULT 1, ip VARCHAR(64) NOT NULL DEFAULT '', detail MEDIUMTEXT,
|
||||
KEY ts (ts), KEY action (action)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
made = true;
|
||||
}
|
||||
async function record(e) {
|
||||
const row = { ts: Date.now(), who: clip(e.who || 'unknown', 190), action: clip(e.action, 80), target: clip(e.target, 190), ok: e.ok === false ? 0 : 1, ip: clip(e.ip, 64), detail: clip(JSON.stringify(scrub(e.detail)), 60000) };
|
||||
try {
|
||||
if (db.enabled()) { await table(); await db.q('INSERT INTO admin_audit (ts, who, action, target, ok, ip, detail) VALUES (?, ?, ?, ?, ?, ?, ?)', [row.ts, row.who, row.action, row.target, row.ok, row.ip, row.detail]); }
|
||||
else fs.appendFileSync(FILE(), JSON.stringify(row) + '\n');
|
||||
return true;
|
||||
} catch (er) { console.error('adminaudit', er.message); return false; }
|
||||
}
|
||||
async function list(limit) {
|
||||
const n = Math.max(1, Math.min(500, Number(limit) || 100));
|
||||
const parse = r => Object.assign({}, r, { ts: Number(r.ts), ok: !!Number(r.ok), detail: (() => { try { return JSON.parse(r.detail); } catch (e) { return r.detail; } })() });
|
||||
if (db.enabled()) { await table(); return (await db.q('SELECT id, ts, who, action, target, ok, ip, detail FROM admin_audit ORDER BY id DESC LIMIT ?', [n])).map(parse); }
|
||||
let lines = []; try { lines = fs.readFileSync(FILE(), 'utf8').split('\n').filter(Boolean); } catch (e) {}
|
||||
return lines.slice(-n).reverse().map(l => { try { return parse(JSON.parse(l)); } catch (e) { return null; } }).filter(Boolean);
|
||||
}
|
||||
module.exports = { init, record, list };
|
||||
@@ -0,0 +1,66 @@
|
||||
// House Banner Spins (Marty 2026-11-16: "no proper Banner Spins for your house ads"). The admin creates or updates Banner Spins
|
||||
// on a house account (ADMIN_EMAIL or NETWORK_LINKS_OWNER, i.e. Marty's own account) for house ads such as the Network Ad Space
|
||||
// rows, WITHOUT signing in as that member: no member session is read or minted. Every step goes through the same bannerspin.js
|
||||
// calls the member Links screen uses (create, update, addBanner, updateBanner), with the account's email as the owner, so the
|
||||
// checks (sizes, https images and targets, the source belonging to the account, the tier's banner count) are the member's.
|
||||
// server.js wires it as POST /api/admin/house-spins (admin only) and writes every call to the admin action log (adminaudit.js).
|
||||
//
|
||||
// Body: { email, host?, spins: [ { id?, name, size, mode?, fallback?, sourceId?, paused?, prune?,
|
||||
// banners: [ { label, image, target, weight?, active? } ] } ] }
|
||||
// id given -> that Banner Spin (it must belong to the account) is updated; without id, a Banner Spin of the same name and size on
|
||||
// the account is reused, else one is created. Banners match by image address: a match is updated, a new image is
|
||||
// added, and with prune: true a banner whose image is no longer listed is removed.
|
||||
// Reply: { ok, email, host, spins: [ { id, code, name, size, created, added, updated, removed, img, click, errors } ] }
|
||||
'use strict';
|
||||
let R = null; // { bannerspin, houseAccounts(): [email], host(wanted): the link domain (wanted when it is one of ours, else the first) }
|
||||
function init(refs) { R = refs; }
|
||||
const norm = e => String(e || '').trim().toLowerCase();
|
||||
|
||||
async function apply(body) {
|
||||
const email = norm(body && body.email);
|
||||
if (!email) return { error: 'Which account? Pass email.' };
|
||||
if (!R.houseAccounts().includes(email)) return { error: 'House Banner Spins go on a house account only (the admin account).' };
|
||||
const list = Array.isArray(body.spins) ? body.spins : [];
|
||||
if (!list.length || list.length > 40) return { error: 'Pass 1 to 40 spins.' };
|
||||
const BS = R.bannerspin; const host = R.host(body.host); const out = [];
|
||||
for (const want of list) {
|
||||
const row = { name: String(want.name || ''), size: String(want.size || ''), created: false, added: 0, updated: 0, removed: 0, errors: [] };
|
||||
out.push(row);
|
||||
let spin = null;
|
||||
const mine = await BS.list(email);
|
||||
if (want.id != null) { spin = mine.find(s => s.id === Number(want.id)) || null; if (!spin) { row.errors.push('No Banner Spin ' + want.id + ' on this account.'); continue; } }
|
||||
else spin = mine.find(s => s.name === String(want.name || '').trim() && s.size === row.size) || null;
|
||||
if (!spin) {
|
||||
const r = await BS.create(email, { name: want.name, size: want.size, mode: want.mode, fallback: want.fallback });
|
||||
if (r.error) { row.errors.push(r.error); continue; }
|
||||
spin = r.spin; row.created = true;
|
||||
}
|
||||
const patch = {};
|
||||
if (want.name != null && String(want.name).trim() !== spin.name) patch.name = want.name;
|
||||
if (want.mode != null) patch.mode = want.mode;
|
||||
if (want.fallback != null) patch.fallback = want.fallback;
|
||||
if (want.sourceId != null) patch.sourceId = want.sourceId;
|
||||
if (want.paused != null) patch.paused = !!want.paused;
|
||||
if (Object.keys(patch).length) { const r = await BS.update(email, spin.id, patch); if (r.error) row.errors.push(r.error); else spin = r.spin; }
|
||||
const banners = Array.isArray(want.banners) ? want.banners : [];
|
||||
for (const b of banners) {
|
||||
const have = spin.banners.find(x => x.image === String(b.image || '').trim());
|
||||
if (have) {
|
||||
const p = {}; if (b.label != null && b.label !== have.label) p.label = b.label; if (b.weight != null && Number(b.weight) !== have.weight) p.weight = b.weight;
|
||||
if (b.target != null && b.target !== have.target) p.target = b.target; const act = b.active == null ? true : !!b.active; if (act !== have.active) p.active = act;
|
||||
if (Object.keys(p).length) { const r = await BS.updateBanner(email, spin.id, have.id, p); if (r.error) row.errors.push(have.id + ': ' + r.error); else { spin = r.spin; row.updated++; } }
|
||||
} else {
|
||||
const r = await BS.addBanner(email, spin.id, { label: b.label, image: b.image, target: b.target, weight: b.weight });
|
||||
if (r.error) row.errors.push(String(b.image).slice(0, 80) + ': ' + r.error); else { spin = r.spin; row.added++; }
|
||||
}
|
||||
}
|
||||
if (want.prune) {
|
||||
const keep = new Set(banners.map(b => String(b.image || '').trim()));
|
||||
for (const x of spin.banners.filter(x => !keep.has(x.image))) { const r = await BS.updateBanner(email, spin.id, x.id, { remove: true }); if (r.error) row.errors.push(x.id + ': ' + r.error); else { spin = r.spin; row.removed++; } }
|
||||
}
|
||||
Object.assign(row, { id: spin.id, code: spin.code, name: spin.name, size: spin.size, sourceId: spin.sourceId || '', fallback: spin.fallback || '', banners: spin.banners.length,
|
||||
img: 'https://' + host + '/i/' + spin.code + '.gif', click: 'https://' + host + '/c/' + spin.code });
|
||||
}
|
||||
return { ok: out.every(r => !r.errors.length), email, host, spins: out };
|
||||
}
|
||||
module.exports = { init, apply };
|
||||
@@ -0,0 +1,78 @@
|
||||
// House Banner Spins admin route (2026-11-16). Boots server.js on its own port with a throwaway data dir (JSON store, no DB) and
|
||||
// checks POST /api/admin/house-spins: admin only (no auth -> 401, logged as denied), house account only, creates a Banner Spin with
|
||||
// its banners, source and fallback through the member code path, a second identical call changes nothing, an update adds / prunes
|
||||
// by image, the image and click serve on a link domain (click -> the banner's target, src + s1 kept in the click row), every call
|
||||
// is in the admin action log with who / what / when, and no member session is ever minted for the account.
|
||||
// node qa/housespins.test.mjs (from the site dir; PORT default 8977)
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
const PORT = Number(process.env.PORT || 8977); const BASE = 'http://127.0.0.1:' + PORT;
|
||||
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 500) : '')); } };
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-qa-')); const ADMIN = 'admin@hs.test', MEM = 'mem@hs.test', KEY = 'k'.repeat(20), LINK = 'lnk-hs.test';
|
||||
fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: LINK }));
|
||||
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: KEY, ADMIN_EMAIL: ADMIN });
|
||||
for (const k of ['NODE_ENV', 'DATABASE_URL', 'DOCSTORE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL', 'NETWORK_LINKS_OWNER', 'NETWORK_SSO_SECRET']) delete env[k];
|
||||
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let srv = null;
|
||||
async function boot() { srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] }); for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); } await sleep(3800); }
|
||||
async function stop() { if (srv) srv.kill(); srv = null; await sleep(600); }
|
||||
const read = f => { try { return JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8')); } catch (e) { return null; } };
|
||||
const post = async (body, auth, actor) => { const r = await fetch(BASE + '/api/admin/house-spins', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, auth ? { Authorization: 'Bearer ' + auth } : {}, actor ? { 'X-Admin-Actor': actor } : {}), body: JSON.stringify(body) }); return { status: r.status, j: await r.json().catch(() => ({})) }; };
|
||||
const go = async (p, ua) => { const r = await fetch(BASE + p, { redirect: 'manual', headers: { Host: LINK, 'User-Agent': ua || 'Mozilla/5.0 (Windows NT 10.0) Chrome/130 hs-qa', Referer: 'https://www.networkadspace.com/page' } }); return { status: r.status, loc: r.headers.get('location') || '', type: r.headers.get('content-type') || '' }; };
|
||||
const sessionsFor = e => { const s = read('sessions.json'); const list = s ? (Array.isArray(s) ? s : Object.values(s.sessions || s)) : []; return list.filter(x => x && String(x.email || '').toLowerCase() === e).length; };
|
||||
try {
|
||||
await boot();
|
||||
let src = null; for (let i = 0; i < 20 && !src; i++) { src = ((read('sources.json') || {}).items || []).find(x => x.owner === ADMIN && x.template === 'viraladblitz'); if (!src) await sleep(500); }
|
||||
ok(!!src, 'the admin account has its network sources (one to tag with)');
|
||||
const T = 'https://linkspin.app/r/nwvab?src=nas&s1=martbost';
|
||||
const IMG = n => 'https://viraladblitz.com/art/kit/vab-' + n + '-panel.png';
|
||||
const spin = (imgs, extra) => Object.assign({ name: 'Network Ad Space: ViralAdBlitz 336x280', size: '336x280', fallback: T, sourceId: src && src.id, banners: imgs.map(n => ({ label: n, image: IMG(n), target: T, weight: 10 })) }, extra || {});
|
||||
const sess0 = sessionsFor(ADMIN);
|
||||
|
||||
let r = await post({ email: ADMIN, spins: [spin(['free'])] }, null, 'qa');
|
||||
ok(r.status === 401, 'no admin auth: 401', r);
|
||||
r = await post({ email: ADMIN, spins: [spin(['free'])] }, 'wrong-key');
|
||||
ok(r.status === 401, 'a wrong admin key: 401', r);
|
||||
r = await post({ email: MEM, spins: [spin(['free'])] }, KEY);
|
||||
ok(r.status === 400 && /house account/.test(r.j.error || ''), 'a member account (not a house account): refused', r);
|
||||
|
||||
r = await post({ email: ADMIN, host: LINK, spins: [spin(['free', 'spread', 'boost'])] }, KEY, 'qa-run');
|
||||
const s1 = r.j.spins && r.j.spins[0];
|
||||
ok(r.status === 200 && r.j.ok && s1 && s1.created && s1.added === 3 && s1.sourceId === (src && src.id) && s1.fallback === T, 'creates the Banner Spin with 3 banners, the source and the fallback', r.j);
|
||||
ok(s1 && s1.img === 'https://' + LINK + '/i/' + s1.code + '.gif' && s1.click === 'https://' + LINK + '/c/' + s1.code, 'answers the image and click URLs on the chosen link domain', s1);
|
||||
const stored = (read('bannerspin.json') || { spins: [] }).spins.find(x => s1 && x.id === s1.id);
|
||||
ok(stored && stored.owner === ADMIN && stored.banners.length === 3 && stored.banners.every(b => b.target === T && b.active), 'stored on the admin account like a member-made Banner Spin', stored);
|
||||
|
||||
r = await post({ email: ADMIN, host: LINK, spins: [spin(['free', 'spread', 'boost'])] }, KEY, 'qa-run');
|
||||
ok(r.status === 200 && r.j.spins[0].id === s1.id && !r.j.spins[0].created && r.j.spins[0].added === 0 && r.j.spins[0].updated === 0, 'the same call again changes nothing (reuses it by name + size)', r.j.spins);
|
||||
r = await post({ email: ADMIN, spins: [spin(['free', 'boost'], { id: s1.id, prune: true })] }, KEY, 'qa-run');
|
||||
ok(r.status === 200 && r.j.spins[0].removed === 1 && r.j.spins[0].banners === 2, 'by id with prune: a banner no longer listed is removed', r.j.spins);
|
||||
r = await post({ email: ADMIN, spins: [{ id: 99999, banners: [] }] }, KEY);
|
||||
ok(r.status === 200 && r.j.ok === false && /No Banner Spin/.test(r.j.spins[0].errors[0] || ''), 'an unknown id reports an error and changes nothing', r.j);
|
||||
r = await post({ email: ADMIN, spins: [spin(['free'], { name: 'Bad size', size: '999x999' })] }, KEY);
|
||||
ok(r.status === 200 && r.j.ok === false && /sizes/.test(r.j.spins[0].errors[0] || ''), 'the member checks apply (a bad size is refused)', r.j);
|
||||
|
||||
let g = await go('/i/' + s1.code + '.gif');
|
||||
ok(g.status === 302 && /^https:\/\/viraladblitz\.com\/art\/kit\/vab-(free|boost)-panel\.png$/.test(g.loc), 'the image URL serves one of the kit banners', g);
|
||||
g = await go('/c/' + s1.code + '?src=nas&s1=martbost');
|
||||
ok(g.status === 302 && g.loc.startsWith(T), 'the click goes to the tracked network link', g);
|
||||
await sleep(300);
|
||||
const click = (read('bannerspin.json') || { clicks: [] }).clicks.slice(-1)[0];
|
||||
ok(click && click.s === s1.id && click.sr === src.id && click.q && click.q.src === 'nas' && click.q.s1 === 'martbost' && click.m !== 'none', 'the click row: this Banner Spin, the source, src + s1 kept, matched to the view', click);
|
||||
|
||||
const log = await (await fetch(BASE + '/api/admin/house-spins/log?limit=50', { headers: { Authorization: 'Bearer ' + KEY } })).json();
|
||||
const E = log.entries || [];
|
||||
ok(E.length === 8, 'every call is in the admin action log (8)', E.length);
|
||||
ok(E.filter(e => !e.ok && /^denied/.test(e.who)).length === 2 && E.some(e => e.who === 'denied (qa)'), 'denied calls logged as denied, with the actor label', E.map(e => e.who));
|
||||
ok(E.filter(e => e.who === 'admin key (qa-run)').length === 3 && E.every(e => e.action === 'house-spins' && e.ts > Date.now() - 600000), 'who (admin key + actor), what and when on each row', E.map(e => [e.who, e.action]));
|
||||
ok(E.some(e => e.target === ADMIN && e.ok && e.detail && e.detail.spins && e.detail.spins[0].code === s1.code), 'the detail names the account and the Banner Spin', E[0]);
|
||||
ok(!JSON.stringify(E).includes(KEY), 'the admin key is never in the log');
|
||||
ok((await fetch(BASE + '/api/admin/house-spins/log')).status === 401, 'reading the log needs admin auth');
|
||||
ok(sessionsFor(ADMIN) === sess0, 'no member session was minted for the account', [sess0, sessionsFor(ADMIN)]);
|
||||
} catch (e) { fail++; console.error(e); }
|
||||
finally { await stop(); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
|
||||
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);
|
||||
@@ -9,7 +9,7 @@
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression
|
||||
# bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay)
|
||||
# bash qa/run.sh netconv # conversion linkage: InstantAdPay's joins, wallets, purchases counted once, own account left out, window, aged hits, two copies racing, one Reports list, the landing tag on network links
|
||||
# bash qa/run.sh netsrc # network sites as traffic sources: the seven fixed network links, ?src= picks the sending site's source, member links get it on first use; partner tracked links (DownlineHydra programs, ViralAdBlitz text ads, its spin-link picker)
|
||||
# bash qa/run.sh netsrc # network sites as traffic sources: the seven fixed network links, ?src= picks the sending site's source, member links get it on first use; partner tracked links (DownlineHydra programs, ViralAdBlitz text ads, its spin-link picker); the admin house Banner Spins route
|
||||
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
|
||||
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
|
||||
# bash qa/run.sh nas # Network Ad Space billing: stop snapshot, active-only reconcile, restart without phantom delivery, the 1/N network + partner-zone rate (stubbed NAS, throwaway data)
|
||||
@@ -105,6 +105,7 @@ elif [ "$MODE" = "netconv" ]; then
|
||||
node qa/netconv.test.mjs || status=1
|
||||
elif [ "$MODE" = "netsrc" ]; then
|
||||
node qa/netsrc.test.mjs || status=1
|
||||
node qa/housespins.test.mjs || status=1 # admin house Banner Spins: admin only, house account only, member code path, idempotent, action log, no session minted
|
||||
node qa/partner-dhlinks.test.mjs || status=1
|
||||
node qa/partner-vablinks.test.mjs || status=1
|
||||
node qa/partner-vabspins.test.mjs || status=1
|
||||
|
||||
@@ -80,6 +80,8 @@ const kit = require('./kit');
|
||||
const engine = require('./engine'); // the Engine Room (same file as InstantAdPay), 2026-10-24
|
||||
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 housespins = require('./housespins'); // admin: house Banner Spins on the admin's own account, no member sign-in (2026-11-16)
|
||||
const adminaudit = require('./adminaudit'); // admin action log: who, what, when (2026-11-16)
|
||||
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)
|
||||
const domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10)
|
||||
@@ -759,6 +761,9 @@ async function boot() {
|
||||
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
|
||||
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
|
||||
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: (owner, url) => { if (convtrack.goalsOf(owner).length > 0) return true; try { return networkHosts().includes(new URL(url).hostname.toLowerCase().replace(/^www\./, '')); } catch (e) { return false; } }, withClickId: convtrack.withClickId });
|
||||
adminaudit.init({ dataDir: DATA_DIR });
|
||||
housespins.init({ bannerspin, houseAccounts: () => [ADMIN_EMAIL, String(process.env.NETWORK_LINKS_OWNER || '').trim().toLowerCase()].filter(Boolean),
|
||||
host: want => { const hs = domains.hosts().map(d => d.host); const w = String(want || '').trim().toLowerCase(); return hs.includes(w) ? w : (hs[0] || SITE_HOST); } });
|
||||
rotator.setExternalConvert((lsid, ev, facts) => /^[ai]/.test(String(lsid)) ? netconv.fromLinkSpin(lsid, ev, facts) : bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks; ad clicks through the ledger
|
||||
netconv.init({ dataDir: DATA_DIR, convtrack, rotator, bannerspin, postbacks, marks });
|
||||
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
|
||||
@@ -2846,6 +2851,28 @@ const server = http.createServer(async (req, res) => {
|
||||
else r = await bannerspin.update(s.email, m[1], b);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// House Banner Spins (Marty 2026-11-16): create or update Banner Spins on the admin's own account for house ads (the Network Ad
|
||||
// Space rows), through the same bannerspin.js calls as the member Links screen. Admin auth only (portal session or the admin key);
|
||||
// no member session is read or minted. Every call, denied ones too, goes to the admin action log (adminaudit.js) with who, what
|
||||
// and when. GET /api/admin/house-spins/log reads that log (?limit=, newest first). Body: housespins.js.
|
||||
if (p === '/api/admin/house-spins' && req.method === 'POST') {
|
||||
const adm = adminFromRequest(req); const ok = isAdmin(req);
|
||||
const actor = String(req.headers['x-admin-actor'] || '').replace(/[^\w .:@-]/g, '').slice(0, 60);
|
||||
const who = adm ? adm.email : ok ? 'admin key' + (actor ? ' (' + actor + ')' : '') : 'denied' + (actor ? ' (' + actor + ')' : '');
|
||||
let b = {}; try { b = await readBody(req, 256 * 1024); } catch (e) { b = null; }
|
||||
if (!ok) { await adminaudit.record({ who, action: 'house-spins', target: String((b && b.email) || '').slice(0, 190), ok: false, ip: clientIp(req), detail: { error: 'not admin' } }); return json(res, 401, { error: 'Admin only.' }); }
|
||||
if (!b) { await adminaudit.record({ who, action: 'house-spins', ok: false, ip: clientIp(req), detail: { error: 'bad body' } }); return json(res, 400, { error: 'Send JSON.' }); }
|
||||
const r = await housespins.apply(b);
|
||||
const summary = r.error ? { error: r.error } : { host: r.host, spins: r.spins.map(x => ({ id: x.id, code: x.code, name: x.name, size: x.size, sourceId: x.sourceId, created: x.created, added: x.added, updated: x.updated, removed: x.removed, banners: x.banners, errors: x.errors })),
|
||||
asked: (b.spins || []).map(x => ({ id: x.id, name: x.name, size: x.size, sourceId: x.sourceId, fallback: x.fallback, banners: (x.banners || []).map(y => ({ label: y.label, image: y.image, target: y.target })) })) };
|
||||
await adminaudit.record({ who, action: 'house-spins', target: String(b.email || '').trim().toLowerCase(), ok: !r.error && r.ok, ip: clientIp(req), detail: summary });
|
||||
if (!r.error) content.invalidate();
|
||||
return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
if (p === '/api/admin/house-spins/log' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
||||
return json(res, 200, { entries: await adminaudit.list(u.searchParams.get('limit')) }, { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
// admin: every Banner Spin; the feature switch + tier grants (POST /api/admin/bannerspins { off } | { email, grant }); one Banner Spin or one banner off / on
|
||||
if (p === '/api/admin/bannerspins' && (req.method === 'GET' || req.method === 'POST')) {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
||||
|
||||
Reference in New Issue
Block a user