From a428075330713290d61da4f699256c5ec7f67a66 Mon Sep 17 00:00:00 2001 From: martbost Date: Mon, 16 Nov 2026 05:23:54 -0600 Subject: [PATCH] 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/, /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//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/ 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 --- board.js | 8 ++- chatbot.js | 9 ++- config.js | 3 + dlbnas.js | 16 +++++- public/admin.html | 30 ++++++++++ public/assets/admin.js | 65 +++++++++++++++++++++ public/assets/line.css | 6 ++ public/assets/my.js | 9 ++- public/board.html | 2 +- public/contract.html | 2 +- public/disclaimer.html | 2 +- public/how.html | 2 +- public/index.html | 2 +- public/join.html | 2 +- public/ledger.html | 2 +- public/my.html | 6 +- public/privacy.html | 2 +- public/promote.html | 2 +- public/terms.html | 2 +- qa/chat-qa.json | 2 + qa/smoke.mjs | 127 ++++++++++++++++++++++++++++++++++++++++- safety.js | 86 +++++++++++++++++++++++++++- server.js | 124 ++++++++++++++++++++++++++++++++++------ store.js | 25 ++++++++ 24 files changed, 499 insertions(+), 37 deletions(-) create mode 100644 public/admin.html create mode 100644 public/assets/admin.js diff --git a/board.js b/board.js index 5a2aca5..f04b490 100644 --- a/board.js +++ b/board.js @@ -9,6 +9,8 @@ const store = require('./store'); const DAY = 86400000; function creative(spot) { + // taken down by the admin (2026-11-16): the spot keeps its place but shows a house banner, nothing of its own + if (store.spotDown(spot.id)) { const h = houseFor(spot.id); return { img: h.img, link: h.link, from: 'down', key: h.key, title: h.title }; } const m = store.spotMeta(spot.id); if (m && m.img && m.link) return { img: m.img, link: m.link, from: 'spot' }; const d = store.memberDefault(spot.owner); @@ -30,7 +32,11 @@ let SPINS = []; function setMemberSpins(list) { SPINS = Array.isArray(list) ? list : []; } function memberSpins() { const a = SPINS.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } +// a spot the admin took down holds its place on the board with a house tile: no image, owner, link or number of its own, and +// t 'house' so no view or click is ever counted for it +function heldTile(s) { const h = houseFor(s.id); return { t: 'house', key: h.key, img: h.img, href: '/go/h-' + h.key, title: h.title, note: h.note || '', held: true }; } function spotTile(s) { + if (store.spotDown(s.id)) return heldTile(s); const c = cfgMod.get(); const cr = creative(s); const v = store.views(s.id); return { t: 'spot', id: s.id, owner: s.owner, img: cr.img, href: '/go/' + s.id, views: v.total, owed: c.viewsOwed, kind: s.kind }; } @@ -86,7 +92,7 @@ async function frameable(url) { function target(ref) { if (/^h-/.test(ref)) { const h = cfgMod.house().find(x => 'h-' + x.key === ref); return h ? { link: h.link, spotId: null } : null; } - const s = chain.spot(Number(ref)); if (!s || s.kind === 3) return null; + const s = chain.spot(Number(ref)); if (!s || s.kind === 3 || store.spotDown(s.id)) return null; // taken down: /go/ goes home return { link: creative(s).link, spotId: s.id }; } diff --git a/chatbot.js b/chatbot.js index 315a05e..99ddcf6 100644 --- a/chatbot.js +++ b/chatbot.js @@ -12,7 +12,7 @@ const core = require('./chatcore'); const C = require('./config').get(); -const KNOWLEDGE_DATE = '2026-11-15'; +const KNOWLEDGE_DATE = '2026-11-16'; const URL_ = 'https://' + C.site; const SUPPORT = 'https://instantadpay.com/support'; const NOT_PROMISED = 'Nothing is promised: you are paid only when spots sell after yours, and a spot can earn back less than it cost.'; @@ -24,6 +24,9 @@ const CANNED = [ { id: 'refund', title: 'Refunds', q: ['Can I get a refund on my spot?', 'Can I cancel my spot?'], tags: ['refund', 'cancel'], re: /\brefund|cancel (my |the |a )?spot|money back|reverse (my |a |the )?(payment|transaction)/i, handoff: true, a: 'Spots are paid on Polygon straight to the contract and are final once confirmed, so they cannot be reversed or refunded. A spot is one payment, never a subscription. If something went wrong with a payment, open network support at ' + SUPPORT + ' with the transaction link.' }, + { id: 'takedown', title: 'A spot taken down', q: ['Why was my spot taken down?', 'My banner was removed', 'Can my spot be taken down?'], tags: ['taken down', 'takedown', 'removed', 'hidden'], + re: /(taken down|take ?down|took (my |it |the )?(spot|banner)? ?down|(spot|banner) (was |got |is )?(removed|hidden|gone|blocked))/i, + a: 'A spot whose banner or link breaks the rules (terms: ' + URL_ + '/terms) can be taken down by the admin. It is then hidden everywhere at once, its place in the line is kept (a network banner shows there, so nobody else moves), and no views count while it is down. My Spots shows "Taken down" with the reason. The on-chain payments from the purchase already happened and do not change. The admin can restore a spot taken down by mistake. To ask about one, open network support at ' + SUPPORT + ' with the spot number.' }, { id: 'about', title: 'What is Downline Banners?', q: ['What is Downline Banners?', 'How does Downline Banners work?', 'What is DLB?'], tags: ['downline banners', 'dlb', 'line', 'board', 'overview'], re: /(what('s| is) (downline ?banners?|dlb|the line|this (site|place))|how does (downline ?banners?|dlb|the line|this site|it) work)/i, a: 'Downline Banners is one global line of 468x60 banner spots. A $5 spot buys ' + C.viewsOwed + ' guaranteed views on the board for your image and link (within ' + C.spotDays + ' days, newest spots on top) and a place in the line. When a later spot sells, the contract pays the 10 spots before it and the buyer\'s sponsor in that same transaction. ' + NOT_PROMISED + ' See ' + URL_ + '/how' }, @@ -50,7 +53,7 @@ const CANNED = [ a: 'A spot is $5 in POL at the Chainlink POL/USD price, one payment, never a subscription. It buys ' + C.viewsOwed + ' guaranteed views on the board for your 468x60 image and link, delivered within ' + C.spotDays + ' days, and a place in the line. Each spot takes the next place, so you can buy more than one. If a spot has not reached ' + C.viewsOwed + ' views after ' + C.spotDays + ' days, Network Ad Space finishes it. Get one at ' + URL_ + '/join' }, { id: 'banner', title: 'Your banner image and link', q: ['How do I add my banner?', 'What size is the banner?', 'How do I change my image?'], tags: ['banner', '468x60', 'image', 'link', 'my spots'], re: /(468 ?x ?60|banner (size|image)|what size|upload|add (my |an )?(image|banner|link)|change (my )?(image|banner|link)|my spots)/i, - a: 'After buying, open My Spots (' + URL_ + '/my), sign in with one free signature (it cannot move funds), and add your 468x60 image (150 KB or less) and link to each spot. Your spot then shows on the board, newest on top, until it has its ' + C.viewsOwed + ' views.' }, + a: 'After buying, open My Spots (' + URL_ + '/my), sign in with one free signature (it cannot move funds), and add your 468x60 image (150 KB or less) and link to each spot. Your spot then shows on the board, newest on top, until it has its ' + C.viewsOwed + ' views. You can change the image or link any time, as often as you like: every change gets the full check (https, a real website, no link shorteners, the link must open, an image address must load as a 468x60 image) and is logged on the spot.' }, { id: 'wallet', title: 'Signing in and paying', q: ['How do I sign in?', 'Which wallet should I use?', 'How do I pay?'], tags: ['sign in', 'wallet', 'pol', 'safepal'], re: /(sign ?(in|up)|log ?in|account|which wallet|what wallet|wallet|metamask|safepal|\bpol\b|polygon|crypto|gas|fee|how (do|can) i (pay|buy))/i, a: 'Pay from your own wallet straight to the contract with SafePal or any other crypto wallet on Polygon; the site never holds your money. Keep a little extra POL for the network fee. Sign in to My Spots with one free signature, or through your InstantAdPay or LinkSpin account.' }, @@ -76,6 +79,8 @@ const FACTS = () => [ '- SPLIT (contract constants, no setters, no owner withdraw): 30% ($1.50) to the buyer\'s sponsor (none: the momentum fund); 55% = $0.275 to each owner of the 10 spots bought just before; 10% company; 5% momentum fund. Same transaction. A failed send goes to the fund. The contract holds nothing except the fund. From the line alone, a member who refers nobody gets back less than $5 per spot. Never estimate totals.', '- MOMENTUM FUND: only buys spots. No sale for ' + C.keeperStallHours + ' hours: it buys one (max ' + C.keeperMaxPerDay + ' a day), gifted to an active member who owns a paid spot and had no gift in 7 days, recent referrers first; nobody qualifies: the fund keeps the spot and its line money returns to the fund.', '- JOIN FLOW: "Look around first" on the home page (sponsor\'s spot, the board, the 3 newest spots, each a short timer), then Join unlocks. /join: connect a wallet and buy, or "Buy a spot for someone else" (they own it). My Spots (/my): one free signature, add a 468x60 image (150 KB max) and link per spot.', + '- EDITS: a spot\'s image and link (and the default) can be changed any number of times. Every change gets the full check (https, public site, no shorteners, the link must answer, an image address must download as a real 468x60 image of 150 KB or less) and is logged on the spot (old and new link and image, time).', + '- TAKEDOWN: the admin can take down a spot that breaks the rules, with a reason. It is hidden everywhere (board, gate, links, Network Ad Space), keeps its place (a house banner holds it, nobody moves), counts no views while down; the owner sees "Taken down" with the reason on My Spots. On-chain payments already happened at purchase and never change; there is no refund. The admin can restore it.', '- REFUEL SPOTS: a counted Monthly Refuel of $50+ on InstantAdPay or LinkSpin earns one spot, bought for the member under their network sponsor, paid by the company.', '- BOARD: open slots show members\' LinkSpin Banner Spins, then network house ads (InstantAdPay, LinkSpin, network games). Pages: /, /board, /how, /join, /my, /promote, /ledger, /contract, /terms, /disclaimer, /privacy.', '- NO REFUNDS: blockchain payments are final. SUPPORT for account or payment problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site). This is advertising with a share of later sales, not an investment. Nothing is promised.' diff --git a/config.js b/config.js index da336ef..ef2058d 100644 --- a/config.js +++ b/config.js @@ -42,6 +42,9 @@ function get() { // board + gate viewsOwed: 300, spotDays: 30, boardSlots: Number(e.BOARD_SLOTS || 12), gateVisitSeconds: 9, gateBoardSeconds: 10, + // every edit of a spot's (or the default's) link and image gets the full check (2026-11-16): the link must answer, an image + // address must download as a real 468x60 image. LINK_PROBE=0 turns the network part off (local smoke only). + linkProbe: e.LINK_PROBE !== '0', // keeper (fund buys). KEEPER_KEY is never stored in cfg: keeper.js reads it from env at signing time only. keeperEnabled: e.KEEPER_ENABLED === '1', keeperStallHours: Number(e.KEEPER_STALL_HOURS || 4), diff --git a/dlbnas.js b/dlbnas.js index 15d02ca..fe73ef4 100644 --- a/dlbnas.js +++ b/dlbnas.js @@ -5,6 +5,8 @@ // so the board gets traffic without crowding InstantAdPay members' paid ads out of NAS. // - spots: a spot past its 30 days with fewer than 300 views gets its own banner placed in NAS for exactly the views still owed; // what NAS serves counts toward the spot's 300 (served(spotId)). +// - a spot the admin took down (2026-11-16) gets no new NAS banner, and its running one is paused (approved = 0, so NAS serves +// none of it and no views count) until it is restored (approved = 1). // State in dlb-nas.json (a MySQL document through docstore). Inert unless NAS_DB_* are set. 'use strict'; const crypto = require('crypto'); @@ -50,7 +52,8 @@ async function tick() { for (const sp of R.spots()) { const id = String(sp.id); const owed = c.viewsOwed - R.views(sp.id); const rec = s.spots[id]; - if (rec) { const sv = await served(rec.id); if (sv != null) rec.served = sv; continue; } + if (rec) { const sv = await served(rec.id); if (sv != null) rec.served = sv; if (R.isDown && R.isDown(sp.id) && !rec.paused) await pause(sp.id); continue; } + if (R.isDown && R.isDown(sp.id)) continue; // taken down: no NAS banner while it is down if (sp.kind === 3 || owed <= 0 || Date.now() - sp.boughtAt < c.spotDays * 86400000) continue; const cr = R.creative(sp); let img = cr.img || ''; if (img.startsWith('/')) img = site + img; if (!/^https:\/\/.+\.(png|jpe?g|gif)(\?.*)?$/i.test(img) && !/\/i\/[a-z0-9]+\.gif/i.test(img)) img = site + '/art/house-strip-nas.png'; @@ -61,8 +64,17 @@ async function tick() { } catch (e) { s.lastErr = String(e.message).slice(0, 200); console.error('dlbnas', e.message); } save(); } +// takedown / restore (2026-11-16): pause or resume a spot's running NAS banner. -> 'paused' | 'resumed' | 'none' | 'off' +async function pause(id) { + const rec = load().spots[String(id)]; if (!rec) return 'none'; if (!on()) return 'off'; + await q('UPDATE sponsorads SET approved = 0 WHERE ID = ?', [Number(rec.id)]); rec.paused = Date.now(); save(); return 'paused'; +} +async function resume(id) { + const rec = load().spots[String(id)]; if (!rec || !rec.paused) return 'none'; if (!on()) return 'off'; + await q('UPDATE sponsorads SET approved = 1 WHERE ID = ?', [Number(rec.id)]); delete rec.paused; save(); return 'resumed'; +} // views NAS delivered for a spot (counted toward its 300) function spotServed(id) { const r = load().spots[String(id)]; return r ? (r.served || 0) : 0; } function init(deps) { R = deps; if (!on()) { console.log('dlbnas: off (no NAS_DB_*)'); return; } load(); setTimeout(() => tick().catch(() => {}), 30000); const t = setInterval(() => tick().catch(() => {}), 6 * 3600000); t.unref && t.unref(); } function view() { const s = load(); return { on: on(), house: s.house || null, spots: s.spots, lastOk: s.lastOk || null, lastErr: s.lastErr || null }; } -module.exports = { init, tick, spotServed, view, on }; +module.exports = { init, tick, spotServed, view, on, pause, resume }; diff --git a/public/admin.html b/public/admin.html new file mode 100644 index 0000000..82f1458 --- /dev/null +++ b/public/admin.html @@ -0,0 +1,30 @@ + + + + +Admin | Downline Banners + + + + + + + + +
+

