Compare commits
2 Commits
046b3068cb
...
a428075330
| Author | SHA1 | Date | |
|---|---|---|---|
| a428075330 | |||
| 197aa39fca |
@@ -9,6 +9,8 @@ const store = require('./store');
|
|||||||
const DAY = 86400000;
|
const DAY = 86400000;
|
||||||
|
|
||||||
function creative(spot) {
|
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);
|
const m = store.spotMeta(spot.id);
|
||||||
if (m && m.img && m.link) return { img: m.img, link: m.link, from: 'spot' };
|
if (m && m.img && m.link) return { img: m.img, link: m.link, from: 'spot' };
|
||||||
const d = store.memberDefault(spot.owner);
|
const d = store.memberDefault(spot.owner);
|
||||||
@@ -30,7 +32,11 @@ let SPINS = [];
|
|||||||
function setMemberSpins(list) { SPINS = Array.isArray(list) ? list : []; }
|
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; }
|
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) {
|
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);
|
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 };
|
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) {
|
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; }
|
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/<id> goes home
|
||||||
return { link: creative(s).link, spotId: s.id };
|
return { link: creative(s).link, spotId: s.id };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+7
-2
@@ -12,7 +12,7 @@
|
|||||||
const core = require('./chatcore');
|
const core = require('./chatcore');
|
||||||
const C = require('./config').get();
|
const C = require('./config').get();
|
||||||
|
|
||||||
const KNOWLEDGE_DATE = '2026-11-15';
|
const KNOWLEDGE_DATE = '2026-11-16';
|
||||||
const URL_ = 'https://' + C.site;
|
const URL_ = 'https://' + C.site;
|
||||||
const SUPPORT = 'https://instantadpay.com/support';
|
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.';
|
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'],
|
{ 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,
|
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.' },
|
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'],
|
{ 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,
|
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' },
|
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' },
|
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'],
|
{ 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,
|
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'],
|
{ 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,
|
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.' },
|
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.',
|
'- 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.',
|
'- 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.',
|
'- 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.',
|
'- 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.',
|
'- 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.'
|
'- 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.'
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ function get() {
|
|||||||
// board + gate
|
// board + gate
|
||||||
viewsOwed: 300, spotDays: 30, boardSlots: Number(e.BOARD_SLOTS || 12),
|
viewsOwed: 300, spotDays: 30, boardSlots: Number(e.BOARD_SLOTS || 12),
|
||||||
gateVisitSeconds: 9, gateBoardSeconds: 10,
|
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.
|
// 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',
|
keeperEnabled: e.KEEPER_ENABLED === '1',
|
||||||
keeperStallHours: Number(e.KEEPER_STALL_HOURS || 4),
|
keeperStallHours: Number(e.KEEPER_STALL_HOURS || 4),
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
// so the board gets traffic without crowding InstantAdPay members' paid ads out of NAS.
|
// 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;
|
// - 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)).
|
// 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.
|
// State in dlb-nas.json (a MySQL document through docstore). Inert unless NAS_DB_* are set.
|
||||||
'use strict';
|
'use strict';
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
@@ -50,7 +52,8 @@ async function tick() {
|
|||||||
for (const sp of R.spots()) {
|
for (const sp of R.spots()) {
|
||||||
const id = String(sp.id); const owed = c.viewsOwed - R.views(sp.id);
|
const id = String(sp.id); const owed = c.viewsOwed - R.views(sp.id);
|
||||||
const rec = s.spots[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;
|
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;
|
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';
|
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); }
|
} catch (e) { s.lastErr = String(e.message).slice(0, 200); console.error('dlbnas', e.message); }
|
||||||
save();
|
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)
|
// 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 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 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 }; }
|
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 };
|
||||||
|
|||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
// Network hub events for a wallet site (Marty 2026-11-16, "Yes do 1 and 2"). Byte-identical in Viral Banner Blitz, Downline Banners,
|
||||||
|
// ViralAdBlitz, DownlineHydra and 5xYourTeam (like networksso.js): copy it whole, never edit one copy alone.
|
||||||
|
//
|
||||||
|
// The hub tells every hooked site what changed (POST /api/hub/events, the same hook InstantAdPay and LinkSpin take): X-Hub-Ts +
|
||||||
|
// X-Hub-Sig = hex HMAC-SHA256(HUB_SECRET, ts + newline + raw body), 5-minute window. The hub only moves its cursor after a 2xx and
|
||||||
|
// may send an event twice. This site acts on three events and ignores every other one:
|
||||||
|
// member.signedout "Sign out everywhere" on any network site
|
||||||
|
// member.blocked the hub blocked the person
|
||||||
|
// member.erased the hub erased the person ({emailHash, walletHashes}: the person is gone from the hub, so no lookup)
|
||||||
|
// Each one ends that person's sessions here. A wallet site keys sessions by wallet, so the person is mapped through the hub:
|
||||||
|
// POST /v1/resolve {id} (signed as HUB_SITE) gives their main wallet and every contract wallet (contractWallets). An erased
|
||||||
|
// person cannot be looked up any more: the event carries the SHA-256 of each of their wallets (and of their email) instead.
|
||||||
|
// Only sessions made BEFORE the event end (a fresh sign-in after it stays), so a replay can never sign anyone out twice.
|
||||||
|
// A failed lookup answers 503 so the hub sends the batch again; after 5 tries an event is set aside in the log.
|
||||||
|
// Nothing here sends mail, posts or touches a banner, a payout or the chain: it only ends sign-in sessions.
|
||||||
|
//
|
||||||
|
// init({ dataDir, site, end }) where end({ type, personId, at, wallets, walletHashes, emailHash, match }) ends the sessions and
|
||||||
|
// answers how many; match(session-like {address?, email?, wallet?, hubId?}) is the shared test (wallet, wallet hash, email
|
||||||
|
// hash, hub id). Off when HUB_HOOK=0, or without HUB_URL and a 32+ character HUB_SECRET (then the route answers 404).
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const WALLET_RE = /^0x[0-9a-f]{40}$/, HASH_RE = /^[0-9a-f]{64}$/;
|
||||||
|
const TRIES = 5, KEEP = 3000, SKEW = 2000;
|
||||||
|
const ACTS = new Set(['member.signedout', 'member.blocked', 'member.erased']);
|
||||||
|
let R = null, st = null, chain_ = Promise.resolve();
|
||||||
|
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const SITE = () => String(process.env.HUB_SITE || (R && R.site) || '').trim().toLowerCase();
|
||||||
|
const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_HOOK || '').trim()) && /^https?:\/\/[a-z0-9.:-]+$/i.test(BASE()) && SECRET().length >= 32;
|
||||||
|
const lc = v => String(v == null ? '' : v).trim().toLowerCase();
|
||||||
|
const sha = v => crypto.createHash('sha256').update(lc(v)).digest('hex');
|
||||||
|
const FILE = () => path.join(R.dataDir, 'hubevents.json');
|
||||||
|
|
||||||
|
function load() {
|
||||||
|
if (st) return st;
|
||||||
|
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||||
|
if (!st || typeof st !== 'object') st = {};
|
||||||
|
st.done = st.done || {}; st.tries = st.tries || {}; st.log = st.log || [];
|
||||||
|
st.stats = Object.assign({ batches: 0, events: 0, ended: 0, ignored: 0, skipped: 0, gaveUp: 0, refused: 0 }, st.stats || {});
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
function save() { if (!R || !R.dataDir) return; try { const t = FILE() + '.tmp'; fs.writeFileSync(t, JSON.stringify(load())); fs.renameSync(t, FILE()); } catch (e) { console.error('hubevents save', e.message); } }
|
||||||
|
function note(x) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, x)); if (s.log.length > 200) s.log = s.log.slice(-200); }
|
||||||
|
function init(deps) { R = deps || {}; load(); }
|
||||||
|
|
||||||
|
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
|
||||||
|
function verify(headers, raw) {
|
||||||
|
if (SECRET().length < 32) return false;
|
||||||
|
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
|
||||||
|
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000 || !/^[0-9a-f]{64}$/.test(sig)) return false;
|
||||||
|
const want = sign(ts, raw);
|
||||||
|
return crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
||||||
|
}
|
||||||
|
// the hub person by hub id (null = the hub does not know them); throws when the hub does not answer
|
||||||
|
async function resolveId(id) {
|
||||||
|
const raw = JSON.stringify({ id }); const ts = String(Date.now());
|
||||||
|
const r = await fetch(BASE() + '/v1/resolve', { method: 'POST', body: raw, signal: AbortSignal.timeout(10000),
|
||||||
|
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) } });
|
||||||
|
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
|
||||||
|
const j = await r.json(); return j && j.person && typeof j.person === 'object' ? j.person : null;
|
||||||
|
}
|
||||||
|
// every wallet the hub holds for a person: the main wallet and each contract's wallet
|
||||||
|
function walletsOf(p) {
|
||||||
|
const out = new Set(); if (!p) return [];
|
||||||
|
if (WALLET_RE.test(lc(p.wallet))) out.add(lc(p.wallet));
|
||||||
|
for (const w of Object.values(p.contractWallets || {})) if (WALLET_RE.test(lc(w))) out.add(lc(w));
|
||||||
|
return [...out];
|
||||||
|
}
|
||||||
|
// the shared test: does this session / member belong to the person?
|
||||||
|
function matcher(who) {
|
||||||
|
const ws = new Set(who.wallets || []), hs = new Set(who.walletHashes || []), eh = who.emailHash || null, id = who.personId || null;
|
||||||
|
return x => {
|
||||||
|
if (!x) return false;
|
||||||
|
for (const w of [x.address, x.wallet, x.hubWallet]) { const v = lc(w); if (WALLET_RE.test(v) && (ws.has(v) || hs.has(sha(v)))) return true; }
|
||||||
|
if (eh && x.email && sha(x.email) === eh) return true;
|
||||||
|
if (id && (x.hubId === id || x.key === id)) return true;
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
async function apply(ev) {
|
||||||
|
if (!ACTS.has(ev.type) || !ev.personId) return 'ignored';
|
||||||
|
const who = { type: ev.type, personId: String(ev.personId), at: Number(ev.at) || Date.now(), wallets: [], walletHashes: [], emailHash: null };
|
||||||
|
if (ev.type === 'member.erased') {
|
||||||
|
const d = ev.data || {};
|
||||||
|
who.walletHashes = (Array.isArray(d.walletHashes) ? d.walletHashes : []).map(lc).filter(h => HASH_RE.test(h)).slice(0, 50);
|
||||||
|
who.emailHash = HASH_RE.test(lc(d.emailHash)) ? lc(d.emailHash) : null;
|
||||||
|
} else {
|
||||||
|
const p = await resolveId(who.personId); // throws: the hub sends it again
|
||||||
|
if (!p) return 'ignored';
|
||||||
|
who.wallets = walletsOf(p);
|
||||||
|
}
|
||||||
|
who.before = who.at + SKEW; // sessions made after the event are fresh sign-ins and stay
|
||||||
|
who.match = matcher(who);
|
||||||
|
const n = Number(await R.end(who)) || 0;
|
||||||
|
note({ type: ev.type, seq: ev.seq, sessions: n });
|
||||||
|
if (n) { load().stats.ended += n; return 'applied'; }
|
||||||
|
return 'none';
|
||||||
|
}
|
||||||
|
function prune() {
|
||||||
|
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
|
||||||
|
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP))) delete s.done[q];
|
||||||
|
}
|
||||||
|
async function handle(events) {
|
||||||
|
const s = load(); s.stats.batches++; let failed = null;
|
||||||
|
for (const ev of Array.isArray(events) ? events : []) {
|
||||||
|
const seq = Number(ev && ev.seq); if (!seq) continue;
|
||||||
|
if (s.done[seq]) { s.stats.skipped++; continue; }
|
||||||
|
s.stats.events++;
|
||||||
|
try {
|
||||||
|
const r = await apply(ev);
|
||||||
|
s.done[seq] = Date.now(); delete s.tries[seq];
|
||||||
|
if (r === 'ignored') s.stats.ignored++;
|
||||||
|
} catch (e) {
|
||||||
|
s.tries[seq] = (s.tries[seq] || 0) + 1;
|
||||||
|
console.error('hubevents', seq, ev.type, e.message);
|
||||||
|
if (s.tries[seq] >= TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
|
||||||
|
failed = e; break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prune(); save();
|
||||||
|
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
|
||||||
|
}
|
||||||
|
// the POST /api/hub/events handler -> { status, body }. Batches run one at a time.
|
||||||
|
function receive(headers, raw) {
|
||||||
|
if (!R || !on()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
|
||||||
|
if (!verify(headers || {}, String(raw || ''))) { load().stats.refused++; return Promise.resolve({ status: 401, body: { error: 'unauthorized' } }); }
|
||||||
|
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
|
||||||
|
const run = chain_.then(() => handle(b && b.events)); chain_ = run.catch(() => {}); return run;
|
||||||
|
}
|
||||||
|
function view() { const s = load(); return { on: on(), stats: s.stats, waiting: Object.keys(s.tries).length, log: s.log.slice(-20) }; }
|
||||||
|
|
||||||
|
module.exports = { init, receive, view, on, verify, walletsOf, matcher, sha, _reset: () => { st = null; chain_ = Promise.resolve(); } };
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Admin | Downline Banners</title>
|
||||||
|
<meta name="description" content="Downline Banners admin.">
|
||||||
|
<meta name="robots" content="noindex">
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="wrap">
|
||||||
|
<section class="hero"><h1>Admin</h1><p class="lead">Take a spot down or restore it. The contract is never touched: only what this site shows and counts changes.</p></section>
|
||||||
|
<div class="card" id="tokCard"><div class="field"><label for="tok">Admin token</label><input id="tok" type="password" autocomplete="off"></div><button class="btn small" id="tokBtn">Open</button></div>
|
||||||
|
<div id="adm" hidden>
|
||||||
|
<div class="card" id="spCard"><h3>Spots: take down or restore</h3>
|
||||||
|
<p class="muted small">Find a spot by #number, wallet or network username. A takedown hides it everywhere at once (board, gate, links, Network Ad Space). Its place stays, held by a house banner, so nobody else moves. No views or clicks count while it is down. The owner sees "Taken down" with your reason. Payments already happened on-chain at purchase and are never touched.</p>
|
||||||
|
<p class="muted small">Credit back: not available yet. A spot is a $5 on-chain purchase and this site has no free replacement spot or post credit, so a takedown is "no credit" until Marty decides what credit back means here.</p>
|
||||||
|
<div class="row"><input id="spQ" placeholder="#12, 0x... or username" autocomplete="off" aria-label="Find a spot" style="flex:1;min-width:200px"><button class="btn sec small" id="spFind">Find</button></div>
|
||||||
|
<div id="spList"></div></div>
|
||||||
|
<div class="card"><h3>Admin ledger (takedowns and restores)</h3><div class="adm-scroll" id="aActions"></div></div>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="note" hidden></div>
|
||||||
|
</main>
|
||||||
|
<script src="/assets/common.js?v=20261115nr"></script>
|
||||||
|
<script src="/assets/admin.js?v=1"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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 ? '<table class="tbl"><tr><th>When</th><th>Action</th><th>Spot</th><th>Owner</th><th>By</th><th>Reason</th><th>Credit</th></tr>'
|
||||||
|
+ a.actions.map(e => '<tr><td>' + esc(ct(e.at)) + '</td><td>' + esc(e.action) + '</td><td>#' + e.spotId + '</td><td>' + esc(who(e)) + '</td><td>' + esc(e.by) + '</td><td>' + esc(e.reason || '') + '</td><td>' + esc(e.credit) + '</td></tr>').join('') + '</table>'
|
||||||
|
: '<p class="muted">No takedowns yet.</p>';
|
||||||
|
}
|
||||||
|
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 = '<p class="note err small">' + esc(d.error) + '</p>'; 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 ? '<details><summary class="small">' + s.edits.length + ' edit' + (s.edits.length === 1 ? '' : 's') + ' (newest first)</summary><table class="tbl"><tr><th>When</th><th>What</th><th>Old</th><th>New</th></tr>'
|
||||||
|
+ s.edits.map(e => '<tr><td>' + esc(ct(e.at)) + '</td><td>' + esc(e.what) + ' (' + esc(e.via) + ')</td><td class="mono small">' + esc(e.old.link) + '<br>' + esc(e.old.img) + '</td><td class="mono small">' + esc(e.new.link) + '<br>' + esc(e.new.img) + '</td></tr>').join('') + '</table></details>' : '<p class="muted small">No edits yet.</p>';
|
||||||
|
el.innerHTML = '<div class="row" style="justify-content:space-between"><b>Spot #' + s.id + '</b><span class="small">' + esc(who(s)) + ' <span class="mono">' + esc(s.owner) + '</span></span></div>'
|
||||||
|
+ '<div class="lots"></div><p class="small">' + esc(st) + '<br>Link: <span class="mono">' + esc(s.link || '(default or none)') + '</span><br><span class="muted">' + 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.' : '') + '</span></p>' + edits + '<div class="act"></div>';
|
||||||
|
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 = '<div class="field"><label class="small muted">Why restore (optional)</label><input class="rs"></div><button class="btn small">Restore this spot</button>';
|
||||||
|
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 = '<div class="field"><label class="small muted">Reason (the owner sees it)</label><textarea class="why" maxlength="300" rows="2"></textarea></div>'
|
||||||
|
+ '<div class="row"><label class="small"><input type="radio" name="cr' + s.id + '" value="none" checked> No credit</label><label class="small muted"><input type="radio" name="cr' + s.id + '" value="back" disabled> Credit back (not available yet)</label>'
|
||||||
|
+ '<button class="btn small">Take down</button></div>';
|
||||||
|
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();
|
||||||
|
})();
|
||||||
@@ -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{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}
|
.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}
|
.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}
|
||||||
|
|||||||
+9
-1
@@ -17,6 +17,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$('outBtn').onclick = async () => { await BL.post('/api/auth/logout'); location.reload(); };
|
$('outBtn').onclick = async () => { await BL.post('/api/auth/logout'); location.reload(); };
|
||||||
|
$('outAllBtn').onclick = async () => { $('outAllBtn').disabled = true; await BL.post('/api/auth/logout-everywhere'); location.reload(); };
|
||||||
async function load() {
|
async function load() {
|
||||||
const d = await BL.getJSON('/api/my');
|
const d = await BL.getJSON('/api/my');
|
||||||
if (d.error) return BL.status(d.error, 'err');
|
if (d.error) return BL.status(d.error, 'err');
|
||||||
@@ -39,7 +40,14 @@
|
|||||||
const el = document.createElement('div'); el.className = 'spot-ed';
|
const el = document.createElement('div'); el.className = 'spot-ed';
|
||||||
const head = kind === 'spot' ? '<div class="row" style="justify-content:space-between"><b>Spot #' + s.id + '</b><span class="muted small">' + esc(KIND[s.kind] || '') + ' · ' + s.views + ' of ' + s.owed + ' views'
|
const head = kind === 'spot' ? '<div class="row" style="justify-content:space-between"><b>Spot #' + s.id + '</b><span class="muted small">' + 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) + '</span></div>' : '';
|
+ (s.kind === 3 ? '' : s.delivering ? ' · ' + s.daysLeft + ' days left' : ' · delivery finished') + ' · clicks ' + (s.clicks.organic + s.clicks.gate) + '</span></div>' : '';
|
||||||
el.innerHTML = head + '<div class="lots" style="align-items:flex-start"></div>'
|
// 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 + '<div class="spot-down"><b>Taken down</b> ' + esc(new Date(s.down.at).toLocaleDateString()) + '. Reason: ' + esc(s.down.reason)
|
||||||
|
+ '<br><span class="small muted">It is hidden everywhere and counts no views while it is down; its place is kept. Questions: use the chat on this page.</span></div>';
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
const hist = kind === 'spot' && s.edits && s.edits.length ? '<p class="small muted">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.</p>' : '';
|
||||||
|
el.innerHTML = head + hist + '<div class="lots" style="align-items:flex-start"></div>'
|
||||||
+ '<div class="field"><label class="small muted">Target link (https)</label><input data-k="link" placeholder="https://your-site.com/page" value="' + esc(s.link || '') + '"><span class="small muted">Tracking: {clickid}, {spot} and {type} in your link are filled on every click (LinkSpin has a Downline Banners source ready for this).</span></div>'
|
+ '<div class="field"><label class="small muted">Target link (https)</label><input data-k="link" placeholder="https://your-site.com/page" value="' + esc(s.link || '') + '"><span class="small muted">Tracking: {clickid}, {spot} and {type} in your link are filled on every click (LinkSpin has a Downline Banners source ready for this).</span></div>'
|
||||||
+ '<div class="field"><label class="small muted">Image address (https), or upload below</label><input data-k="img" placeholder="https://your-site.com/image.png" value="' + esc(String(s.img || '').startsWith('/art/u/') ? '' : s.img || '') + '"></div>'
|
+ '<div class="field"><label class="small muted">Image address (https), or upload below</label><input data-k="img" placeholder="https://your-site.com/image.png" value="' + esc(String(s.img || '').startsWith('/art/u/') ? '' : s.img || '') + '"></div>'
|
||||||
+ '<div class="row"><button class="btn small" data-a="save">Save</button><label class="btn sec small">Upload image<input type="file" accept="image/png,image/jpeg,image/gif" hidden></label>'
|
+ '<div class="row"><button class="btn small" data-a="save">Save</button><label class="btn sec small">Upload image<input type="file" accept="image/png,image/jpeg,image/gif" hidden></label>'
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap legal">
|
<main class="wrap legal">
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
|
|||||||
+4
-4
@@ -22,18 +22,18 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap">
|
<main class="wrap">
|
||||||
<section class="hero"><h1>My Spots</h1><p class="lead">Your spots, your images and links, and every payment the contract sent you.</p></section>
|
<section class="hero"><h1>My Spots</h1><p class="lead">Your spots, your images and links, and every payment the contract sent you.</p></section>
|
||||||
<div class="card" id="signin" hidden><h3>Sign in with your wallet</h3><p class="muted small">You sign a short message. It is free and cannot move funds or approve anything.</p><button class="btn" id="signBtn">Sign in</button></div>
|
<div class="card" id="signin" hidden><h3>Sign in with your wallet</h3><p class="muted small">You sign a short message. It is free and cannot move funds or approve anything.</p><button class="btn" id="signBtn">Sign in</button></div>
|
||||||
<div id="dash" hidden>
|
<div id="dash" hidden>
|
||||||
<div class="card"><div class="row" style="justify-content:space-between"><div><span class="muted small">Signed in as</span> <span class="mono" id="me"></span></div><button class="btn quiet small" id="outBtn">Sign out</button></div>
|
<div class="card"><div class="row" style="justify-content:space-between"><div><span class="muted small">Signed in as</span> <span class="mono" id="me"></span></div><span class="row" style="gap:8px"><button class="btn quiet small" id="outBtn">Sign out</button><button class="btn quiet small" id="outAllBtn" title="Ends your network sign-in on every network site">Sign out everywhere</button></span></div>
|
||||||
<div class="grid2" style="margin-top:12px" id="stats"></div></div><div id="zMySpots"></div>
|
<div class="grid2" style="margin-top:12px" id="stats"></div></div><div id="zMySpots"></div>
|
||||||
<div class="card"><h3>Your share link</h3><p class="muted small">People who join through this link have you as their sponsor. It is set once, on their first spot.</p>
|
<div class="card"><h3>Your share link</h3><p class="muted small">People who join through this link have you as their sponsor. It is set once, on their first spot.</p>
|
||||||
<div class="field"><input id="share" readonly></div><button class="btn sec small" id="copyBtn">Copy link</button></div>
|
<div class="field"><input id="share" readonly></div><button class="btn sec small" id="copyBtn">Copy link</button></div>
|
||||||
<div class="card"><h3>Spots</h3><p class="muted small">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.</p>
|
<div class="card"><h3>Spots</h3><p class="muted small">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.</p>
|
||||||
<div id="spots"></div></div>
|
<div id="spots"></div></div>
|
||||||
<div class="card"><h3>Default image and link</h3><p class="muted small">Used by any spot you have not set up.</p><div id="defaults"></div></div>
|
<div class="card"><h3>Default image and link</h3><p class="muted small">Used by any spot you have not set up.</p><div id="defaults"></div></div>
|
||||||
<div class="card"><h3>Payments to you</h3><div id="payouts"></div></div>
|
<div class="card"><h3>Payments to you</h3><div id="payouts"></div></div>
|
||||||
@@ -43,7 +43,7 @@
|
|||||||
</main>
|
</main>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261115nr"></script>
|
||||||
<script src="/assets/wallet.js?v=1"></script>
|
<script src="/assets/wallet.js?v=1"></script>
|
||||||
<script src="/assets/my.js?v=z1"></script>
|
<script src="/assets/my.js?v=z3"></script>
|
||||||
<script src="/assets/chat.js?v=1" defer></script>
|
<script src="/assets/chat.js?v=1" defer></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap legal">
|
<main class="wrap legal">
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
<link rel="stylesheet" href="/assets/kit.css?v=1">
|
<link rel="stylesheet" href="/assets/kit.css?v=1">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/site.css?v=2">
|
<link rel="stylesheet" href="/assets/site.css?v=2">
|
||||||
<link rel="stylesheet" href="/assets/line.css?v=8">
|
<link rel="stylesheet" href="/assets/line.css?v=9">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="wrap legal">
|
<main class="wrap legal">
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
{ "q": "Where does the $5 go?", "kb": "split", "must": ["30%", "55%", "\\$0.275", "10%", "5%"] },
|
{ "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 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": "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": "What is the momentum fund?", "kb": "fund", "must": ["4 hours", "7 days"] },
|
||||||
{ "q": "Why is Join locked?", "kb": "tour", "must": ["timer"] },
|
{ "q": "Why is Join locked?", "kb": "tour", "must": ["timer"] },
|
||||||
{ "q": "Can I buy a spot for someone else?", "kb": "buy-for", "must": ["wallet address"] },
|
{ "q": "Can I buy a spot for someone else?", "kb": "buy-for", "must": ["wallet address"] },
|
||||||
|
|||||||
+166
-2
@@ -17,6 +17,42 @@ const { ethers } = require('ethers');
|
|||||||
|
|
||||||
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
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('<!doctype html><title>ok</title>');
|
||||||
|
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 ART = path.resolve(APP, '..', 'contracts', 'out');
|
||||||
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', 'anvil.exe');
|
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';
|
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
@@ -27,7 +63,7 @@ let pass = 0, fail = 0; const procs = [];
|
|||||||
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 300) : '')); } };
|
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 300) : '')); } };
|
||||||
// stand-in network hub (POST /v1/resolve, signed as bannerline) and stand-in InstantAdPay member lookup (the fallback when the
|
// stand-in network hub (POST /v1/resolve, signed as bannerline) and stand-in InstantAdPay member lookup (the fallback when the
|
||||||
// hub is unreachable). HUB.people: {id, username, wallet, sponsorId}; HUB.down makes every hub call fail with 503.
|
// hub is unreachable). HUB.people: {id, username, wallet, sponsorId}; HUB.down makes every hub call fail with 503.
|
||||||
const HUB = { people: [], down: false, calls: 0, badSig: 0 }; const HUB_PORT = APP_PORT + 7, HUB_SECRET = 'b'.repeat(40);
|
const HUB = { people: [], down: false, calls: 0, badSig: 0, got: [] }; const HUB_PORT = APP_PORT + 7, HUB_SECRET = 'b'.repeat(40);
|
||||||
const IAPNET = new Map(); const IAP_PORT = APP_PORT + 8;
|
const IAPNET = new Map(); const IAP_PORT = APP_PORT + 8;
|
||||||
const TG = []; const TG_PORT = APP_PORT + 9; // stand-in Telegram Bot API (trust pack 2026-11-14): never the real group
|
const TG = []; const TG_PORT = APP_PORT + 9; // stand-in Telegram Bot API (trust pack 2026-11-14): never the real group
|
||||||
const hubView = p => p ? { id: p.id, username: p.username, wallet: p.wallet, sponsor: (x => x ? { id: x.id, username: x.username } : null)(HUB.people.find(y => y.id === p.sponsorId)), blocked: false, locked: false } : null;
|
const hubView = p => p ? { id: p.id, username: p.username, wallet: p.wallet, sponsor: (x => x ? { id: x.id, username: x.username } : null)(HUB.people.find(y => y.id === p.sponsorId)), blocked: false, locked: false } : null;
|
||||||
@@ -45,6 +81,7 @@ function startStandIns() {
|
|||||||
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"superseded"}'); }
|
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"superseded"}'); }
|
||||||
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
|
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
|
||||||
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'bannerline') { HUB.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'bannerline') { HUB.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
||||||
|
if (q.url === '/v1/sso/signout') { HUB.got.push({ route: q.url, body: JSON.parse(b || '{}') }); return r.end('{"ok":true,"ended":1}'); } // Sign out everywhere (2026-11-16)
|
||||||
if (q.url !== '/v1/resolve') { r.statusCode = 404; return r.end('{"error":"not_found"}'); }
|
if (q.url !== '/v1/resolve') { r.statusCode = 404; return r.end('{"error":"not_found"}'); }
|
||||||
const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase();
|
const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase();
|
||||||
const p = j.id ? HUB.people.find(x => x.id === j.id) : j.wallet ? HUB.people.find(x => x.wallet === String(j.wallet).toLowerCase()) : ref ? HUB.people.find(x => x.username === ref || x.wallet === ref) : null;
|
const p = j.id ? HUB.people.find(x => x.id === j.id) : j.wallet ? HUB.people.find(x => x.wallet === String(j.wallet).toLowerCase()) : ref ? HUB.people.find(x => x.username === ref || x.wallet === ref) : null;
|
||||||
@@ -116,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,
|
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',
|
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',
|
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();
|
startStandIns();
|
||||||
const hid = n => 'h_' + String(n).padStart(16, '0');
|
const hid = n => 'h_' + String(n).padStart(16, '0');
|
||||||
const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here
|
const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here
|
||||||
@@ -357,6 +395,132 @@ async function main() {
|
|||||||
const ours = errors.filter(e => !/example\.(com|net|org)/.test(e)); // gate frames load example.* sites; their own 404s (favicon) are not ours
|
const ours = errors.filter(e => !/example\.(com|net|org)/.test(e)); // gate frames load example.* sites; their own 404s (favicon) are not ours
|
||||||
ok(ours.length === 0, 'no console errors on our pages', ours);
|
ok(ours.length === 0, 'no console errors on our pages', ours);
|
||||||
}
|
}
|
||||||
|
console.log('9. network hub events (sign out everywhere, block, erase end sessions here)');
|
||||||
|
{ const crypto = require('node:crypto'); const admin = (p, body) => client().json(p, body, { 'x-admin-token': ADMIN }); let hseq = 900000; let hn = 700;
|
||||||
|
const signAs = async (w, name) => { const c = client('Mozilla/5.0 hook ' + (hn++)); const a = w.address.toLowerCase(); const xf = { 'X-Forwarded-For': '198.51.100.' + (hn % 250) };
|
||||||
|
if (name) { c.hubId = hid(hn); HUB.people.push({ id: c.hubId, username: name, wallet: a, sponsorId: null }); }
|
||||||
|
const ch = await c.json('/api/auth/challenge', { address: w.address }, xf);
|
||||||
|
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) }, xf);
|
||||||
|
c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['bl.sid']; return c; };
|
||||||
|
const walletMember = o => signAs((o && o.wallet) || ethers.Wallet.createRandom(), o && o.hub && o.hub.username); const signedIn = async c => (await c.json('/api/me')).signedIn === true;
|
||||||
|
const hook = async (events, o = {}) => { const raw = JSON.stringify({ events }); const ts = String(o.ts || Date.now());
|
||||||
|
const sig = o.sig || crypto.createHmac('sha256', o.secret || HUB_SECRET).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(BASE + '/api/hub/events', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, body: raw }); return r.status; };
|
||||||
|
const ev = (type, personId, data, at) => ({ seq: ++hseq, at: at || Date.now(), type, personId, data: data || {} });
|
||||||
|
const H1 = await walletMember({ hub: { username: 'hookone' } }); const H1b = await walletMember({ wallet: H1.wallet }); const H2 = await walletMember({ hub: { username: 'hooktwo' } });
|
||||||
|
const H3 = await walletMember({ hub: { username: 'hookthree' } }); const H4 = await walletMember({ hub: { username: 'hookfour' } });
|
||||||
|
ok(H1.ok && H1b.ok && H2.ok && H3.ok && H4.ok && await signedIn(H1) && await signedIn(H1b), 'setup: hub members signed in here (one of them in two browsers)');
|
||||||
|
ok(await hook([ev('member.signedout', H1.hubId)], { secret: 'x'.repeat(40) }) === 401 && await hook([ev('member.signedout', H1.hubId)], { ts: Date.now() - 600000 }) === 401, 'a hook signed with another key, or 10 minutes old, is refused (401)');
|
||||||
|
ok(await signedIn(H1), 'a refused hook ends nothing');
|
||||||
|
const so = ev('member.signedout', H1.hubId);
|
||||||
|
ok(await hook([so]) === 200 && !(await signedIn(H1)) && !(await signedIn(H1b)) && await signedIn(H2), 'member.signedout: every session of that wallet ends (both browsers), nobody else\'s');
|
||||||
|
const H1c = await walletMember({ wallet: H1.wallet });
|
||||||
|
ok(await hook([so]) === 200 && await signedIn(H1c), 'the same event sent twice: applied once, a fresh sign-in stays');
|
||||||
|
ok(await hook([ev('member.signedout', H1.hubId, {}, Date.now() - 60000)]) === 200 && await signedIn(H1c), 'an event older than a session never ends it (only sessions made before the event)');
|
||||||
|
ok(await hook([ev('member.blocked', H2.hubId)]) === 200 && !(await signedIn(H2)) && await signedIn(H3), 'member.blocked: that member is signed out here');
|
||||||
|
const wh = crypto.createHash('sha256').update(H3.address).digest('hex'); HUB.people = HUB.people.filter(x => x.id !== H3.hubId);
|
||||||
|
ok(await hook([ev('member.erased', H3.hubId, { emailHash: 'a'.repeat(64), walletHashes: [wh] })]) === 200 && !(await signedIn(H3)) && await signedIn(H4), 'member.erased: found by the wallet hash in the event (the hub no longer knows them), signed out');
|
||||||
|
ok(await hook([ev('member.joined', H4.hubId), ev('member.signedout', 'h_' + 'f'.repeat(16))]) === 200 && await signedIn(H4), 'other events and unknown people are ignored');
|
||||||
|
HUB.down = true; const late = ev('member.signedout', H4.hubId);
|
||||||
|
ok(await hook([late]) === 503 && await signedIn(H4), 'the hub lookup failing answers 503 (the hub sends it again), nothing ended');
|
||||||
|
HUB.down = false; ok(await hook([late]) === 200 && !(await signedIn(H4)), 'resent once the hub answers: signed out');
|
||||||
|
const E1 = await walletMember({ hub: { username: 'hookfive' } }); const E2 = await walletMember({ wallet: E1.wallet }); const g0 = HUB.got.length;
|
||||||
|
const eo = await E1.json('/api/auth/logout-everywhere', {});
|
||||||
|
const call = HUB.got.slice(g0).find(x => x.route === '/v1/sso/signout');
|
||||||
|
ok(eo.ok && eo.everywhere === true && !(await signedIn(E1)) && !(await signedIn(E2)) && call && call.body.wallet === E1.address, 'Sign out everywhere: the hub is told (signed, by wallet) and every session of that wallet here ends', { eo, call });
|
||||||
|
ok(/id="outAllBtn"[^>]*>Sign out everywhere</.test(await (await client().req('/my')).text()), '/my has a Sign out everywhere button next to Sign out');
|
||||||
|
const st2 = await admin('/api/admin/status');
|
||||||
|
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/<spot> 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/<spot> 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);
|
console.log('\n' + pass + ' passed, ' + fail + ' failed. Output in ' + OUT);
|
||||||
cleanup(); process.exit(fail ? 1 : 0);
|
cleanup(); process.exit(fail ? 1 : 0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// Link + image checks for My Spots. https only, a real public hostname, no tricks; uploads must be a real
|
// 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.
|
// PNG/JPG/GIF at 468x60 (or 936x120 retina) and at most 150 KB.
|
||||||
const net = require('net');
|
const net = require('net');
|
||||||
|
const dns = require('dns');
|
||||||
|
const https = require('https');
|
||||||
|
|
||||||
const MAX_UPLOAD = 150 * 1024;
|
const MAX_UPLOAD = 150 * 1024;
|
||||||
const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i;
|
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 };
|
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 };
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ function limited(req, name, max, windowMs) {
|
|||||||
// verify membership"; hubpeople.js, cached 5 minutes); InstantAdPay's GET /api/network/member ?u= / ?a= only when the hub is
|
// verify membership"; hubpeople.js, cached 5 minutes); InstantAdPay's GET /api/network/member ?u= / ?a= only when the hub is
|
||||||
// unreachable (cached an hour, misses too; a failed call is not cached). A person the hub does not know is unknown here too.
|
// unreachable (cached an hour, misses too; a failed call is not cached). A person the hub does not know is unknown here too.
|
||||||
const hubpeople = require('./hubpeople');
|
const hubpeople = require('./hubpeople');
|
||||||
|
const hubevents = require('./hubevents'); // network hub hook (2026-11-16): sign-out-everywhere, block and erase end sessions here
|
||||||
const netCache = new Map();
|
const netCache = new Map();
|
||||||
const fromHub = p => { const a = hubpeople.wallet(p); return a ? { address: a, username: p.username ? String(p.username) : null, hubId: p.id || null, via: 'hub' } : null; };
|
const fromHub = p => { const a = hubpeople.wallet(p); return a ? { address: a, username: p.username ? String(p.username) : null, hubId: p.id || null, via: 'hub' } : null; };
|
||||||
async function netMember(q) {
|
async function netMember(q) {
|
||||||
@@ -221,10 +222,12 @@ async function visitStep(role, ref, img, link, title) {
|
|||||||
async function makeGate(req) {
|
async function makeGate(req) {
|
||||||
const vk = visitorKey(req); const steps = [];
|
const vk = visitorKey(req); const steps = [];
|
||||||
const sp = sponsorOf(req); const sSpot = sp && board.newestOf(sp);
|
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 });
|
steps.push({ type: 'board', tiles: board.pick(), seconds: C.gateBoardSeconds });
|
||||||
const nw = board.newest(3, sSpot ? [sSpot.id] : []);
|
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;
|
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; }
|
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');
|
const gid = crypto.randomBytes(12).toString('hex');
|
||||||
@@ -243,7 +246,44 @@ function spotView(s) {
|
|||||||
const left = Math.max(0, C.spotDays - Math.floor((now - s.boughtAt) / 86400000));
|
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,
|
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,
|
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) {
|
async function myData(addr) {
|
||||||
const a = addr.toLowerCase();
|
const a = addr.toLowerCase();
|
||||||
@@ -267,6 +307,8 @@ networksso.init({ self: 'bannerline', peer: 'iap', peerBase: () => C.iapBase, fr
|
|||||||
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||||
signIn: async (email, req, v) => { if (v.name) netCache.set('a:' + v.wallet, { at: Date.now(), m: { address: v.wallet, username: v.name } }); return cookie('bl.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); },
|
signIn: async (email, req, v) => { if (v.name) netCache.set('a:' + v.wallet, { at: Date.now(), m: { address: v.wallet, username: v.name } }); return cookie('bl.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); },
|
||||||
landing: to => to, signinPath: to => to });
|
landing: to => to, signinPath: to => to });
|
||||||
|
// the hub's member.signedout / member.blocked / member.erased: that person's sessions here end (by any of their wallets)
|
||||||
|
hubevents.init({ dataDir: C.dataDir, site: 'bannerline', end: who => store.endSessions(x => who.match(x), who.before) });
|
||||||
|
|
||||||
const server = http.createServer(async (req, res) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
const u = new URL(req.url, 'http://x'); const p = u.pathname;
|
const u = new URL(req.url, 'http://x'); const p = u.pathname;
|
||||||
@@ -294,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 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',
|
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]) {
|
if (PAGES[p]) {
|
||||||
const set = [];
|
const set = [];
|
||||||
if (setVid) set.push(setVid);
|
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)); }
|
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 } : {};
|
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);
|
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(); }
|
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
|
||||||
@@ -452,6 +494,17 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const s = session(req); if (s) store.dropSession(s.token);
|
const s = session(req); if (s) store.dropSession(s.token);
|
||||||
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('bl.sid', '', 0, true), networksso.offCookie()] }); // signed out stays signed out here for 12 hours
|
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('bl.sid', '', 0, true), networksso.offCookie()] }); // signed out stays signed out here for 12 hours
|
||||||
}
|
}
|
||||||
|
// "Sign out everywhere" (2026-11-16): the hub ends every network sign-in of this member and tells every hooked site; every
|
||||||
|
// session of this wallet here ends now. Same-origin POST only (SameSite=Lax session cookie).
|
||||||
|
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
|
||||||
|
const s = session(req); let hub = { ok: false };
|
||||||
|
if (s) { hub = await networksso.signOutEverywhere(s); store.endSessions(x => x.address === s.address, Date.now() + 1000); }
|
||||||
|
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [cookie('bl.sid', '', 0, true), networksso.offCookie()] });
|
||||||
|
}
|
||||||
|
if (p === '/api/hub/events' && req.method === 'POST') {
|
||||||
|
let raw = ''; try { raw = (await readRaw(req, 256 * 1024)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||||
|
const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body);
|
||||||
|
}
|
||||||
if (p === '/api/me' && req.method === 'GET') {
|
if (p === '/api/me' && req.method === 'GET') {
|
||||||
// username / refName (Marty 2026-11-15): the footer's network links carry a referral username, the member's own network
|
// username / refName (Marty 2026-11-15): the footer's network links carry a referral username, the member's own network
|
||||||
// username when signed in, else the sponsor's (usernames only, never the wallet)
|
// username when signed in, else the sponsor's (usernames only, never the wallet)
|
||||||
@@ -468,32 +521,40 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const me = s.address;
|
const me = s.address;
|
||||||
if (p === '/api/my' && req.method === 'GET') return json(res, 200, await myData(me));
|
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' && 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);
|
let m = /^\/api\/my\/spot\/(\d+)$/.exec(p);
|
||||||
if (m && req.method === 'POST') {
|
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 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 (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT });
|
||||||
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 (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
|
||||||
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; } }
|
const b = await readBody(req); const ck = await checkEdit(me, b, 'Target link'); if (ck.error) return json(res, 400, ck);
|
||||||
return json(res, 200, { ok: true, meta: store.setSpotMeta(sp.id, out) });
|
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') {
|
if (p === '/api/my/default' && req.method === 'POST') {
|
||||||
const b = await readBody(req); const out = {};
|
if (limited(req, 'edit', 120, 3600000)) return json(res, 429, { error: 'Too many changes this hour. Try again in a while.' });
|
||||||
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; } }
|
const b = await readBody(req); const ck = await checkEdit(me, b, 'Default link'); if (ck.error) return json(res, 400, ck);
|
||||||
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; } }
|
const before = Object.assign({}, store.memberDefault(me) || {});
|
||||||
return json(res, 200, { ok: true, defaults: store.setMemberDefault(me, out) });
|
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 (p === '/api/my/upload' && req.method === 'POST') {
|
||||||
if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' });
|
if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' });
|
||||||
const target = u.searchParams.get('for') || '';
|
const target = u.searchParams.get('for') || '';
|
||||||
let sp = null;
|
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.' }); }
|
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 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;
|
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);
|
fs.writeFileSync(path.join(C.dataDir, 'art', name), buf);
|
||||||
const img = '/art/u/' + name;
|
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 });
|
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, 200, { ok: true, img });
|
||||||
}
|
}
|
||||||
return json(res, 404, { error: 'Not found' });
|
return json(res, 404, { error: 'Not found' });
|
||||||
@@ -537,7 +598,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
// -- admin (ADMIN_TOKEN header): keeper preview + index status. No key material is ever returned.
|
// -- admin (ADMIN_TOKEN header): keeper preview + index status. No key material is ever returned.
|
||||||
if (p === '/api/admin/status' && req.method === 'GET') {
|
if (p === '/api/admin/status' && req.method === 'GET') {
|
||||||
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
|
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
|
||||||
return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), hubLookup: hubpeople.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() });
|
return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() });
|
||||||
}
|
}
|
||||||
|
|
||||||
// -- admin: the network hub's member lookup (Marty 2026-11-14, read-only). GET ?q=<wallet> | <spot id>. No email lives here.
|
// -- admin: the network hub's member lookup (Marty 2026-11-14, read-only). GET ?q=<wallet> | <spot id>. No email lives here.
|
||||||
@@ -555,6 +616,51 @@ const server = http.createServer(async (req, res) => {
|
|||||||
gifted: chain.fundBuys().filter(f => f.giftee === a), contract: C.contract, explorer: C.explorer }));
|
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=#<id> | <id> | <wallet> | <username>
|
||||||
|
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' });
|
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
|
||||||
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
|
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
|
||||||
return res.end('<!doctype html><title>Not found</title><body style="background:#09080f;color:#f3f1fa;font-family:sans-serif;text-align:center;padding:40px 16px"><p>Not found. <a style="color:#c6f432" href="/">Downline Banners home</a></p>'
|
return res.end('<!doctype html><title>Not found</title><body style="background:#09080f;color:#f3f1fa;font-family:sans-serif;text-align:center;padding:40px 16px"><p>Not found. <a style="color:#c6f432" href="/">Downline Banners home</a></p>'
|
||||||
@@ -589,7 +695,7 @@ function weekLine() {
|
|||||||
hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() });
|
hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() });
|
||||||
refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy());
|
refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy());
|
||||||
keeper.init();
|
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
|
// members' LinkSpin Banner Spins for empty board slots: one active 468x60 spin per member, refreshed every 10 minutes
|
||||||
const refreshSpins = async () => {
|
const refreshSpins = async () => {
|
||||||
const out = [];
|
const out = [];
|
||||||
|
|||||||
@@ -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 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]; }
|
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) ----
|
// ---- 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.
|
// 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 seenView = new Map(), seenClick = new Map();
|
||||||
const HOUR = 3600000;
|
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 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) {
|
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);
|
const k = visitorKey + ':' + spotId; const t = seenView.get(k);
|
||||||
if (t && Date.now() - t < HOUR) return false;
|
if (t && Date.now() - t < HOUR) return false;
|
||||||
seenView.set(k, Date.now()); prune(seenView);
|
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 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) {
|
function addClick(spotId, visitorKey, source) {
|
||||||
|
if (spotDown(spotId)) return false;
|
||||||
const k = visitorKey + ':' + spotId + ':' + source; const t = seenClick.get(k);
|
const k = visitorKey + ':' + spotId + ':' + source; const t = seenClick.get(k);
|
||||||
if (t && Date.now() - t < HOUR) return false;
|
if (t && Date.now() - t < HOUR) return false;
|
||||||
seenClick.set(k, Date.now()); prune(seenClick);
|
seenClick.set(k, Date.now()); prune(seenClick);
|
||||||
@@ -59,6 +83,8 @@ 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 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 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(); }
|
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 touch(address) { S.seen[String(address).toLowerCase()] = Date.now(); save(); }
|
||||||
function lastSeen(address) { return S.seen[String(address).toLowerCase()] || 0; }
|
function lastSeen(address) { return S.seen[String(address).toLowerCase()] || 0; }
|
||||||
|
|
||||||
@@ -67,4 +93,5 @@ function keeperLog(entry) { S.keeper.log.push(Object.assign({ at: Date.now() },
|
|||||||
function keeperEntries() { return S.keeper.log.slice(); }
|
function keeperEntries() { return S.keeper.log.slice(); }
|
||||||
|
|
||||||
module.exports = { load, flush, spotMeta, setSpotMeta, memberDefault, setMemberDefault, addView, views, addClick, clicks, daily,
|
module.exports = { load, flush, spotMeta, setSpotMeta, memberDefault, setMemberDefault, addView, views, addClick, clicks, daily,
|
||||||
mintSession, session, dropSession, touch, lastSeen, keeperLog, keeperEntries, SESSION_TTL };
|
logSpotEdit, logDefaultEdit, spotEdits, defaultEdits, spotDown, setSpotDown, clearSpotDown, spotDowns, downIds, adminLog, adminLogs,
|
||||||
|
mintSession, session, dropSession, endSessions, touch, lastSeen, keeperLog, keeperEntries, SESSION_TTL };
|
||||||
|
|||||||
Reference in New Issue
Block a user