Files
martbost a428075330 Spot edits: unlimited, full link check on every one, every one logged; admin takedown and restore (Marty 2026-11-16)
Edits (POST /api/my/spot/<id>, /api/my/default, uploads): still any number of times. Every change now gets the full check:
checkLink, then (LINK_PROBE on) the link must answer (safety.probeLink, up to 3 redirects each checked) and an image address must
download as a real 468x60 image of 150 KB or less (safety.probeImage; the address is kept, a Banner Spin image rotates). The
Banner Spin image + click link LinkSpin just handed the member are not fetched (that would count a LinkSpin click). safety.js gains
privateIp + safeLookup with the Node 20 fix VBB/ViralAdBlitz needed (honors opts.all, answers an array). Every real change is
logged on the spot (or the default): old and new link and image, time, via edit/upload; the owner sees the newest 10. 120 changes
an hour per connection (each one fetches the link).

Admin takedown (the Viral Banner Blitz way, 8e6d2f9): /admin (new page) finds a spot by #number, wallet or network username;
POST /api/admin/spots/<id>/takedown {reason (required, the owner sees it), credit}. Hidden everywhere at once: the board shows a
house tile in its place (nobody else moves), the gate gives its step to a house site, /go/<id> goes home, its Network Ad Space
banner is paused (approved = 0) and no new one is placed. No views or clicks count while down. My Spots shows "Taken down" with
the reason and no edit controls. Restore (POST .../restore) reverses it (NAS resumed). Admin ledger: GET /api/admin/actions (who,
when, reason, credit decision). The contract is never touched.
CREDIT BACK IS NOT BUILT: a spot is a $5 on-chain purchase and this site has no free replacement spot or post credit, so
credit: "back" is refused with a note until Marty decides what it means here; takedowns are "no credit".
Chatbot: CANNED takedown + banner answer (unlimited checked, logged edits) + FACTS EDITS/TAKEDOWN lines, KNOWLEDGE_DATE 2026-11-16.
line.css?v=9, my.js?v=z3.
Tests: smoke section 10 (the lookup shape, edit log, unlimited edits, refusals: unreachable, 404, private address, http redirect,
shortener, bad image size/404/unreachable; redirect followed; same link logs nothing; upload logged; default checked + logged;
takedown: token, reason, credit choice, credit back refused, held house tile, image nowhere, /go home, gate, no views, owner view,
no edits while down, ledger, restore, /admin) against a stand-in internet preloaded into the app (qa/out/probe-stub.cjs, nothing
leaves the machine), plus phone renders of My Spots taken down and /admin: 193/193 with UI. chatbot.test 181/181.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 05:23:54 -06:00

98 lines
7.1 KiB
JavaScript