Admin

Take a spot down or restore it. The contract is never touched: only what this site shows and counts changes.

+
+ + +
+ + + + diff --git a/public/assets/admin.js b/public/assets/admin.js new file mode 100644 index 0000000..b9b3093 --- /dev/null +++ b/public/assets/admin.js @@ -0,0 +1,65 @@ +// Admin (2026-11-16): spot takedown and restore with a required reason, and the admin ledger. Read with the ADMIN_TOKEN (kept in this tab only). +(function () { + BL.renderNav(''); + const $ = BL.$, esc = BL.esc; + let tok = ''; try { tok = sessionStorage.getItem('bl.admin') || ''; } catch (e) {} + const get = u => BL.getJSON(u, { headers: { 'x-admin-token': tok } }); + const send = (u, body) => BL.getJSON(u, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-admin-token': tok }, body: JSON.stringify(body) }); + const ct = t => t ? new Date(t).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT' : ''; + const who = x => x.username ? '@' + x.username : BL.short(x.owner || ''); + async function open() { + const s = await get('/api/admin/actions?n=1'); + if (s.error) { BL.status('That token was not accepted.', 'err'); return; } + try { sessionStorage.setItem('bl.admin', tok); } catch (e) {} + $('tokCard').hidden = true; $('adm').hidden = false; BL.status(''); + actions(); + } + async function actions() { + const a = await get('/api/admin/actions?n=200'); if (a.error) return; + $('aActions').innerHTML = a.actions.length ? '' + + a.actions.map(e => '').join('') + '
WhenActionSpotOwnerByReasonCredit
' + esc(ct(e.at)) + '' + esc(e.action) + '#' + e.spotId + '' + esc(who(e)) + '' + esc(e.by) + '' + esc(e.reason || '') + '' + esc(e.credit) + '
' + : '

No takedowns yet.