// JSON volume store (the InstantAdPay JSON-mode pattern: one file in DATA_DIR, atomic tmp+rename, debounced).
// Holds only what the chain does not: banner + link per spot, member defaults, views/visits delivered,
// sign-in sessions, last-seen times and the keeper log. Every function is sync and small so a MySQL
// version can replace this file behind the same names later.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cfgMod = require('./config');
let S = null, saveT = null;
const FILE = () => path.join(cfgMod.get().dataDir, 'store.json');
function load() {
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
S = Object.assign({ v: 1, spotMeta: {}, defaults: {}, views: {}, clicks: {}, seen: {}, sessions: {}, keeper: { log: [] }, daily: {} }, S || {});
const now = Date.now();
for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k];
}
function save(now) {
if (saveT && !now) return;
const run = () => { saveT = null; try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(S), { mode: 0o600 }); fs.renameSync(tmp, FILE()); } catch (e) { console.error('store save failed', e.message); } };
if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 1500);
}
function flush() { save(true); }
// ---- creative per spot + member default ----
function spotMeta(id) { return S.spotMeta[id] || null; }
function setSpotMeta(id, m) { S.spotMeta[id] = Object.assign({}, S.spotMeta[id] || {}, m, { updatedAt: Date.now() }); save(); return S.spotMeta[id]; }
function memberDefault(addr) { return S.defaults[String(addr).toLowerCase()] || null; }
function setMemberDefault(addr, m) { const a = String(addr).toLowerCase(); S.defaults[a] = Object.assign({}, S.defaults[a] || {}, m, { updatedAt: Date.now() }); save(); return S.defaults[a]; }
// ---- edit history (2026-11-16: unlimited edits, every one logged): { at, what: 'link'|'img'|'both', old: {img, link}, new: {img, link}, via }
const EDIT_KEEP = 200;
function logEdit(bucket, key, e) { const b = S[bucket] || (S[bucket] = {}); const l = b[key] || (b[key] = []); l.push(Object.assign({ at: Date.now() }, e)); if (l.length > EDIT_KEEP) l.splice(0, l.length - EDIT_KEEP); save(); return l[l.length - 1]; }
const logSpotEdit = (id, e) => logEdit('spotEdits', String(id), e);
const logDefaultEdit = (addr, e) => logEdit('defaultEdits', String(addr).toLowerCase(), e);
const spotEdits = id => ((S.spotEdits || {})[String(id)] || []).slice();
const defaultEdits = addr => ((S.defaultEdits || {})[String(addr).toLowerCase()] || []).slice();
// ---- admin takedown (2026-11-16, the Viral Banner Blitz way): a spot taken down is hidden everywhere, keeps its place (a house
// tile shows there) and counts no views while down. { at, by, reason, credit }; restores move it to the spot's history.
function spotDown(id) { return (S.down || {})[String(id)] || null; }
function setSpotDown(id, rec) { (S.down || (S.down = {}))[String(id)] = rec; save(true); return rec; }
function clearSpotDown(id, restored) {
const k = String(id); const was = spotDown(k); if (!was) return null;
delete S.down[k]; const h = S.downs || (S.downs = {}); (h[k] || (h[k] = [])).push(Object.assign({}, was, restored || {})); save(true); return h[k][h[k].length - 1];
}
const spotDowns = id => ((S.downs || {})[String(id)] || []).slice();
const downIds = () => Object.keys(S.down || {});
// the admin ledger: one row per takedown or restore
function adminLog(e) { const L = S.adminLog || (S.adminLog = []); S.adminSeq = (S.adminSeq || 0) + 1; const row = Object.assign({ id: 'a' + S.adminSeq, at: Date.now() }, e); L.push(row); if (L.length > 5000) L.splice(0, L.length - 5000); save(true); return row; }
const adminLogs = n => (S.adminLog || []).slice(-(n || 100)).reverse();
// ---- views + clicks (gate and organic kept apart) ----
// Rate limit: one counted view per visitor per spot per hour, one counted click per visitor per spot per hour.
const seenView = new Map(), seenClick = new Map();
const HOUR = 3600000;
function prune(m) { if (m.size < 50000) return; const cut = Date.now() - HOUR; for (const [k, t] of m) if (t < cut) m.delete(k); }
function addView(spotId, visitorKey, source) {
if (spotDown(spotId)) return false; // taken down: no views count while it is down
const k = visitorKey + ':' + spotId; const t = seenView.get(k);
if (t && Date.now() - t < HOUR) return false;
seenView.set(k, Date.now()); prune(seenView);
const v = S.views[spotId] || (S.views[spotId] = { organic: 0, gate: 0 });
v[source === 'gate' ? 'gate' : 'organic'] += 1; bumpDaily('views_' + (source === 'gate' ? 'gate' : 'organic')); save();
return true;
}
function views(spotId) { const v = S.views[spotId] || { organic: 0, gate: 0 }; return { organic: v.organic, gate: v.gate, total: v.organic + v.gate }; }
function addClick(spotId, visitorKey, source) {
if (spotDown(spotId)) return false;
const k = visitorKey + ':' + spotId + ':' + source; const t = seenClick.get(k);
if (t && Date.now() - t < HOUR) return false;
seenClick.set(k, Date.now()); prune(seenClick);
const c = S.clicks[spotId] || (S.clicks[spotId] = { organic: 0, gate: 0 });
c[source === 'gate' ? 'gate' : 'organic'] += 1; bumpDaily('clicks_' + (source === 'gate' ? 'gate' : 'organic')); save();
return true;
}
function clicks(spotId) { return S.clicks[spotId] || { organic: 0, gate: 0 }; }
function bumpDaily(k) { const day = new Date().toISOString().slice(0, 10); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + 1; }
function daily() { return S.daily; }
// ---- sessions + last seen ----
const SESSION_TTL = 7 * 24 * HOUR;
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; touch(address); save(); return token; }
function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; }
function dropSession(token) { delete S.sessions[token]; save(); }
// network hub events (hubevents.js, 2026-11-16): end every session `match` names that was made before `before` -> how many
function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; }
function touch(address) { S.seen[String(address).toLowerCase()] = Date.now(); save(); }
function lastSeen(address) { return S.seen[String(address).toLowerCase()] || 0; }
// ---- keeper ----
function keeperLog(entry) { S.keeper.log.push(Object.assign({ at: Date.now() }, entry)); if (S.keeper.log.length > 2000) S.keeper.log = S.keeper.log.slice(-2000); save(true); }
function keeperEntries() { return S.keeper.log.slice(); }
module.exports = { load, flush, spotMeta, setSpotMeta, memberDefault, setMemberDefault, addView, views, addClick, clicks, daily,
logSpotEdit, logDefaultEdit, spotEdits, defaultEdits, spotDown, setSpotDown, clearSpotDown, spotDowns, downIds, adminLog, adminLogs,
mintSession, session, dropSession, endSessions, touch, lastSeen, keeperLog, keeperEntries, SESSION_TTL };