'; + } + async function find() { + const q = $('spQ').value.trim(); if (!q) return; + const d = await get('/api/admin/spots?q=' + encodeURIComponent(q)); + if (d.error) { $('spList').innerHTML = '

' + esc(d.error) + '

'; return; } + $('spList').innerHTML = ''; + for (const s of d.spots) { + const el = document.createElement('div'); el.className = 'spot-ed adm-spot'; + const st = s.down ? 'TAKEN DOWN ' + ct(s.down.at) + ' by ' + s.down.by + ': ' + s.down.reason + ' (no credit)' : 'Showing (' + s.showing.from + ')'; + const edits = s.edits.length ? '
' + s.edits.length + ' edit' + (s.edits.length === 1 ? '' : 's') + ' (newest first)' + + s.edits.map(e => '').join('') + '
WhenWhatOldNew
' + esc(ct(e.at)) + '' + esc(e.what) + ' (' + esc(e.via) + ')' + esc(e.old.link) + '
' + esc(e.old.img) + '
' + esc(e.new.link) + '
' + esc(e.new.img) + '
' : '

No edits yet.

'; + el.innerHTML = '
Spot #' + s.id + '' + esc(who(s)) + ' ' + esc(s.owner) + '
' + + '

' + esc(st) + '
Link: ' + esc(s.link || '(default or none)') + '
' + s.views + ' of ' + s.owed + ' views, ' + + (s.clicks.organic + s.clicks.gate) + ' clicks. Bought ' + esc(ct(s.boughtAt)) + '.' + (s.downs.length ? ' Restored before: ' + s.downs.length + 'x.' : '') + '

' + edits + '
'; + el.querySelector('.lots').appendChild(BL.tile({ t: 'x', img: s.img || s.showing.img, href: '#' })); + const act = el.querySelector('.act'); + if (s.down) { + act.innerHTML = '
'; + act.querySelector('button').onclick = async () => { + const r = await send('/api/admin/spots/' + s.id + '/restore', { reason: act.querySelector('.rs').value }); + BL.status(r.error || ('Spot #' + s.id + ' restored.'), r.error ? 'err' : 'ok'); find(); actions(); + }; + } else if (s.kind !== 3) { + act.innerHTML = '
' + + '
' + + '
'; + const bt = act.querySelector('button'); + bt.onclick = async () => { + const reason = act.querySelector('.why').value.trim(); + if (reason.length < 3) return BL.status('Write the reason first.', 'err'); + if (!bt.dataset.armed) { bt.dataset.armed = '1'; bt.textContent = 'Click again to take down #' + s.id; setTimeout(() => { if (bt.isConnected) { delete bt.dataset.armed; bt.textContent = 'Take down'; } }, 8000); return; } + const r = await send('/api/admin/spots/' + s.id + '/takedown', { reason, credit: 'none' }); + BL.status(r.error || ('Spot #' + s.id + ' taken down, no credit.'), r.error ? 'err' : 'ok'); find(); actions(); + }; + } + $('spList').appendChild(el); + } + } + $('spFind').onclick = find; + $('spQ').addEventListener('keydown', e => { if (e.key === 'Enter') find(); }); + $('tokBtn').onclick = () => { tok = $('tok').value.trim(); open(); }; + $('tok').addEventListener('keydown', e => { if (e.key === 'Enter') $('tokBtn').click(); }); + if (tok) open(); +})(); diff --git a/public/assets/line.css b/public/assets/line.css index a3ceb5e..5b1b0ea 100644 --- a/public/assets/line.css +++ b/public/assets/line.css @@ -68,3 +68,9 @@ nav .links a.active{color:var(--mint-ink);background:var(--mint)} .bl-foot .netline{margin-top:12px;padding-top:12px;border-top:1px solid var(--line);line-height:1.9} .bl-foot .netline .here{color:var(--mint-ink);background:var(--mint);font-weight:700;border-radius:999px;padding:1px 9px} .legal .card h2{font-size:21px} .legal .card p,.legal .card li{max-width:760px;color:var(--ink)} .legal .card ul{padding-left:20px} .legal .card li{margin:6px 0} +/* spot takedown + edit history (2026-11-16) */ +.spot-down{border:1px solid var(--line-strong);border-left:4px solid #ff5d6c;border-radius:10px;padding:10px 12px;margin:8px 0} +.spot-down b{color:#ff5d6c} +.adm-scroll{overflow-x:auto} +.adm-spot details{margin:6px 0} +.adm-spot .tbl td{word-break:break-all} diff --git a/public/assets/my.js b/public/assets/my.js index 88ae63d..9da940d 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -40,7 +40,14 @@ const el = document.createElement('div'); el.className = 'spot-ed'; const head = kind === 'spot' ? '
Spot #' + s.id + '' + esc(KIND[s.kind] || '') + ' · ' + s.views + ' of ' + s.owed + ' views' + (s.kind === 3 ? '' : s.delivering ? ' · ' + s.daysLeft + ' days left' : ' · delivery finished') + ' · clicks ' + (s.clicks.organic + s.clicks.gate) + '
' : ''; - el.innerHTML = head + '
' + // taken down by the admin (2026-11-16): the reason, and no edit controls (the spot keeps its place; a house banner shows there) + if (kind === 'spot' && s.down) { + el.innerHTML = head + '
Taken down ' + esc(new Date(s.down.at).toLocaleDateString()) + '. Reason: ' + esc(s.down.reason) + + '
It is hidden everywhere and counts no views while it is down; its place is kept. Questions: use the chat on this page.
'; + return el; + } + const hist = kind === 'spot' && s.edits && s.edits.length ? '

Last change ' + esc(new Date(s.edits[0].at).toLocaleString()) + ' (' + s.edits.length + (s.edits.length >= 10 ? '+' : '') + ' logged). Every change gets the full link check.

' : ''; + el.innerHTML = head + hist + '
' + '
Tracking: {clickid}, {spot} and {type} in your link are filled on every click (LinkSpin has a Downline Banners source ready for this).
' + '
' + '
' diff --git a/public/board.html b/public/board.html index 1553f22..9be396f 100644 --- a/public/board.html +++ b/public/board.html @@ -21,7 +21,7 @@ - +
diff --git a/public/contract.html b/public/contract.html index f7453ce..84cdde1 100644 --- a/public/contract.html +++ b/public/contract.html @@ -21,7 +21,7 @@ - +
diff --git a/public/disclaimer.html b/public/disclaimer.html index e0662ae..2ce1065 100644 --- a/public/disclaimer.html +++ b/public/disclaimer.html @@ -21,7 +21,7 @@ - +
diff --git a/public/how.html b/public/how.html index e5a60cd..3e1afa4 100644 --- a/public/how.html +++ b/public/how.html @@ -21,7 +21,7 @@ - +
diff --git a/public/index.html b/public/index.html index 0c0b630..0face98 100644 --- a/public/index.html +++ b/public/index.html @@ -22,7 +22,7 @@ - +
diff --git a/public/join.html b/public/join.html index a72cf73..204d4ae 100644 --- a/public/join.html +++ b/public/join.html @@ -21,7 +21,7 @@ - +
diff --git a/public/ledger.html b/public/ledger.html index 9feee90..a04019a 100644 --- a/public/ledger.html +++ b/public/ledger.html @@ -21,7 +21,7 @@ - +
diff --git a/public/my.html b/public/my.html index 0427ea7..560c978 100644 --- a/public/my.html +++ b/public/my.html @@ -22,7 +22,7 @@ - +
@@ -33,7 +33,7 @@

Your share link

People who join through this link have you as their sponsor. It is set once, on their first spot.

-

Spots

Image: 468x60 PNG, JPG or GIF up to 150 KB, or an https image address. Link: https only. Change them any time. A spot with no image shows your default, or a network image until you add one.

+

Spots

Image: 468x60 PNG, JPG or GIF up to 150 KB, or an https image address. Link: https only. Change them any time, as often as you like: every change is checked (the link must open, an image address must load) and logged. A spot with no image shows your default, or a network image until you add one.

Default image and link

Used by any spot you have not set up.

Payments to you

@@ -43,7 +43,7 @@ - + diff --git a/public/privacy.html b/public/privacy.html index ecfcc1d..8e0932a 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -21,7 +21,7 @@ - +
diff --git a/public/promote.html b/public/promote.html index 9036922..1e8940f 100644 --- a/public/promote.html +++ b/public/promote.html @@ -21,7 +21,7 @@ - + diff --git a/public/terms.html b/public/terms.html index 0e3d8a0..7db2a39 100644 --- a/public/terms.html +++ b/public/terms.html @@ -21,7 +21,7 @@ - +
diff --git a/qa/chat-qa.json b/qa/chat-qa.json index a297812..7af3fc6 100644 --- a/qa/chat-qa.json +++ b/qa/chat-qa.json @@ -6,6 +6,8 @@ { "q": "Where does the $5 go?", "kb": "split", "must": ["30%", "55%", "\\$0.275", "10%", "5%"] }, { "q": "What do I get when someone I referred buys?", "kb": "split", "must": ["\\$1.50"] }, { "q": "What size is the banner?", "kb": "banner", "must": ["468x60", "150 KB"] }, + { "q": "How often can I change my image or link?", "kb": "banner", "must": ["as often as you like", "full check", "logged"] }, + { "q": "Why was my spot taken down?", "kb": "takedown", "must": ["Taken down", "reason", "place"] }, { "q": "What is the momentum fund?", "kb": "fund", "must": ["4 hours", "7 days"] }, { "q": "Why is Join locked?", "kb": "tour", "must": ["timer"] }, { "q": "Can I buy a spot for someone else?", "kb": "buy-for", "must": ["wallet address"] }, diff --git a/qa/smoke.mjs b/qa/smoke.mjs index cf29640..2b2633e 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -17,6 +17,42 @@ const { ethers } = require('ethers'); const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true }); +// stand-in internet for the link check (2026-11-16): preloaded into the app (NODE_OPTIONS --require), it answers safety.js's https.get +// calls (the ones with a lookup) and the DNS lookups those make, so every edit gets the full check with nothing leaving this machine. Like Node 20, +// the request asks the lookup for every address (all: true) and needs an array back (the VBB/ViralAdBlitz bug of 2026-11-15). +// Hosts: private.* -> 10.0.0.5 (refused), down.* unreachable, e404.* answers 404, redir.* 302 to https://example.org/landed, +// redir-http.* 302 to an http address, small.* a 125x125 image, anything else 200 (an image path gets a real 468x60 PNG). +const PROBE_STUB = `const https = require('https'), dns = require('dns'), fs = require('fs'), zlib = require('zlib'), { EventEmitter } = require('events'), { PassThrough } = require('stream'); +const LOG = process.env.PROBE_LOG; +let probing = false; const dnsLookup = dns.lookup; // only lookups made by a link check are answered here; the app's other traffic resolves as usual +dns.lookup = function (h, o, cb) { if (!probing) return dnsLookup.apply(this, arguments); if (typeof o === 'function') { cb = o; o = {}; } const list = [{ address: String(h).startsWith('private.') ? '10.0.0.5' : '93.184.216.34', family: 4 }]; setImmediate(() => o && o.all ? cb(null, list) : cb(null, list[0].address, 4)); }; +function png(w, h) { + const T = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; }); + const crc = b => { let c = 0xffffffff; for (const x of b) c = T[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; + const ch = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([l, td, c]); }; + const ih = Buffer.alloc(13); ih.writeUInt32BE(w, 0); ih.writeUInt32BE(h, 4); ih[8] = 8; ih[9] = 2; + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), ch('IHDR', ih), ch('IDAT', zlib.deflateSync(Buffer.alloc((w * 3 + 1) * h))), ch('IEND', Buffer.alloc(0))]); +} +const orig = https.get; +https.get = function (url, opts, cb) { + if (!opts || typeof opts.lookup !== 'function') return orig.apply(this, arguments); + const u = new URL(url); const req = new EventEmitter(); req.destroy = () => {}; + if (LOG) fs.appendFileSync(LOG, u.href + '\\n'); + probing = true; try { opts.lookup(u.hostname, { all: true, family: 0 }, (err, list) => { + if (err) return req.emit('error', err); + if (!Array.isArray(list)) return req.emit('error', new Error('lookup answered ' + typeof list + ', not the array Node 20 asks for')); + const h = u.hostname; if (h.startsWith('down.')) return req.emit('error', new Error('ECONNREFUSED')); + const res = new PassThrough(); res.headers = {}; res.statusCode = 200; let body = Buffer.from('ok'); + if (h.startsWith('e404.')) res.statusCode = 404; + else if (h.startsWith('redir-http.')) { res.statusCode = 302; res.headers.location = 'http://plain-http.com/'; } + else if (h.startsWith('redir.')) { res.statusCode = 302; res.headers.location = 'https://example.org/landed'; } + else if (/\\.(png|gif|jpe?g)$/i.test(u.pathname)) { body = h.startsWith('small.') ? png(125, 125) : png(468, 60); res.headers['content-type'] = 'image/png'; } + res.location = res.headers.location; const destroy = res.destroy.bind(res); res.destroy = () => destroy(); + cb(res); res.end(body); + }); } finally { probing = false; } + return req; +};`; +const PROBE_LOG = path.join(OUT, 'probe-' + Date.now() + '.log'); const PROBE_FILE = path.join(OUT, 'probe-stub.cjs'); fs.writeFileSync(PROBE_FILE, PROBE_STUB); const ART = path.resolve(APP, '..', 'contracts', 'out'); const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', 'anvil.exe'); const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; @@ -117,7 +153,8 @@ async function main() { const env = Object.assign({}, process.env, { PORT: String(APP_PORT), DATA_DIR: DATA, CHAIN_ID: '31337', RPC_URLS: 'http://127.0.0.1:' + RPC_PORT, CONTRACT_ADDRESS: CA, DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', NETKB: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member', - TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT }); + TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT, + PROBE_LOG, NODE_OPTIONS: '--require ' + JSON.stringify(PROBE_FILE).slice(1, -1) }); // the link check runs on every edit against the stand-in internet (probe-stub.cjs) startStandIns(); const hid = n => 'h_' + String(n).padStart(16, '0'); const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here @@ -396,6 +433,94 @@ async function main() { ok(st2.hubEvents && st2.hubEvents.on && st2.hubEvents.stats.ended >= 5 && st2.hubEvents.stats.refused >= 2 && !JSON.stringify(st2.hubEvents).includes(HUB_SECRET), 'admin status shows the hub events (counts only, no secret)', st2.hubEvents); } + console.log('10. spot edits (unlimited, full check, logged) + admin takedown and restore'); + { const ADM = (q, body) => u.json(q, body, { 'x-admin-token': ADMIN }); + const probes = () => { try { return fs.readFileSync(PROBE_LOG, 'utf8').split('\n').filter(Boolean); } catch (e) { return []; } }; + // the Node 20 lookup shape (VBB and ViralAdBlitz broke on it 2026-11-15): this copy answers an array when asked for all + const safety = require(path.join(APP, 'safety.js')); const dns = require('node:dns'); const dl = dns.lookup; + dns.lookup = (h, o, cb) => { const list = [{ address: String(h).startsWith('private.') ? '10.0.0.5' : '93.184.216.34', family: 4 }]; cb(null, o && o.all ? list : list[0].address, 4); }; + const look = (h, o) => new Promise(r => safety.safeLookup(h, o, (e, a, f) => r({ e: e && e.message, a, f }))); + const l1 = await look('pub.com', { all: true }), l2 = await look('pub.com', {}), l3 = await look('private.com', { all: true }); dns.lookup = dl; + ok(Array.isArray(l1.a) && l1.a[0].address === '93.184.216.34' && l2.a === '93.184.216.34' && l2.f === 4 && /private/.test(l3.e || ''), 'safeLookup: an array when asked for every address (Node 20), one address otherwise, a private address refused', { l1, l2, l3 }); + const p0 = probes().length; const linkNow = async () => ((await m.json('/api/my')).spots.find(x => x.id === sid) || {}).link; + let e = await m.json('/api/my/spot/' + sid, { link: 'https://edit-one.com/a' }); + ok(e.ok && e.edit && e.edit.what === 'link' && e.edit.old.link === 'https://example.org/landing' && e.edit.new.link === 'https://edit-one.com/a' && e.edit.at > 0, 'an edit is logged on the spot: old and new link, time', e.edit); + ok(probes().slice(p0).some(l => l.includes('edit-one.com')), 'the new link was fetched (the full check ran on the edit)'); + let all = true; for (let i = 2; i <= 6; i++) { e = await m.json('/api/my/spot/' + sid, { link: 'https://edit-' + i + '.com/p' }); all = all && !!e.ok; } + ok(all && await linkNow() === 'https://edit-6.com/p', 'edits are unlimited: five more in a row all saved'); + const refuse = [['https://down.edit-x.com/', /could not reach/], ['https://e404.edit-x.com/', /error \(404\)/], ['https://private.edit-x.com/', /private network/], ['https://redir-http.edit-x.com/', /must start with https/], ['https://bit.ly/abc', /shortener/]]; + for (const [l, re] of refuse) { const r = await m.json('/api/my/spot/' + sid, { link: l }); ok(r._status === 400 && re.test(r.error || ''), 'edit refused by the full check: ' + l, r); } + ok(await linkNow() === 'https://edit-6.com/p', 'a refused edit changes nothing'); + e = await m.json('/api/my/spot/' + sid, { link: 'https://redir.edit-x.com/go' }); ok(e.ok && probes().some(l => l.startsWith('https://example.org/landed')), 'a redirecting link is followed and its target checked too', e); + e = await m.json('/api/my/spot/' + sid, { img: 'https://img.edit-x.com/b.png' }); + ok(e.ok && e.edit.what === 'img' && e.edit.new.img === 'https://img.edit-x.com/b.png' && probes().some(l => l.includes('img.edit-x.com')), 'an image address is downloaded and checked (468x60), then saved and logged', e.edit); + for (const [im, re] of [['https://small.edit-x.com/b.png', /468x60/], ['https://e404.edit-x.com/b.png', /answered 404/], ['https://down.edit-x.com/b.png', /could not download/]]) { const r = await m.json('/api/my/spot/' + sid, { img: im }); ok(r._status === 400 && re.test(r.error || ''), 'image refused: ' + im, r); } + e = await m.json('/api/my/spot/' + sid, { link: 'https://redir.edit-x.com/go' }); ok(e.ok && !e.edit, 'saving the same link again changes nothing and logs nothing', e); + const upE = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json(); ok(upE.ok, 'upload (edit by file)'); + const mine = (await m.json('/api/my')).spots.find(x => x.id === sid); + ok(mine.edits.length === 10 && mine.edits[0].via === 'upload' && mine.edits[0].old.img === 'https://img.edit-x.com/b.png' && mine.edits[0].new.img === upE.img, 'the owner sees the newest edits first (an upload is logged too)', mine.edits.slice(0, 2)); + const de = await m.json('/api/my/default', { link: 'https://e404.def-x.com/' }); const de2 = await m.json('/api/my/default', { link: 'https://def-ok.com/x' }); + ok(de._status === 400 && de2.ok && de2.edit && de2.edit.old.link === 'https://example.org/default', 'the default link gets the same check and log', { de, de2 }); + + console.log('10b. admin takedown and restore'); + const tilesOf = async () => (await v.json('/api/board')).tiles; + const t0 = await tilesOf(); const i0 = t0.findIndex(x => x.id === sid); + ok(i0 >= 0, 'the spot is on the board before', t0.map(x => x.id || x.t)); + let r = await u.json('/api/admin/spots?q=%23' + sid); ok(r._status === 401, 'admin find needs the token'); + const f1 = await ADM('/api/admin/spots?q=%23' + sid), f2 = await ADM('/api/admin/spots?q=' + addr[A]), f3 = await ADM('/api/admin/spots?q=alpha'); + ok(f1.spots && f1.spots[0].id === sid && f1.spots[0].edits.length >= 10 && f1.spots[0].defaultEdits.length >= 1 && [f2, f3].every(f => f.spots && f.spots.some(x => x.id === sid)), 'admin finds the spot by #number, wallet and username, with its edit log', { f2: f2.spots && f2.spots.length, f3: f3.error || f3.spots.length }); + ok((await ADM('/api/admin/spots?q=nobodyhere')).error, 'nothing found for an unknown username'); + const P = '/api/admin/spots/' + sid; + ok((await u.json(P + '/takedown', { reason: 'test', credit: 'none' }))._status === 401, 'takedown needs the token'); + ok((await ADM(P + '/takedown', { reason: '', credit: 'none' }))._status === 400, 'a reason is required'); + ok((await ADM(P + '/takedown', { reason: 'Broken landing page' }))._status === 400, 'a credit choice is required'); + const cb = await ADM(P + '/takedown', { reason: 'Broken landing page', credit: 'back' }); + ok(cb._status === 400 && /Marty decides/.test(cb.error) && !(await ADM('/api/admin/spots?q=%23' + sid)).spots[0].down, 'credit back is refused (not defined for Downline Banners yet) and nothing is taken down', cb.error); + const views0 = f1.spots[0].views; + const td = await ADM(P + '/takedown', { reason: 'Misleading offer on the landing page', credit: 'none', by: 'smoke' }); + ok(td.ok && td.down.reason === 'Misleading offer on the landing page' && td.log.action === 'takedown' && td.log.credit === 'none' && td.spot.showing.from === 'down', 'taken down, no credit; the admin view shows it', td); + ok((await ADM(P + '/takedown', { reason: 'again', credit: 'none' }))._status === 400, 'a second takedown is refused'); + const t1 = await tilesOf(); + ok(!t1.some(x => x.id === sid) && t1.length === t0.length && t1[i0] && t1[i0].t === 'house' && t1[i0].held === true && !t1[i0].owner, 'board: the spot is gone, a house tile holds its place, same number of tiles', t1.map(x => x.id || (x.held ? 'held' : x.t))); + ok(JSON.stringify(t1).indexOf(upE.img) < 0, 'its image shows nowhere on the board'); + ok((await v.req('/go/' + sid)).headers.get('location') === '/', '/go/ goes home while it is down'); + const gv = client('Mozilla/5.0 gate after takedown'); const gg = await gv.json('/api/gate', undefined, { 'X-Forwarded-For': '198.51.100.240' }); + ok(gg.steps && !gg.steps.some(st => st.ref === String(sid) || st.img === upE.img), 'the gate never shows it (a house site takes its step)', gg.steps && gg.steps.map(st => st.ref || st.type)); + const bt = await v.json('/api/board'); await sleep(4800); await v.json('/api/board/seen', { token: bt.token }); + ok((await ADM('/api/admin/spots?q=%23' + sid)).spots[0].views === views0, 'no views count while it is down'); + const mineD = (await m.json('/api/my')).spots.find(x => x.id === sid); + ok(mineD.down && mineD.down.reason === 'Misleading offer on the landing page' && mineD.showing.from === 'down', 'the owner sees "Taken down" with the reason', mineD.down); + const ed = await m.json('/api/my/spot/' + sid, { link: 'https://edit-7.com/' }); + const upD = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json(); + ok(ed._status === 400 && /taken down/.test(ed.error) && /taken down/.test(upD.error || ''), 'the owner cannot change a spot while it is down', { ed, upD }); + if (!process.env.SKIP_UI) { // the pages while it is down: My Spots at phone width, and the admin page + const { chromium } = require(PW); const br = await chromium.launch(); const errs = []; + const cx = await br.newContext({ viewport: { width: 390, height: 844 } }); await cx.addCookies([{ name: 'bl.sid', value: m.jar['bl.sid'], url: BASE }]); + const pg = await cx.newPage(); pg.on('pageerror', x => errs.push(x.message)); + await pg.goto(BASE + '/my', { waitUntil: 'networkidle' }); await pg.waitForSelector('.spot-down', { timeout: 8000 }).catch(() => {}); + const txt = await pg.textContent('#spots'); const wide = await pg.evaluate(() => { const e = document.getElementById('spots'); return e.scrollWidth - e.clientWidth; }); // the spots card (the payments table further down is wider than a phone on its own) + ok(/Taken down/.test(txt) && txt.includes('Misleading offer on the landing page') && wide <= 1, 'My Spots (phone): "Taken down" with the reason, no sideways scroll', { wide }); + ok(await pg.isVisible('#outAllBtn'), 'My Spots: Sign out everywhere button shows'); await pg.screenshot({ path: path.join(OUT, 'my-taken-down.png'), fullPage: true }); + const pa = await cx.newPage(); pa.on('pageerror', x => errs.push(x.message)); await pa.goto(BASE + '/admin', { waitUntil: 'networkidle' }); + await pa.fill('#tok', ADMIN); await pa.click('#tokBtn'); await pa.waitForSelector('#adm:not([hidden])', { timeout: 8000 }).catch(() => {}); + await pa.fill('#spQ', '#' + sid); await pa.click('#spFind'); await pa.waitForSelector('.adm-spot', { timeout: 8000 }).catch(() => {}); + const at = await pa.textContent('#spList'); const aw = await pa.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + ok(/TAKEN DOWN/.test(at) && /Restore this spot/.test(at) && /takedown/.test(await pa.textContent('#aActions')) && aw <= 1, 'admin page (phone): finds the spot, shows it taken down with Restore, ledger row', { aw }); + await pa.screenshot({ path: path.join(OUT, 'admin-takedown.png'), fullPage: true }); + ok(errs.length === 0, 'no page errors (taken-down views)', errs); await br.close(); + } + const acts = await ADM('/api/admin/actions'); + ok(acts.actions[0].action === 'takedown' && acts.actions[0].spotId === sid && acts.actions[0].reason === 'Misleading offer on the landing page' && acts.actions[0].credit === 'none' && acts.actions[0].by === 'smoke' && acts.actions[0].username === 'alpha', 'admin ledger: who, when, reason, credit decision', acts.actions[0]); + const rs = await ADM(P + '/restore', { reason: 'Owner fixed the page', by: 'smoke' }); + ok(rs.ok && !rs.spot.down && rs.spot.downs.length === 1 && rs.spot.downs[0].restoreReason === 'Owner fixed the page' && rs.log.action === 'restore', 'restore: shows again, the takedown kept in its history', rs); + ok((await ADM(P + '/restore', {}))._status === 400, 'restoring a spot that is not down is refused'); + const t2 = await tilesOf(); ok(t2.some(x => x.id === sid && x.img === upE.img), 'board shows the spot again after the restore'); + ok((await v.req('/go/' + sid)).headers.get('location') === 'https://redir.edit-x.com/go', '/go/ sends to its link again'); + ok((await m.json('/api/my/spot/' + sid, { link: 'https://edit-8.com/' })).ok, 'the owner can edit again after the restore'); + ok((await ADM('/api/admin/actions')).actions[0].action === 'restore', 'the restore is on the admin ledger'); + const ap = await u.req('/admin'); ok(ap.status === 200 && ap.headers.get('x-frame-options') === 'DENY' && /Take a spot down/.test(await ap.text()), '/admin page served, never framed'); + } + console.log('\n' + pass + ' passed, ' + fail + ' failed. Output in ' + OUT); cleanup(); process.exit(fail ? 1 : 0); } diff --git a/safety.js b/safety.js index 989336e..ddd878f 100644 --- a/safety.js +++ b/safety.js @@ -1,6 +1,8 @@ // Link + image checks for My Spots. https only, a real public hostname, no tricks; uploads must be a real // PNG/JPG/GIF at 468x60 (or 936x120 retina) and at most 150 KB. const net = require('net'); +const dns = require('dns'); +const https = require('https'); const MAX_UPLOAD = 150 * 1024; const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i; @@ -54,4 +56,86 @@ function checkImage(buf) { return { ok: true, info }; } -module.exports = { checkLink, checkImage, imageInfo, MAX_UPLOAD }; +// ---- the network part of the check (2026-11-16: every edit gets it, any number of edits) ---- +// Outbound requests only to public addresses: the DNS answer used for the connection is the one checked. +function privateIp(ip) { + if (net.isIPv4(ip)) { + const [a, b] = ip.split('.').map(Number); + return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) + || (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224; + } + const s = String(ip).toLowerCase(); + if (s.startsWith('::ffff:')) return privateIp(s.slice(7)); + return s === '::' || s === '::1' || s.startsWith('fc') || s.startsWith('fd') || s.startsWith('fe80') || s.startsWith('ff'); +} +// Node 20's https agent asks for every address (opts.all, for happy eyeballs) and expects an array back; answering with one +// address broke every link check on VBB and ViralAdBlitz (fixed there 2026-11-15). Answer in the shape asked for, private refused. +function safeLookup(host, opts, cb) { + if (typeof opts === 'function') { cb = opts; opts = {}; } + dns.lookup(host, Object.assign({}, opts, { all: true }), (err, list) => { + if (err) return cb(err); + if (!list || !list.length || list.some(a => privateIp(a.address))) return cb(new Error('private address')); + if (opts && opts.all) return cb(null, list); + cb(null, list[0].address, list[0].family); + }); +} +// GET with a size cap, a timeout and no redirects followed (a redirect is reported so the caller can decide) +function get(url, maxBytes, timeoutMs) { + return new Promise(resolve => { + let done = false; const fin = v => { if (!done) { done = true; resolve(v); } }; + let req; + try { + req = https.get(url, { lookup: safeLookup, timeout: timeoutMs || 5000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; DLBCheck/1.0; +https://downlinebanners.com)', Accept: '*/*' } }, res => { + const out = { status: res.statusCode, headers: res.headers, location: res.headers.location || null }; + if (!maxBytes) { res.destroy(); return fin(out); } + const ch = []; let n = 0; + res.on('data', c => { n += c.length; if (n > maxBytes) { res.destroy(); return fin(Object.assign(out, { tooBig: true })); } ch.push(c); }); + res.on('end', () => fin(Object.assign(out, { body: Buffer.concat(ch) }))); + res.on('error', () => fin(Object.assign(out, { error: 'read' }))); + }); + req.on('timeout', () => { req.destroy(); fin({ error: 'timeout' }); }); + req.on('error', e => fin({ error: /private address/.test(e.message) ? 'private' : 'unreachable' })); + } catch (e) { fin({ error: 'unreachable' }); } + }); +} +// the target link must answer (up to 3 redirects, each one checked like the link itself). Unlike VBB, a site that refuses frames +// is fine here: the gate opens it in a new tab instead (board.frameable). +async function probeLink(url) { + let cur = url; + for (let hop = 0; hop < 4; hop++) { + const r = await get(cur, 0, 6000); + if (r.error === 'private') return { error: 'That link points to a private network address.' }; + if (r.error) return { error: 'We could not reach that link. Check it opens in your browser and try again.' }; + if (r.status >= 300 && r.status < 400 && r.location) { + let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { error: 'That link redirects somewhere invalid.' }; } + const c = checkLink(next, 'The page your link redirects to'); if (c.error) return c; + cur = c.url; continue; + } + if (r.status >= 400) return { error: 'That link answered with an error (' + r.status + '). Use a page that loads.' }; + return { ok: true }; + } + return { error: 'That link redirects too many times.' }; +} +// an https image address: downloaded once and checked like an upload (468x60 or 936x120, 150 KB). The spot keeps the address +// (a LinkSpin Banner Spin image rotates, so it is never copied). -> { ok, info } or { error } +async function probeImage(url) { + let cur = url, r = null; + for (let hop = 0; hop < 4; hop++) { // up to 3 redirects, each one checked like the address itself + r = await get(cur, MAX_UPLOAD, 6000); + if (!r.error && r.status >= 300 && r.status < 400 && r.location) { + let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { error: 'That image address redirects somewhere invalid.' }; } + const c = checkLink(next, 'The address your image redirects to'); if (c.error) return c; + cur = c.url; r = null; continue; + } + break; + } + if (!r) return { error: 'That image address redirects too many times.' }; + if (r.error === 'private') return { error: 'That image address points to a private network address.' }; + if (r.error) return { error: 'We could not download that image. Check the address or upload the file instead.' }; + if (r.tooBig) return { error: 'That image is over 150 KB.' }; + if (r.status !== 200) return { error: 'The image address answered ' + r.status + '. Use a direct link to the image file, or upload it.' }; + const c = checkImage(r.body); if (c.error) return c; + return { ok: true, info: c.info }; +} + +module.exports = { checkLink, checkImage, imageInfo, privateIp, safeLookup, probeLink, probeImage, MAX_UPLOAD }; diff --git a/server.js b/server.js index 1292841..d71600b 100644 --- a/server.js +++ b/server.js @@ -222,10 +222,12 @@ async function visitStep(role, ref, img, link, title) { async function makeGate(req) { const vk = visitorKey(req); const steps = []; const sp = sponsorOf(req); const sSpot = sp && board.newestOf(sp); - if (sSpot) { const cr = board.creative(sSpot); steps.push(await visitStep('sponsor', sSpot.id, cr.img, cr.link, 'Your sponsor\'s newest spot')); } + // a spot the admin took down (2026-11-16) keeps its step, but the step shows a house site (never the spot's own banner or link) + const stepOf = async (role, s, title) => { const cr = board.creative(s); return cr.from === 'down' ? visitStep(role, 'h-' + cr.key, cr.img, cr.link, cr.title) : visitStep(role, s.id, cr.img, cr.link, title); }; + if (sSpot) steps.push(await stepOf('sponsor', sSpot, 'Your sponsor\'s newest spot')); steps.push({ type: 'board', tiles: board.pick(), seconds: C.gateBoardSeconds }); const nw = board.newest(3, sSpot ? [sSpot.id] : []); - for (const s of nw) { const cr = board.creative(s); steps.push(await visitStep('newest', s.id, cr.img, cr.link, 'Spot #' + s.id)); } + for (const s of nw) steps.push(await stepOf('newest', s, 'Spot #' + s.id)); const house = cfgMod.house().filter(h => h.link.startsWith('https://')); let hi = 0; while (steps.filter(x => x.role === 'newest' || x.role === 'house').length < 3 && house.length) { const h = house[hi++ % house.length]; steps.push(await visitStep('house', 'h-' + h.key, h.img, h.link, h.title)); if (hi > 6) break; } const gid = crypto.randomBytes(12).toString('hex'); @@ -244,7 +246,44 @@ function spotView(s) { const left = Math.max(0, C.spotDays - Math.floor((now - s.boughtAt) / 86400000)); return { id: s.id, kind: s.kind, boughtAt: s.boughtAt, tx: s.tx, valueWei: s.valueWei, views: v.total, gateViews: v.gate, owed: C.viewsOwed, clicks: store.clicks(s.id), daysLeft: left, delivering: s.kind !== 3 && left > 0 && v.total < C.viewsOwed, - img: m.img || '', link: m.link || '', showing: cr }; + img: m.img || '', link: m.link || '', showing: cr, + down: (dn => dn ? { at: dn.at, reason: dn.reason } : null)(store.spotDown(s.id)), // taken down by the admin: the owner sees the reason + edits: store.spotEdits(s.id).slice(-10).reverse() }; +} + +// ---- spot edits (Marty 2026-11-16): unlimited, every one gets the full check and is logged on the spot ---- +// checkLink first; then (LINK_PROBE on) the link must answer (safety.probeLink, up to 3 checked redirects) and an image address +// must download as a real 468x60 image (safety.probeImage). The one exception: the Banner Spin image + click link LinkSpin's signed +// answer just handed this member (/api/my/lsspins/use) are not fetched (fetching the click link would count a click on LinkSpin). +const lsVouched = new Map(); // wallet -> { link, img, at } +async function checkEdit(me, b, linkLabel) { + const out = {}; + if (b.link !== undefined) { if (b.link === '') out.link = ''; else { const r = safety.checkLink(b.link, linkLabel); if (r.error) return r; out.link = r.url; } } + if (b.img !== undefined && !String(b.img).startsWith('/art/u/')) { if (b.img === '') out.img = ''; else { const r = safety.checkLink(b.img, 'Image URL'); if (r.error) return r; out.img = r.url; } } + if (C.linkProbe) { + const v = lsVouched.get(me); const vouched = x => !!v && Date.now() - v.at < 30 * 60000 && (x === v.link || x === v.img); + if (out.link && !vouched(out.link)) { const pr = await safety.probeLink(out.link.replace(/\{(clickid|spot|type)\}/g, 'x')); if (pr.error) return pr; } + if (out.img && !vouched(out.img)) { const pr = await safety.probeImage(out.img); if (pr.error) return pr; } + } + return { ok: true, out }; +} +// one log row per real change: old and new link and image, when, how (edit, upload) +function logChange(kind, key, before, patch, via) { + const o = { img: (before && before.img) || '', link: (before && before.link) || '' }; const n = Object.assign({}, o, patch); + const what = ['link', 'img'].filter(k => o[k] !== n[k]); if (!what.length) return null; + const row = { what: what.length === 2 ? 'both' : what[0], old: o, new: { img: n.img, link: n.link }, via }; + return kind === 'spot' ? store.logSpotEdit(key, row) : store.logDefaultEdit(key, row); +} +const DOWN_EDIT = 'This spot was taken down, so it cannot be changed. The reason is shown on the spot.'; +// "credit back" has no meaning on Downline Banners yet (2026-11-16): a spot is a $5 on-chain purchase (POL cannot be refunded) and +// the site has no free replacement spot or post credit. Marty decides; until then a takedown is "no credit" only. +const CREDIT_BACK_PENDING = 'Credit back is not available on Downline Banners yet: a spot is a $5 on-chain purchase and this site has no free replacement spot or post credit. Marty decides what credit back means; until then choose credit: "none".'; +// the admin view of a spot: what it shows, its views, every edit, and its takedown history +async function adminSpot(s) { + const m = store.spotMeta(s.id) || {}; const v0 = store.views(s.id); + return { id: s.id, owner: s.owner, username: await nameOf(s.owner).catch(() => null), kind: s.kind, boughtAt: s.boughtAt, tx: s.tx, + img: m.img || '', link: m.link || '', showing: board.creative(s), views: v0.total + dlbnas.spotServed(s.id), owed: C.viewsOwed, clicks: store.clicks(s.id), + down: store.spotDown(s.id), downs: store.spotDowns(s.id), edits: store.spotEdits(s.id).slice(-50).reverse(), defaultEdits: store.defaultEdits(s.owner).slice(-10).reverse() }; } async function myData(addr) { const a = addr.toLowerCase(); @@ -297,13 +336,13 @@ const server = http.createServer(async (req, res) => { const net = old && OR[old]; res.writeHead(301, { Location: net ? '/?ref=' + encodeURIComponent(net) : '/', 'Cache-Control': 'no-store' }); return res.end(); } const PAGES = { '/': 'index.html', '/board': 'board.html', '/join': 'join.html', '/my': 'my.html', '/how': 'how.html', '/ledger': 'ledger.html', '/contract': 'contract.html', - '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html' }; // legal pages: trust pack 2026-11-14 + '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html', '/admin': 'admin.html' }; // legal pages: trust pack 2026-11-14; /admin 2026-11-16 if (PAGES[p]) { const set = []; if (setVid) set.push(setVid); if (u.searchParams.get('ref')) { const a = await resolveRef(u.searchParams.get('ref')); if (a) set.push(cookie('bl.ref', a, 90 * 86400, false)); } const ex = set.length ? { 'Set-Cookie': set } : {}; - if (p === '/my') ex['X-Frame-Options'] = 'DENY'; // member board: never framed (public pages stay frameable for traffic exchanges) + if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY'; // member board + admin: never framed (public pages stay frameable for traffic exchanges) return sendFile(res, path.join(PUB, PAGES[p]), ex); } if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); } @@ -482,32 +521,40 @@ const server = http.createServer(async (req, res) => { const me = s.address; if (p === '/api/my' && req.method === 'GET') return json(res, 200, await myData(me)); if (p === '/api/my/lsspins' && req.method === 'GET') { const r = await lsSpins({ wallet: me }); return json(res, r.error ? 502 : 200, r); } - if (p === '/api/my/lsspins/use' && req.method === 'POST') { const b = await readBody(req); const r = await lsSpins({ wallet: me, spinId: Number(b.spinId) || 0 }); return json(res, r.error ? 400 : 200, r); } + if (p === '/api/my/lsspins/use' && req.method === 'POST') { const b = await readBody(req); const r = await lsSpins({ wallet: me, spinId: Number(b.spinId) || 0 }); + if (!r.error && r.use) { const lk = safety.checkLink(r.use.link, 'link'), im = safety.checkLink(r.use.img, 'img'); if (lk.ok && im.ok) lsVouched.set(me, { link: lk.url, img: im.url, at: Date.now() }); if (lsVouched.size > 20000) lsVouched.clear(); } + return json(res, r.error ? 400 : 200, r); } let m = /^\/api\/my\/spot\/(\d+)$/.exec(p); if (m && req.method === 'POST') { const sp = chain.spot(m[1]); if (!sp || sp.owner !== me) return json(res, 403, { error: 'That spot is not yours.' }); - const b = await readBody(req); const out = {}; - if (b.link !== undefined) { if (b.link === '') out.link = ''; else { const r = safety.checkLink(b.link, 'Target link'); if (r.error) return json(res, 400, r); out.link = r.url; } } - if (b.img !== undefined && !String(b.img).startsWith('/art/u/')) { if (b.img === '') out.img = ''; else { const r = safety.checkLink(b.img, 'Image URL'); if (r.error) return json(res, 400, r); out.img = r.url; } } - return json(res, 200, { ok: true, meta: store.setSpotMeta(sp.id, out) }); + if (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT }); + if (limited(req, 'edit', 120, 3600000)) return json(res, 429, { error: 'Too many changes this hour. Try again in a while.' }); // each change fetches the link + const b = await readBody(req); const ck = await checkEdit(me, b, 'Target link'); if (ck.error) return json(res, 400, ck); + if (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT }); // re-checked after the fetches + const before = Object.assign({}, store.spotMeta(sp.id) || {}); + const meta = store.setSpotMeta(sp.id, ck.out); const edit = logChange('spot', sp.id, before, ck.out, 'edit'); + return json(res, 200, { ok: true, meta, edit }); } if (p === '/api/my/default' && req.method === 'POST') { - const b = await readBody(req); const out = {}; - if (b.link !== undefined) { if (b.link === '') out.link = ''; else { const r = safety.checkLink(b.link, 'Default link'); if (r.error) return json(res, 400, r); out.link = r.url; } } - if (b.img !== undefined && !String(b.img).startsWith('/art/u/')) { if (b.img === '') out.img = ''; else { const r = safety.checkLink(b.img, 'Image URL'); if (r.error) return json(res, 400, r); out.img = r.url; } } - return json(res, 200, { ok: true, defaults: store.setMemberDefault(me, out) }); + if (limited(req, 'edit', 120, 3600000)) return json(res, 429, { error: 'Too many changes this hour. Try again in a while.' }); + const b = await readBody(req); const ck = await checkEdit(me, b, 'Default link'); if (ck.error) return json(res, 400, ck); + const before = Object.assign({}, store.memberDefault(me) || {}); + const defaults = store.setMemberDefault(me, ck.out); const edit = logChange('default', me, before, ck.out, 'edit'); + return json(res, 200, { ok: true, defaults, edit }); } if (p === '/api/my/upload' && req.method === 'POST') { if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' }); const target = u.searchParams.get('for') || ''; let sp = null; - if (target !== 'default') { sp = chain.spot(target); if (!sp || sp.owner !== me) return json(res, 403, { error: 'That spot is not yours.' }); } + if (target !== 'default') { sp = chain.spot(target); if (!sp || sp.owner !== me) return json(res, 403, { error: 'That spot is not yours.' }); if (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT }); } let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 150 KB.' }); } const r = safety.checkImage(buf); if (r.error) return json(res, 400, r); const name = (sp ? 's' + sp.id : 'd' + me.slice(2, 10)) + '-' + crypto.randomBytes(5).toString('hex') + r.info.ext; fs.writeFileSync(path.join(C.dataDir, 'art', name), buf); const img = '/art/u/' + name; + const before = Object.assign({}, (sp ? store.spotMeta(sp.id) : store.memberDefault(me)) || {}); if (sp) store.setSpotMeta(sp.id, { img }); else store.setMemberDefault(me, { img }); + logChange(sp ? 'spot' : 'default', sp ? sp.id : me, before, { img }, 'upload'); return json(res, 200, { ok: true, img }); } return json(res, 404, { error: 'Not found' }); @@ -569,6 +616,51 @@ const server = http.createServer(async (req, res) => { gifted: chain.fundBuys().filter(f => f.giftee === a), contract: C.contract, explorer: C.explorer })); } + // -- admin: spot takedown and restore (Marty 2026-11-16, the Viral Banner Blitz way). The spot is a $5 on-chain purchase: the + // contract is never touched; only what this site shows and counts changes. Taken down = hidden everywhere at once (board, gate, + // /go, Network Ad Space), its place held by a house tile so nobody else moves, no views or clicks counted while down; the owner + // sees "Taken down" with the reason; one admin ledger row per takedown and restore. + if (p === '/api/admin/spots' || p === '/api/admin/actions' || /^\/api\/admin\/spots\/\d{1,9}\/(takedown|restore)$/.test(p)) { + const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' }); + if (p === '/api/admin/actions' && req.method === 'GET') return json(res, 200, { actions: store.adminLogs(Math.min(500, Math.max(1, Number(u.searchParams.get('n')) || 100))) }); + // GET ?q=# | | | + if (p === '/api/admin/spots' && req.method === 'GET') { + const q = String(u.searchParams.get('q') || '').trim(); let list = []; + if (/^#?\d{1,9}$/.test(q)) { const sp = chain.spot(Number(q.replace('#', ''))); if (sp) list = [sp]; } + else if (ADDR_RE.test(q)) list = chain.spotsOf(q.toLowerCase()); + else if (/^@?[a-zA-Z0-9_]{1,20}$/.test(q)) { + const name = q.replace(/^@/, '').toLowerCase(); const al = Object.entries(aliases()).find(([, v]) => v && String(v.username || '').toLowerCase() === name); + const a = al ? al[0] : await resolveRef(name).catch(() => null); if (a) list = chain.spotsOf(a); + } + if (!list.length) return json(res, 404, { error: 'No spot found for that.' }); + return json(res, 200, { spots: await Promise.all(list.slice(0, 100).map(adminSpot)) }); + } + const tk = /^\/api\/admin\/spots\/(\d{1,9})\/(takedown|restore)$/.exec(p); + if (tk && req.method === 'POST') { + const sp = chain.spot(Number(tk[1])); if (!sp) return json(res, 404, { error: 'No such spot.' }); + const b = await readBody(req); const by = String(b.by || 'admin').replace(/[^\w .@-]/g, '').slice(0, 40) || 'admin'; + const reason = String(b.reason || '').replace(/[\u0000-\u001f\u007f<>]/g, '').replace(/\s+/g, ' ').trim(); + const username = await nameOf(sp.owner).catch(() => null); + if (tk[2] === 'takedown') { + if (store.spotDown(sp.id)) return json(res, 400, { error: 'That spot is already taken down.' }); + if (sp.kind === 3) return json(res, 400, { error: 'A fund-kept spot never shows, so there is nothing to take down.' }); + if (reason.length < 3 || reason.length > 300) return json(res, 400, { error: 'A reason is required (3 to 300 characters). The owner sees it.' }); + if (b.credit === 'back') return json(res, 400, { error: CREDIT_BACK_PENDING }); + if (b.credit !== 'none') return json(res, 400, { error: 'Choose credit: "none". (Credit back is not available on Downline Banners yet.)' }); + const rec = store.setSpotDown(sp.id, { at: Date.now(), by, reason, credit: 'none', views: store.views(sp.id).total }); + const nas = await dlbnas.pause(sp.id).catch(e => 'error: ' + String(e.message).slice(0, 80)); + const e = store.adminLog({ action: 'takedown', spotId: sp.id, owner: sp.owner, username, by, reason, credit: 'none', nas }); + return json(res, 200, { ok: true, spot: await adminSpot(sp), down: rec, log: e }); + } + const was = store.spotDown(sp.id); if (!was) return json(res, 400, { error: 'That spot is not taken down.' }); + store.clearSpotDown(sp.id, { restoredAt: Date.now(), restoredBy: by, restoreReason: reason || null }); + const nas = await dlbnas.resume(sp.id).catch(e => 'error: ' + String(e.message).slice(0, 80)); + const e = store.adminLog({ action: 'restore', spotId: sp.id, owner: sp.owner, username, by, reason: reason || null, credit: 'none given', nas }); + return json(res, 200, { ok: true, spot: await adminSpot(sp), log: e }); + } + return json(res, 404, { error: 'Not found' }); + } + if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' }); res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end('Not found

Not found. Downline Banners home

' @@ -603,7 +695,7 @@ function weekLine() { hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() }); refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy()); keeper.init(); - dlbnas.init({ spots: () => chain.spots(), views: id => store.views(id).total, creative: board.creative }); + dlbnas.init({ spots: () => chain.spots(), views: id => store.views(id).total, creative: board.creative, isDown: id => !!store.spotDown(id) }); // members' LinkSpin Banner Spins for empty board slots: one active 468x60 spin per member, refreshed every 10 minutes const refreshSpins = async () => { const out = []; diff --git a/store.js b/store.js index d02484c..dae2cf4 100644 --- a/store.js +++ b/store.js @@ -28,12 +28,35 @@ function setSpotMeta(id, m) { S.spotMeta[id] = Object.assign({}, 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); @@ -43,6 +66,7 @@ function addView(spotId, visitorKey, source) { } 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); @@ -69,4 +93,5 @@ function keeperLog(entry) { S.keeper.log.push(Object.assign({ at: Date.now() }, 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 };