diff --git a/ads.js b/ads.js index 4eb62b0..9dd2d3c 100644 Binary files a/ads.js and b/ads.js differ diff --git a/chatbot.js b/chatbot.js index 3b99dd6..18741ea 100644 --- a/chatbot.js +++ b/chatbot.js @@ -31,6 +31,8 @@ const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)| const CANNED = [ { re: SUPPORT_RE, handoff: true, a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' }, + { re: /\b(fix|change|edit|update|correct|replace|wrong|broken|typo)\b.{0,40}\b(link|url|image|banner|picture|headline|text|name)\b.{0,30}\b(ad|ads|campaign|campaigns|banner)\b|\b(edit|fix|change|update) (my |an |the |this )?(ad|ads|campaign|banner|login ad|text ad)\b/i, + a: 'Open Ads in your Control Room (' + SITE_URL + '/ads) and press Edit on the ad. You can change where the click goes, the banner image (upload a new one or paste a link), the headline and line of a text ad, and the ad name. A login ad shows your page itself, so its link is the whole ad. The first edit of every ad is free, your one correction; each edit after that costs a small credit fee (100 credits at the moment, shown before you save), taken from earned credits first. The type, size, budget, countries, schedule and audience stay as they are; for those, start a new ad. A new link is checked the same way as a new ad, so it has to load and, for banner and text ads, allow framing.' }, { re: /(log ?-?in|sign ?-?in) (ad|ads|spot|sponsor|slot|slots)|(ad|sponsor) (on|at) (the )?(log ?-?in|sign ?-?in)/i, a: 'A login ad is a slot: 1,000 purchased credits buys 30 days of your page, full screen, to every member right after they sign in, with unlimited sign-in impressions and nothing charged per day. At most 3 member slots run at once because they share the same sign-ins, first come first served; when all 3 are taken the Ads screen says so and a place opens when a running slot ends its 30 days. Login ads spend purchased credits only, so earned credits go to banner and text ads instead. Buy one from Ads, New ad, Login ad.' }, { re: /(instant ?ad ?pay|[^a-z]iap[^a-z]|differen|same as|another (site|program|property)|why (two|another)|sister (site|property)|which (one|site) (should|do))/i, @@ -98,7 +100,7 @@ FACTS: - PACKAGES (priced in dollars, settled in POL at the live rate, 1 credit = 1 cent of ad delivery): $10 door = 1,000 credits, for trying the ads, does NOT count toward qualification; $25 Starter = 2,500; $50 Builder = 5,000; $100 Growth = 10,000; $250 Leader = 25,000; $500 Network = 50,000. Any package of $25 or more makes the buyer a qualifying buyer for their sponsor. - THE SPLIT, same transaction on Polygon, fixed in the contract: 50 percent direct sponsor, 20 percent level 2, 10 percent level 3, 10 percent + 10 percent to the two admin wallets. Level 1 pays from a referral's first qualifying purchase once the sponsor's payouts are on. Level 2 opens after two of the member's people buy a qualifying ($25 or larger) package, level 3 after five. An unfilled tier passes up the line to the next qualified member, then to the platform. Nothing is held, there are no withdrawals, no pending balances. Contract ${CONTRACT} on Polygon, verified on Polygonscan; plain-language review at ${SITE_URL}/contract; live ledger at ${SITE_URL}/ledger with a verify link on every row. - CREDITS VS POL: every member, free ones included, earns CREDITS (zones, the daily ad set with a claim streak, watch-to-earn videos, verified visits, a daily sign-in bonus). Credits buy the member's own banner and text ads (a login-ad slot takes purchased credits only) and NEVER cash out or convert to crypto. POL only reaches a wallet through the contract split when a package sells in the member's line. Never promise or estimate income. -- AD FORMATS members buy with credits: banner ads (standard sizes), text ads, full-screen login ads (a flat slot: 1,000 PURCHASED credits for 30 days of unlimited sign-in impressions, never charged per day; at most 3 member slots live at once, first come first served, a 4th is refused until one ends; house login ads only show when no member slot is running; earned credits never fund login ads), plus solo ads to member inboxes, watch-to-earn video, verified visits. Banner and text ads also run on member zones and the partner network. +- AD FORMATS members buy with credits: banner ads (standard sizes), text ads, full-screen login ads (a flat slot: 1,000 PURCHASED credits for 30 days of unlimited sign-in impressions, never charged per day; at most 3 member slots live at once, first come first served, a 4th is refused until one ends; house login ads only show when no member slot is running; earned credits never fund login ads); EDITING AN AD (2026-10-18): the Edit button on each ad on the Ads screen changes the click link, the banner image (upload or https link), a text ad's headline and line, and the ad name; type, size, budget, countries, schedule and audience cannot change (start a new ad); the first edit of every ad is free, each later edit costs the campaignEditFee, 100 credits by default, earned credits first, then purchased; a new link and a new banner image get the same checks as a new ad, plus solo ads to member inboxes, watch-to-earn video, verified visits. Banner and text ads also run on member zones and the partner network. - ACCOUNT: join at ${SITE_URL}/join with email only, a six-digit code, no password. Wallet linking happens inside the Control Room (Credits screen): one signature to link, then payouts switch on by activating (one transaction, gas only) or by buying any package. SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first) and any WalletConnect wallet work; Trust Wallet blocks a buy that spends most of its POL. MoonPay card on-ramp from the Credits screen puts POL on Polygon into the member's own wallet. - SPONSOR: the invite link opened most recently sets the sponsor (30-day cookie), shown on the join page, locked when the account is created; the contract binds the buyer to that sponsor at the first purchase. CARRY-OVER: Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their InstantAdPay sponsor from the network registry automatically when no invite link was used. Wrong sponsor before the first purchase: the admin can move the account. Members should switch on payouts before their people buy. - CONTROL ROOM screens: Links, Pages, Zones (with Audiences), Ads, Credits, Reports, Team (three levels, who has payouts on, who bought, qualifying-buyer counts), Wallet (what was paid to this wallet, payout history). More at ${SITE_URL}/tools: Promo tools, Training, Pipeline (a follow-up board for prospects and directs), My line (including the holding tank: members who joined with no sponsor wait there and can be adopted by a member with payouts on and their own qualifying package), Profile. diff --git a/content.js b/content.js index 8f36fa8..df2e6fd 100644 --- a/content.js +++ b/content.js @@ -119,9 +119,11 @@ async function collect(fresh) { const reps = open[c.id] || []; const flags = reps.length ? [{ k: 'reported', t: reps.length + ' open report' + (reps.length > 1 ? 's' : '') + ': ' + Array.from(new Set(reps.map(x => x.reason))).join(', ') }] : []; const body = strip(c.body).slice(0, 300); add({ type: 'ad', id: String(c.id), ownerEmail: c.owner, title: c.name, created: c.created, status: c.scheduled ? 'scheduled' : c.status, live: c.status === 'active' && !c.scheduled, url: c.targetUrl, open: c.targetUrl, - detail: { adType: c.type, imageUrl: c.imageUrl, title: c.title, body, width: c.width, height: c.height, budget: c.budget, spent: c.spent, starts: c.starts, expires: c.expires, geo: c.geo, dailyCap: c.dailyCap, audience: c.audience }, + detail: { adType: c.type, imageUrl: c.imageUrl, title: c.title, body, width: c.width, height: c.height, budget: c.budget, spent: c.spent, starts: c.starts, expires: c.expires, geo: c.geo, dailyCap: c.dailyCap, audience: c.audience, name: c.name, + edits: c.edits || 0, editLog: (c.editLog || []).slice(-5).map(e => ({ ts: e.ts, by: e.by, fields: e.fields, from: e.from, to: e.to, fee: e.fee || 0 })) }, // member edits (first free) + the last few changes counts: { imps: c.imps, impsNas: c.impsNas, clicks: c.clicks }, hosts: [hostOf(c.targetUrl)].concat(urlsIn(c.body).map(hostOf)), flags, - actions: c.status === 'active' ? [{ label: 'Pause ad', path: '/api/admin/campaigns/' + c.id + '/pause', body: {}, warn: 'Pause campaign #' + c.id + '? It stops serving until resumed.' }] : c.status === 'paused' ? [{ label: 'Resume ad', path: '/api/admin/campaigns/' + c.id + '/resume', body: {} }] : [], + actions: (c.status === 'active' ? [{ label: 'Pause ad', path: '/api/admin/campaigns/' + c.id + '/pause', body: {}, warn: 'Pause campaign #' + c.id + '? It stops serving until resumed.' }] : c.status === 'paused' ? [{ label: 'Resume ad', path: '/api/admin/campaigns/' + c.id + '/resume', body: {} }] : []) + .concat(c.status !== 'done' ? [{ label: 'Edit ad', edit: true, path: '/api/admin/campaigns/' + c.id + '/edit' }] : []), // free for the admin, the member's free edit untouched search: [c.type, c.targetUrl, c.imageUrl, c.title, body] }); } diff --git a/db.js b/db.js index 8322471..fdc01fc 100644 --- a/db.js +++ b/db.js @@ -135,6 +135,8 @@ async function bootstrap() { ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0'); await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL"); + await alterSafe('ALTER TABLE campaigns ADD COLUMN edits INT NOT NULL DEFAULT 0'); // member edits so far (the first is free), 2026-10-18 + await alterSafe('ALTER TABLE campaigns ADD COLUMN edit_log MEDIUMTEXT NULL'); // JSON [{ts, by, fields, from, to, fee, paidFrom}], last 50 // linked positions: extra wallets owned by one email account (Qualified Start). // Each is its own on-chain member sponsored by the account's main member. await q(`CREATE TABLE IF NOT EXISTS positions ( diff --git a/nas.js b/nas.js index fc31bdd..5efc772 100644 --- a/nas.js +++ b/nas.js @@ -115,6 +115,14 @@ async function setClickUrl(nasAdId, campaignId) { await q('UPDATE sponsorads SET WebsiteURL=? WHERE ID=?', [SITE_URL + '/api/ads/click/' + Number(campaignId), Number(nasAdId)]); return { ok: true }; } +// an edited campaign's creative (2026-10-18): headline, text line and banner image on the live NAS row. +// The click URL never changes (it is our /api/ads/click/ redirect), so a new link needs no NAS write. +async function updateCreative(nasAdId, c) { + if (!enabled()) return { skipped: 'flag-off' }; + if (c.type === 'banner') await q('UPDATE sponsorads SET BannerURL=?, Subject=? WHERE ID=?', [c.imageUrl || null, c.title || null, Number(nasAdId)]); + else if (c.type === 'text') await q('UPDATE sponsorads SET Subject=?, Body=? WHERE ID=?', [c.title || null, c.body || null, Number(nasAdId)]); + return { ok: true }; +} async function topUp(nasAdId, addImpressions, days) { if (!enabled()) return { skipped: 'flag-off' }; await q(`UPDATE sponsorads SET assigned=assigned+?, remaining=remaining+?, approved=1, @@ -123,4 +131,4 @@ async function topUp(nasAdId, addImpressions, days) { return { ok: true }; } -module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind }; +module.exports = { setClickUrl, updateCreative, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind }; diff --git a/public/admin.html b/public/admin.html index f8d1c1e..7042b57 100644 --- a/public/admin.html +++ b/public/admin.html @@ -472,6 +472,6 @@ - + diff --git a/public/ads.html b/public/ads.html index 50ffd3b..96a798a 100644 --- a/public/ads.html +++ b/public/ads.html @@ -70,6 +70,6 @@ - + diff --git a/public/assets/admin.js b/public/assets/admin.js index 5c9f5fe..271ce34 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -545,6 +545,7 @@ if (d.imageUrl) line(ctImg(d.imageUrl, true) + (d.width ? ' ' + d.width + '×' + d.height + '' : '')); if (d.title || d.body) line((d.title ? '' + esc(ctCut(d.title, 100)) + ' ' : '') + esc(ctCut(d.body, 200))); line('Budget ' + ctN(d.budget) + ' · spent ' + ctN(d.spent) + ' · left ' + ctN(Math.max(0, (d.budget || 0) - (d.spent || 0))) + (d.dailyCap ? ' · cap ' + ctN(d.dailyCap) + '/day' : '') + (d.geo ? ' · tiers ' + esc(d.geo) : '') + (d.starts ? ' · starts ' + ctWhen(d.starts) : '') + (d.expires ? ' · ends ' + ctWhen(d.expires) : '')); + if (d.edits || (d.editLog && d.editLog.length)) line('Edited by the member ' + ctN(d.edits) + ' time' + (d.edits === 1 ? '' : 's') + (d.edits ? ' (first free)' : '') + (d.editLog || []).slice().reverse().map(e => '
' + ctWhen(e.ts) + ' · ' + esc(e.by === 'admin' ? 'admin' : 'member') + (e.fee ? ' · ' + ctN(e.fee) + ' cr' : ' · free') + ' · ' + (e.fields || []).map(k => esc(k) + ': ' + esc(ctCut((e.from || {})[k], 50)) + ' → ' + esc(ctCut((e.to || {})[k], 50))).join('; ') + '
').join('')); } else if (r.type === 'postback') { line('' + esc(ctCut(d.postbackUrl, 110)) + ''); line(esc(d.method) + ' · ' + esc((d.events || []).join(', ')) + (d.lastStatus ? ' · last ' + esc(d.lastStatus) + ' ' + ctWhen(d.lastAt) : '')); @@ -623,11 +624,36 @@ const m = e.target.closest('[data-ctmember]'); if (m) { e.preventDefault(); setPane('members'); return openMember(m.dataset.ctmember); } const b = e.target.closest('[data-ctact]'); if (!b || b.disabled) return; const [i, j] = b.dataset.ctact.split(':').map(Number); const r = CT.data && CT.data.items[i]; const a = r && r.actions[j]; if (!a) return; + if (a.edit) return ctEditAd(r, a); if (a.warn && !await IAP.confirmBox(a.warn, { title: a.label, ok: a.label, cancel: 'Cancel' })) return; b.disabled = true; try { await api(a.path, a.body || {}, 'POST'); IAP.status(a.label + ': done.', 'ok'); await loadContent(true); } catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; } }); + // admin edit of any member ad (2026-10-18): the same checks as a member edit, free, and the member keeps their free one + function ctEditAd(r, a) { + const d = r.detail || {}; const t = d.adType; + const F = [['name', 'Name', d.name || r.title, 60], ['targetUrl', 'Where the click goes', r.url, 0]]; + if (t === 'banner') F.push(['imageUrl', 'Image URL (' + d.width + 'x' + d.height + ')', d.imageUrl, 0]); + if (t === 'text') F.push(['title', 'Headline (60)', d.title, 60], ['body', 'One line (140)', d.body, 140]); + const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; + back.innerHTML = ''; + document.body.appendChild(back); + const im = back.querySelector('[data-k="imageUrl"]'); const paint = () => { const p = back.querySelector('#aePrev'); if (p) p.innerHTML = ctSafe(im.value.trim()) ? '' : ''; }; + if (im) { im.addEventListener('input', paint); paint(); } + back.addEventListener('click', async e => { + const x = e.target.closest('[data-x]'); if (e.target === back || (x && x.dataset.x === 'no')) return back.remove(); if (!x) return; + const body = {}; F.forEach(f => { const v = back.querySelector('[data-k="' + f[0] + '"]').value.trim(); if (v !== String(f[2] || '').trim()) body[f[0]] = v; }); + if (!Object.keys(body).length) return IAP.status('Nothing changed.', 'bad'); + x.disabled = true; + try { const res = await api(a.path, body, 'POST'); back.remove(); IAP.status('Ad #' + r.id + ' saved' + (res.network === 'retrying' ? ' (the network copy retries on the next pass)' : '') + '.', 'ok'); await loadContent(true); } + catch (err) { IAP.status(err.message, 'bad'); x.disabled = false; } + }); + } + // ── link domains: channel per domain, last safety check, burned flag; check now / clear / pull (2026-10-10) ── async function loadDomains() { const d = await api('/api/admin/domains'); @@ -976,7 +1002,7 @@ })); // site settings: key / value rows; booleans as checkboxes, numbers stay numbers - const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Daily growth snapshot: targets (feed = proof channel, echo = shared payments topic; comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' }; + const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Daily growth snapshot: targets (feed = proof channel, echo = shared payments topic; comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)', campaignEditFee: 'Ad edits: credits per edit after the first, free one on each ad (0 = always free)' }; function drawSite() { const wrap = $('siteForm'); wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '
' + esc(SITE_META[k] || humanize(k)) + '' diff --git a/public/assets/ads-screen.js b/public/assets/ads-screen.js index ee32a70..de16bdb 100644 --- a/public/assets/ads-screen.js +++ b/public/assets/ads-screen.js @@ -34,15 +34,48 @@ const cr = c => c.type === 'banner' ? (c.imageUrl ? '' : '') + '' + c.width + 'x' + c.height + '' : c.type === 'text' ? '' + esc(c.title) + '
' + esc(c.body || '') + '' : 'full page' + (c.type === 'login' && c.expires ? '
' + (c.expires > Date.now() ? 'slot ends ' : 'ended ') + new Date(c.expires).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + '' : '') + '
'; $('rows').innerHTML = cs.length ? cs.map(c => '
' + esc(c.name) + ' ' + esc(c.type) + '' + (c.audience ? ' ' + esc((((D && D.audiences) || []).find(a => a.id === c.audience) || {}).name || 'audience') + (c.audienceMode === 'exclude' ? ' · excluded' : '') + '' : '') + '
#' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '
' + cr(c) + '
' + fmt(c.spent) + ' / ' + fmt(c.budget) + '
' + fmt(c.imps) + (c.impsNas ? '
+' + fmt(c.impsNas) + ' network' : '') + '
' + fmt(c.clicks) + '' + st(c) + '' + (c.status === 'active' ? '' : c.status === 'paused' ? '' : '') - + (['active', 'paused', 'out'].includes(c.status) && c.type !== 'login' ? '' : '') + '
').join('') + + (['active', 'paused', 'out'].includes(c.status) && c.type !== 'login' ? '' : '') + + (c.status !== 'done' ? '' : '') + '
').join('') : '
No ads yet. Launch one: a banner, a text ad or a login-ad slot.
'; if (D.gauntletPending) $('earnNote').insertAdjacentHTML('afterend', '
Your welcome credits unlock after the short welcome tour on the classic dashboard.
'); $('foot').textContent = 'views = timed views in the ad viewer plus member zones; network = the partner ad network · a paused ad keeps its credits · unspent credits return when an ad ends'; $('rows').querySelectorAll('[data-pause]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.pause + '/pause'))); $('rows').querySelectorAll('[data-resume]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.resume + '/resume'))); $('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => { const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return; try { await api('/api/my/campaigns/' + b.dataset.top + '/topup', { credits: Number(v.credits) }); toast('Topped up.'); load(); } catch (e) { toast(e.message, true); } })); + $('rows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openEdit(Number(b.dataset.edit)))); slotChip(); if (!$('composer').hidden) setType(TYPE); earnPaint(); + { const hm = /^#edit=(\d+)$/.exec(location.hash || ''); if (hm) { history.replaceState(null, '', location.pathname + location.search); openEdit(Number(hm[1])); } } // /tools campaign list links here + } + // -- edit an ad (2026-10-18): fix the link, the image or the text. The first edit of each ad is free, then D.editFee credits. + // Type, size, budget, countries, schedule and audience are the buy itself and stay a new campaign. + const feeNote = c => !c.edits ? 'This edit is free (your one free correction).' : (D.editFee ? 'This edit costs ' + fmt(D.editFee) + ' credits.' : 'Edits are free right now.'); + async function openEdit(id) { + const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) { toast('That ad is not in your list.', true); return; } + const fields = [{ k: 'name', label: 'Name', value: c.name, max: 60 }, { k: 'targetUrl', label: 'Where the click goes', value: c.targetUrl, mono: true }]; + if (c.type === 'banner') fields.push({ k: 'imageUrl', label: 'Image URL (' + c.width + 'x' + c.height + ')', value: c.imageUrl || '', mono: true }); + if (c.type === 'text') fields.push({ k: 'title', label: 'Headline (60)', value: c.title || '', max: 60 }, { k: 'body', label: 'One line (140)', value: c.body || '', max: 140 }); + const last = (c.editLog || []).slice(-1)[0]; + const html = '
' + esc(feeNote(c)) + ' ' + (c.edits ? 'Your free correction on this ad is used.' : 'After this one, each edit costs ' + fmt(D.editFee) + ' credits.') + '
' + + '
The type, size, budget, countries, schedule and audience stay as they are. To change those, start a new ad.' + (last ? ' Last edited ' + new Date(last.ts).toLocaleString() + '.' : '') + '
' + + (c.type === 'banner' ? '
Preview at real size
' : '') + + (c.type === 'login' ? '
A login ad shows the page itself, full screen, so the link is the ad.
' : ''); + const wait = dialog({ title: 'Edit ad #' + c.id + ' (' + c.type + ')', html, fields, ok: 'Review changes' }); + if (c.type === 'banner') { // the dialog is in the page now: wire the preview and the uploader + const host = $('crModalHost'), inp = host.querySelector('#dlg-imageUrl'), prev = host.querySelector('#edPrev'); + const paint = () => { const u = inp.value.trim(); prev.innerHTML = /^https?:\/\//i.test(u) ? '' : 'No image yet'; }; + inp.addEventListener('input', paint); paint(); + host.querySelector('#edFile').addEventListener('change', async e => { const f = e.target.files[0]; if (!f) return; try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); inp.value = location.origin + r.url; paint(); toast('Uploaded.'); } catch (er) { toast(er.message, true); } }); + } + const v = await wait; if (!v) return; + const label = { name: 'name', targetUrl: 'link', imageUrl: 'image', title: 'headline', body: 'text line' }; + const changed = Object.keys(v).filter(k => String(v[k]).trim() !== String(c[k] || '').trim()); + if (!changed.length) { toast('Nothing changed.'); return; } + const ok = await dialog({ title: 'Save the new ' + changed.map(k => label[k]).join(', ') + '?', text: feeNote(c) + (c.edits && D.editFee ? ' It comes out of your earned credits first, then purchased.' : ''), ok: c.edits && D.editFee ? 'Save and pay ' + fmt(D.editFee) : 'Save' }); + if (!ok) return; + const body = {}; changed.forEach(k => { body[k] = v[k].trim(); }); + try { const r = await api('/api/my/campaigns/' + c.id + '/edit', body); toast('Saved.' + (r.fee ? ' ' + fmt(r.fee) + ' credits charged.' : '') + (r.warn ? ' ' + r.warn : '')); load(); } + catch (e) { toast(e.message, true); } } async function act(path) { try { await api(path, {}); load(); } catch (e) { toast(e.message, true); } } // -- earn by viewing: the engine's fraud-guarded flow (server-timed dwell + a human check) runs inside /view/ diff --git a/public/assets/my.js b/public/assets/my.js index 762ec30..531b4a8 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -827,6 +827,7 @@ + '' + (c.status === 'active' ? '' : c.status === 'paused' ? '' : '') + ' ' + + (c.status !== 'done' ? ' Edit' : '') + '').join('') + ''; el.appendChild(tbl); el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { diff --git a/public/my.html b/public/my.html index 88286ed..82f3f38 100644 --- a/public/my.html +++ b/public/my.html @@ -1012,7 +1012,7 @@ - + diff --git a/qa/adedit.mjs b/qa/adedit.mjs new file mode 100644 index 0000000..6c398a5 --- /dev/null +++ b/qa/adedit.mjs @@ -0,0 +1,257 @@ +// Ad editing end-to-end test (2026-10-18, Orlando's ask). Boots server.js on its own port with a throwaway, seeded data +// dir (JSON store, no DB, no mail key, devCode sign-in, NAS off, no chain: free members only), then checks: +// create banner + login ads with seeded credits; first edit free, second charges the fee, third refused when short; +// bad URL / bad image / blocked-framing link refused; type, size, budget locked; non-owner refused; history recorded; +// a NAS-linked campaign edits with NAS off (no crash); admin edit is free and keeps the member's free edit; +// the Ads screen Edit flow in Playwright with screenshots. +// node qa/adedit.mjs (from the site dir; needs internet for the frame check on example.com) +// Env: PORT (default 8963), PW (playwright package dir), SHOTS (default D:/tmp/ad-edit) +import { pathToFileURL } from 'node:url'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import zlib from 'node:zlib'; +import crypto from 'node:crypto'; +import { spawn } from 'node:child_process'; + +const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; +const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default; +const PORT = Number(process.env.PORT || 8963); +const BASE = 'http://127.0.0.1:' + PORT; +const SHOTS = process.env.SHOTS || 'D:/tmp/ad-edit'; +const ADMIN_PW = 'localtest-ae'; +const results = []; let failed = 0; +const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; }; + +function crc32(buf) { let c, crc = 0xffffffff; for (let n = 0; n < buf.length; n++) { c = (crc ^ buf[n]) & 0xff; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crc = (crc >>> 8) ^ c; } return (crc ^ 0xffffffff) >>> 0; } +function png(w, h, rgb) { + const chunk = (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(crc32(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; + const raw = Buffer.alloc((w * 3 + 1) * h); + for (let y = 0; y < h; y++) { const o = y * (w * 3 + 1); for (let x = 0; x < w; x++) { const i = o + 1 + x * 3; const st = ((x >> 4) & 1) ? 40 : 0; raw[i] = Math.min(255, rgb[0] + st); raw[i + 1] = rgb[1]; raw[i + 2] = rgb[2]; } } + return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ih), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); +} + +// ── seed: two free members (no member id, so no chain calls), engine-pool credits, one NAS-linked campaign ── +const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ae-qa-')); +fs.mkdirSync(path.join(DATA, 'uploads')); +const now = Date.now(); +const acct = (email, username) => ({ email, username, code: username.slice(0, 7), memberId: 0, created: now - 86400000, sponsorRef: '' }); +const A = 'orlando@ae.test', B = 'other@ae.test'; +const accounts = { v: 2, byEmail: { [A]: acct(A, 'aeorlando'), [B]: acct(B, 'aeother') }, byAddress: {}, byCode: {}, joins: 2, positions: {} }; +for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email; +fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts)); +// A: 1000 credited purchased (the login slot) + 200 viewing (110 free once two banners hold 90); B: 500 viewing +fs.writeFileSync(path.join(DATA, 'earned.json'), JSON.stringify({ [A]: { balance: 1200, grade: 1000, welcomed: true }, [B]: { balance: 500, welcomed: true } })); +// a banner of A's that is syndicated to NAS (nasAdId set), so the edit walks the network branch with NAS off +fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 2, burnsPending: [], campaigns: [{ id: 1, owner: A, memberId: 0, type: 'banner', name: 'Old network banner', + targetUrl: 'https://example.com/', imageUrl: 'https://example.com/old.png', title: null, body: null, budget: 40, spent: 0, accrued: 0, imps: 0, clicks: 0, batchImps: 0, + width: 468, height: 60, nasAdId: 4242, status: 'active', created: now - 3600000 }] })); +const IMG = { a: png(468, 60, [200, 40, 40]), b: png(468, 60, [40, 160, 60]), c: png(300, 250, [40, 80, 220]) }; +fs.mkdirSync(SHOTS, { recursive: true }); +for (const [k, b] of Object.entries(IMG)) fs.writeFileSync(path.join(DATA, k + '.png'), b); + +const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); +const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@ae.test' }); +for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_API_KEY']) delete env[k]; +const log = fs.createWriteStream(path.join(SHOTS, 'server.log')); +const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] }); +srv.stdout.pipe(log); srv.stderr.pipe(log); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +function req(method, p, o) { + o = o || {}; + return new Promise((resolve, reject) => { + const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) QA' }, o.headers || {}); + if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip; + let body = o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; } + if (body) headers['Content-Length'] = body.length; + const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, buf, json: j }); }); }); + r.on('error', reject); if (body) r.write(body); r.end(); + }); +} +async function signIn(email) { + const ip = '10.8.' + crypto.randomInt(250) + '.' + crypto.randomInt(250); + const s = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } }); + if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.buf.toString().slice(0, 200)); + const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: s.json.devCode } }); + const sc = [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; '); + if (!sc) throw new Error('no session cookie for ' + email); + return sc; +} +const err = r => (r.json && r.json.error) || ('HTTP ' + r.status); +const ADMIN = { Authorization: 'Bearer ' + ADMIN_PW }; + +let browser, page = null; const pageErrors = []; +try { + for (let i = 0; i < 40; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) break; } catch (e) {} await sleep(500); } + const cA = await signIn(A), cB = await signIn(B); + const earnA = async () => (await req('GET', '/api/my/earn', { cookie: cA })).json; + const campsA = async () => (await req('GET', '/api/my/campaigns', { cookie: cA })).json; + + // ── create: a banner (uploaded image) and a login slot ── + const up = await req('POST', '/api/my/upload', { cookie: cA, body: IMG.a, headers: { 'Content-Type': 'image/png' } }); + check(up.status === 200 && /^\/uploads\//.test(up.json.url), 'banner image uploads', err(up)); + const imgA = BASE + up.json.url; + const mkB = await req('POST', '/api/my/campaigns', { cookie: cA, body: { type: 'banner', name: 'Orlando banner', targetUrl: 'https://example.com/', budget: 50, size: '468x60', imageUrl: imgA } }); + check(mkB.status === 200 && mkB.json.campaign && mkB.json.campaign.edits === 0, 'banner ad created (edits 0)', err(mkB)); + const mkL = await req('POST', '/api/my/campaigns', { cookie: cA, body: { type: 'login', name: 'Orlando login', targetUrl: 'https://example.com/login-page', budget: 1000 } }); + check(mkL.status === 200 && mkL.json.campaign, 'login ad created from credited purchased credits', err(mkL)); + const BID = mkB.json.campaign.id, LID = mkL.json.campaign.id; + const badCreate = await req('POST', '/api/my/campaigns', { cookie: cA, body: { type: 'banner', name: 'Bad img', targetUrl: 'https://example.com/', budget: 20, size: '468x60', imageUrl: 'https://example.com/' } }); + check(badCreate.status === 400 && /PNG, JPG, GIF or WebP/.test(err(badCreate)), 'create runs the same image check (an HTML page is not an image)', err(badCreate)); + const list0 = await campsA(); + check(list0.editFee === 100, 'GET campaigns carries the edit fee (default 100)', String(list0.editFee)); + + // ── refusals that never cost anything ── + const e0 = await earnA(); + const badUrl = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { targetUrl: 'ftp://nope.example/x' } }); + check(badUrl.status === 400 && /only http\(s\) URLs work/.test(err(badUrl)), 'bad link refused (same message as create)', err(badUrl)); + const shapeUrl = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { targetUrl: 'not a url' } }); + check(shapeUrl.status === 400, 'malformed link refused', err(shapeUrl)); + const framed = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { targetUrl: 'https://www.google.com/' } }); + check(framed.status === 400 && /blocks framing/.test(err(framed)), 'link that blocks framing refused (frame check, as create)', err(framed)); + const badImg = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { imageUrl: 'https://example.com/' } }); + check(badImg.status === 400 && /PNG, JPG, GIF or WebP/.test(err(badImg)), 'bad image (a web page) refused', err(badImg)); + const badImg2 = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { imageUrl: 'javascript:alert(1)' } }); + check(badImg2.status === 400 && /image URL starting with http/.test(err(badImg2)), 'non-http image refused with the create message', err(badImg2)); + const missImg = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { imageUrl: BASE + '/uploads/aaaaaaaaaaaaaaaaaaaaaaaa.png' } }); + check(missImg.status === 400 && /not on this server/.test(err(missImg)), 'an upload that does not exist refused', err(missImg)); + for (const [k, v] of [['type', 'text'], ['size', '300x250'], ['budget', 999], ['geo', '1'], ['dailyCap', 20], ['endsAt', now + 9e8]]) { + const r = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { [k]: v, name: 'try ' + k } }); + check(r.status === 400 && /cannot be changed/.test(err(r)), k + ' cannot be changed', err(r)); + } + const same = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { type: 'banner', size: '468x60', budget: 50, name: 'Orlando banner v2' } }); + check(same.status === 200, 'sending the unchanged type/size/budget alongside an edit is fine', err(same)); + const BEdits1 = same.json && same.json.campaign && same.json.campaign.edits; + check(same.json && same.json.fee === 0 && BEdits1 === 1, 'first edit of the banner is free', JSON.stringify({ fee: same.json && same.json.fee, edits: BEdits1 })); + const other = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cB, body: { targetUrl: 'https://example.com/hijack' } }); + check(other.status === 400 && /No such campaign/.test(err(other)), 'non-owner refused', err(other)); + const anon = await req('POST', '/api/my/campaigns/' + BID + '/edit', { body: { name: 'x' } }); + check(anon.status === 401, 'signed-out refused', String(anon.status)); + const nothing = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { name: 'Orlando banner v2' } }); + check(nothing.status === 400 && /Nothing changed/.test(err(nothing)), 'no change refused (no fee)', err(nothing)); + const e1 = await earnA(); + check(e1.earned === e0.earned, 'refusals and the free edit charged nothing', e0.earned + ' -> ' + e1.earned); + + // ── the login ad: first edit free (link), second costs 100 ── + const l1 = await req('POST', '/api/my/campaigns/' + LID + '/edit', { cookie: cA, body: { targetUrl: 'https://example.com/fixed-login' } }); + check(l1.status === 200 && l1.json.fee === 0 && l1.json.campaign.targetUrl === 'https://example.com/fixed-login', 'login ad link fixed, free', err(l1)); + const lImg = await req('POST', '/api/my/campaigns/' + LID + '/edit', { cookie: cA, body: { imageUrl: imgA, name: 'Orlando login' } }); + check(lImg.status === 400 && /Nothing changed/.test(err(lImg)), 'login ad has no image to edit (the page is the ad)', err(lImg)); + + // ── banner: second edit costs 100, third refused when short ── + const before2 = await earnA(); + const up2 = await req('POST', '/api/my/upload', { cookie: cA, body: IMG.b, headers: { 'Content-Type': 'image/png' } }); + const b2 = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { imageUrl: BASE + up2.json.url, targetUrl: 'https://example.com/?offer=new' } }); + const after2 = await earnA(); + check(b2.status === 200 && b2.json.fee === 100 && b2.json.paidFrom === 'earned', 'second edit charges 100 credits from earned', err(b2) + ' ' + JSON.stringify(b2.json && { fee: b2.json.fee, paidFrom: b2.json.paidFrom })); + check(before2.earned - after2.earned === 100, 'the pool dropped by exactly 100', before2.earned + ' -> ' + after2.earned); + const freeNow = after2.earnedAvailable; + check(freeNow < 100, 'A now has fewer than 100 free credits (' + freeNow + ')', String(freeNow)); + const b3 = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { name: 'Third try' } }); + const after3 = await earnA(); + check(b3.status === 400 && /costs 100 credits/.test(err(b3)) && b3.json.short === true, 'third edit refused when credits are short', err(b3)); + check(after3.earned === after2.earned, 'the refused edit charged nothing', after2.earned + ' -> ' + after3.earned); + const cs3 = await campsA(); const B3 = cs3.campaigns.find(c => c.id === BID); + check(B3.edits === 2 && B3.name === 'Orlando banner v2' && B3.targetUrl === 'https://example.com/?offer=new', 'refused edit left the ad and the count alone', JSON.stringify({ edits: B3.edits, name: B3.name })); + // ── history ── + const h = B3.editLog || []; + check(h.length === 2 && h[0].fields.join() === 'name' && h[0].from.name === 'Orlando banner' && h[0].to.name === 'Orlando banner v2' && h[0].fee === 0 + && h[1].fields.includes('imageUrl') && h[1].fields.includes('targetUrl') && h[1].from.targetUrl === 'https://example.com/' && h[1].fee === 100 && h[1].ts > 0, 'edit history: ts, fields, old and new values, fee', JSON.stringify(h).slice(0, 300)); + // ── NAS-linked campaign with NAS off ── + const n1 = await req('POST', '/api/my/campaigns/1/edit', { cookie: cA, body: { imageUrl: imgA } }); + check(n1.status === 200 && n1.json.network === null, 'NAS-linked banner edits with NAS off: no crash, network untouched', err(n1) + ' ' + JSON.stringify(n1.json && n1.json.network)); + const alive = await req('GET', '/api/config'); + check(alive.status === 200, 'server still up after the NAS branch', String(alive.status)); + // ── admin: free, any campaign, member's count untouched ── + const ad = await req('POST', '/api/admin/campaigns/' + BID + '/edit', { headers: ADMIN, body: { name: 'Typo fixed by Marty' } }); + check(ad.status === 200 && ad.json.fee === 0 && ad.json.campaign.edits === 2, 'admin edit: free, member edit count unchanged', err(ad) + ' edits=' + (ad.json && ad.json.campaign && ad.json.campaign.edits)); + const adNo = await req('POST', '/api/admin/campaigns/' + BID + '/edit', { body: { name: 'x' } }); + check(adNo.status === 401, 'admin route needs admin', String(adNo.status)); + const ct = await req('GET', '/api/admin/content?type=ad&fresh=1&per=50', { headers: ADMIN }); + const row = ct.json && ct.json.items.find(r => r.id === String(BID)); + check(row && row.detail.edits === 2 && row.detail.editLog.length === 3 && row.detail.editLog[2].by === 'admin' && row.actions.some(a => a.label === 'Edit ad'), 'admin Member content shows edits, history and an Edit action', JSON.stringify(row && { edits: row.detail.edits, n: row.detail.editLog.length })); + // ── the fee setting ── + await req('PATCH', '/api/admin/site', { headers: ADMIN, body: { campaignEditFee: 0 } }); + const z = await req('POST', '/api/my/campaigns/' + BID + '/edit', { cookie: cA, body: { name: 'Free while the fee is 0' } }); + check(z.status === 200 && z.json.fee === 0, 'campaignEditFee 0 makes edits free', err(z)); + await req('PATCH', '/api/admin/site', { headers: ADMIN, body: { campaignEditFee: 100 } }); + // ── chatbot ── + const cb = await req('POST', '/api/chat', { cookie: cA, body: { message: 'How do I fix the link on my ad?' } }); + check(cb.json && /press Edit/.test(cb.json.reply || ''), 'chatbot canned answer for fixing an ad link', (cb.json && (cb.json.reply || cb.json.error) || '').slice(0, 80)); + + // ── the Ads screen: Edit flow in the browser ── + browser = await chromium.launch(); + const ctx = await browser.newContext({ viewport: { width: 1360, height: 950 } }); + await ctx.addCookies(cA.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; })); + await ctx.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} }); // skip the once-per-session login sponsor gate + page = await ctx.newPage(); + page.on('pageerror', e => pageErrors.push(e.message)); page.on('console', m => { if (m.type() === 'error' && !/favicon|fonts|status of 40[014]|ERR_NAME|ERR_CONNECTION|example\.com/.test(m.text())) pageErrors.push(m.text()); }); + // give A a fresh banner with a free edit, plus enough for one paid edit + const up3 = await req('POST', '/api/my/upload', { cookie: cA, body: IMG.a, headers: { 'Content-Type': 'image/png' } }); + const mk2 = await req('POST', '/api/my/campaigns', { cookie: cA, body: { type: 'banner', name: 'UI banner', targetUrl: 'https://example.com/', budget: 10, size: '468x60', imageUrl: BASE + up3.json.url } }); + check(mk2.status === 200, 'second banner for the UI flow', err(mk2)); + const UID = mk2.json.campaign.id; + await page.goto(BASE + '/ads', { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('[data-edit="' + UID + '"]', { timeout: 15000 }); + await page.screenshot({ path: path.join(SHOTS, '01-ads-list-edit-buttons.png'), fullPage: true }); + await page.click('[data-edit="' + UID + '"]'); + await page.waitForSelector('#dlg-targetUrl', { timeout: 5000 }); + check(await page.inputValue('#dlg-targetUrl') === 'https://example.com/', 'editor prefilled with the current link'); + check(/free \(your one free correction\)/.test(await page.textContent('#edFee')), 'editor shows the free note', (await page.textContent('#edFee')).trim()); + const pw = await page.$eval('#edPrev img', i => i.getBoundingClientRect().width).catch(() => 0); + check(Math.round(pw) === 468 + 2 || Math.round(pw) === 468, 'image preview at real size (468 px)', String(pw)); + await page.fill('#dlg-targetUrl', 'https://example.com/?ui=fixed'); + await page.setInputFiles('#edFile', path.join(DATA, 'b.png')); + await page.waitForFunction(() => /\/uploads\//.test(document.querySelector('#dlg-imageUrl').value), null, { timeout: 5000 }); + await page.screenshot({ path: path.join(SHOTS, '02-editor-free.png') }); + await page.click('#dlgOk'); + await page.waitForSelector('.modal h2', { timeout: 5000 }); + const conf1 = await page.textContent('.modal'); + check(/This edit is free \(your one free correction\)/.test(conf1), 'confirm says the edit is free', conf1.slice(0, 120)); + await page.screenshot({ path: path.join(SHOTS, '03-confirm-free.png') }); + await page.click('#dlgOk'); + await page.waitForFunction(id => { const b = document.querySelector('[data-edit="' + id + '"]'); return b && /credits/.test(b.title); }, UID, { timeout: 10000 }); + const cu = (await campsA()).campaigns.find(c => c.id === UID); + check(cu.targetUrl === 'https://example.com/?ui=fixed' && /\/uploads\//.test(cu.imageUrl) && cu.edits === 1, 'UI edit saved link + new upload', JSON.stringify({ t: cu.targetUrl, e: cu.edits })); + // second, paid edit: give A 100 more earned credits through the admin grant path is not available here, so top the + // pool up by the promo-free route: B cannot gift, so check the fee wording and the refusal toast instead + await page.click('[data-edit="' + UID + '"]'); + await page.waitForSelector('#dlg-name', { timeout: 5000 }); + check(/costs 100 credits/.test(await page.textContent('#edFee')), 'editor shows the fee note on the second edit', (await page.textContent('#edFee')).trim()); + await page.fill('#dlg-name', 'UI banner renamed'); + await page.click('#dlgOk'); + await page.waitForSelector('.modal h2', { timeout: 5000 }); + const conf2 = await page.textContent('.modal'); + check(/This edit costs 100 credits/.test(conf2) && /Save and pay 100/.test(conf2), 'confirm says the edit costs 100 credits', conf2.slice(0, 160)); + await page.screenshot({ path: path.join(SHOTS, '04-confirm-fee.png') }); + await page.click('#dlgOk'); + await page.waitForSelector('#crToast.on.bad', { timeout: 8000 }); + const toastTxt = await page.textContent('#crToast'); + check(/costs 100 credits/.test(toastTxt), 'short on credits: clear refusal in the screen', toastTxt.slice(0, 140)); + await page.screenshot({ path: path.join(SHOTS, '05-refused-short.png') }); + // phone width + await page.setViewportSize({ width: 390, height: 844 }); await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('[data-edit="' + UID + '"]', { timeout: 15000 }); + await page.click('[data-edit="' + UID + '"]'); await page.waitForSelector('#dlg-name', { timeout: 5000 }); + await page.screenshot({ path: path.join(SHOTS, '06-editor-phone.png') }); + const hs = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + check(hs <= 1, 'no horizontal page scroll at phone width with the editor open', String(hs)); + // the /tools campaign list deep link + await page.goto(BASE + '/ads#edit=' + BID, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#dlg-name', { timeout: 15000 }); + check(/Edit ad #/.test(await page.textContent('.modal h2')), '/ads#edit= opens the editor (link from the /tools list)'); + check(!pageErrors.length, 'no page errors', pageErrors.slice(0, 3).join(' | ')); +} catch (e) { + check(false, 'run crashed', e.stack + ' | page errors: ' + pageErrors.join(' | ')); if (page) try { await page.screenshot({ path: path.join(SHOTS, 'crash.png'), fullPage: true }); } catch (x) {} +} finally { + if (browser) await browser.close(); + srv.kill(); + await sleep(300); + try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} + console.log(results.join('\n')); + console.log('\n' + (results.length - failed) + '/' + results.length + ' passed' + (failed ? ', ' + failed + ' FAILED' : '')); + fs.writeFileSync(path.join(SHOTS, 'results.txt'), results.join('\n') + '\n'); + process.exit(failed ? 1 : 0); +} diff --git a/server.js b/server.js index 9ef234d..326056b 100644 --- a/server.js +++ b/server.js @@ -454,6 +454,93 @@ async function frameCheck(url) { return { ok: false, reason: 'That site blocks framing (CSP frame-ancestors), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; return { ok: true }; } +// ── banner image check (2026-10-18, with ad editing): the image has to load, be a real PNG / JPG / GIF / WebP and stay +// within the 3 MB the uploader allows. Our own uploads are read off the volume; anything else is fetched through the same +// private-address guard as the frame check. A size that differs from the banner slot is a warning, never a refusal. +const IMG_MAGIC = b => b.length > 16 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47 ? 'image/png' + : b.length > 16 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff ? 'image/jpeg' + : b.length > 16 && b.slice(0, 4).toString() === 'GIF8' ? 'image/gif' + : b.length > 16 && b.slice(0, 4).toString() === 'RIFF' && b.slice(8, 12).toString() === 'WEBP' ? 'image/webp' : ''; +const IMG_MAX = 3 * 1024 * 1024; +function imageFetch(url, depth) { + return new Promise(resolve => { + let u; try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); } + if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' }); + if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' }); + if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' }); + dns.lookup(u.hostname, (de, addr) => { + if (de) return resolve({ error: 'that domain does not resolve' }); + if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' }); + const mod = u.protocol === 'https:' ? https : http; + const rq = mod.get(u.href, { timeout: 8000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpin-ImageCheck/1.0)', Accept: 'image/*' } }, r => { + const loc = r.headers.location; + if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) { + r.resume(); rq.destroy(); + let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); } + return resolve(imageFetch(next, depth + 1)); + } + if (r.statusCode >= 400) { r.resume(); rq.destroy(); return resolve({ error: 'it answers with HTTP ' + r.statusCode }); } + const chunks = []; let n = 0, done = false; + r.on('data', c => { if (done) return; n += c.length; if (n > IMG_MAX) { done = true; rq.destroy(); return resolve({ error: 'it is larger than 3 MB' }); } chunks.push(c); }); + r.on('end', () => { if (!done) { done = true; resolve({ buf: Buffer.concat(chunks) }); } }); + r.on('error', () => { if (!done) { done = true; resolve({ error: 'it stopped loading part way' }); } }); + }); + rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); }); + rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' })); + }); + }); +} +async function imageCheck(url, size) { + let got = null; + try { + const u = new URL(String(url || '')); + const own = [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); + const local = /^\/uploads\/([a-f0-9]{24}\.(png|jpg|webp|gif))$/.exec(u.pathname); + if (local && (own.includes(u.hostname.toLowerCase()) || (!IS_PROD && /^(localhost|127\.0\.0\.1)$/.test(u.hostname)))) { + try { const buf = fs.readFileSync(path.join(UPLOADS_DIR, local[1])); got = buf.length > IMG_MAX ? { error: 'it is larger than 3 MB' } : { buf }; } + catch (e) { got = { error: 'that upload is not on this server' }; } + } + } catch (e) {} + if (!got) got = await imageFetch(url, 0); + // a host that is slow or blocks our checker must not block a real ad: only a too-big file or a missing upload refuses + // outright; anything else goes through with a warning (review 2026-10-18) + if (got.error && !/larger than 3 MB|not on this server/.test(got.error)) return { ok: true, warn: 'We could not check your banner image just now (' + got.error + '). If it does not show in your ad, upload the image instead.' }; + if (got.error) return { ok: false, reason: 'We checked your banner image and ' + got.error + '. Upload the image or paste a working https link to it.' }; + const mime = IMG_MAGIC(got.buf); + if (!mime) return { ok: false, reason: 'That link does not lead to a PNG, JPG, GIF or WebP image. Upload the image or paste a direct link to the image file.' }; + const d = mime === 'image/webp' ? { w: 0, h: 0 } : bannerspin.dims(got.buf, mime); + const want = /^(\d+)x(\d+)$/.exec(String(size || '')); + return { ok: true, w: d.w, h: d.h, bytes: got.buf.length, + warn: want && d.w && (d.w !== Number(want[1]) || d.h !== Number(want[2])) ? 'This image is ' + d.w + 'x' + d.h + ' and the ad slot is ' + want[1] + 'x' + want[2] + ', so it will be scaled to fit.' : '' }; +} +// the outside checks a campaign's link and image go through, shared by member create, house-ad create and every edit. +// Banner and text views frame the target, so it has to allow framing; login (and solo, video, featured) open in a new +// tab or our own player. A banner image has to load and be an image. `f` carries only what is being set or changed. +async function adChecks(type, f) { + if (f.targetUrl !== undefined && !['login', 'solo', 'video', 'featured'].includes(String(type || ''))) { + const fc = await frameCheck(f.targetUrl); if (!fc.ok) return { error: fc.reason }; + } + let warn = ''; + if (type === 'banner' && f.imageUrl !== undefined && /^https?:\/\/\S+$/i.test(String(f.imageUrl || '').trim())) { // a malformed URL gets the plain shape message from ads.validate + const ic = await imageCheck(String(f.imageUrl).trim(), f.size); if (!ic.ok) return { error: ic.reason }; warn = ic.warn || ''; + } + return { ok: true, warn }; +} +const editFee = () => { const n = Math.floor(Number(siteConfig().campaignEditFee)); return n >= 0 ? n : 100; }; +// one path for member and admin edits: the outside checks on whatever changed, then ads.editCampaign (shape checks, +// fee, history, network copy). Open ad-viewer tokens for this campaign get the new link, so a view in flight frames it. +async function editAd(id, b, who) { + const c = await ads.campaignById(id); + if (!c || (!who.admin && String(c.owner || '').toLowerCase() !== String(who.owner || '').toLowerCase())) return { error: 'No such campaign.' }; + const f = {}; + if (b.targetUrl !== undefined && String(b.targetUrl).trim() !== String(c.targetUrl || '')) f.targetUrl = String(b.targetUrl).trim(); + if (c.type === 'banner' && b.imageUrl !== undefined && String(b.imageUrl).trim() !== String(c.imageUrl || '')) { f.imageUrl = String(b.imageUrl).trim(); f.size = c.width && c.height ? c.width + 'x' + c.height : ''; } + const ck = await adChecks(c.type, f); if (ck.error) return { error: ck.error }; + const r = await ads.editCampaign(who.owner, id, b, { admin: !!who.admin, fee: editFee(), ids: who.ids }); + if (r.ok && r.changed.includes('targetUrl')) for (const t of earnTokens.values()) if (t && Number(t.adId) === Number(id)) t.targetUrl = r.campaign.targetUrl; + if (r.ok) { r.nextFee = who.admin ? null : editFee(); if (ck.warn) r.warn = ck.warn; } + return r; +} async function boot() { await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode) chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {}); @@ -574,7 +661,8 @@ function siteConfig() { legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else - pnlFixedMonthlyUsd: 0 + pnlFixedMonthlyUsd: 0, + campaignEditFee: 100 // credits per ad edit after each campaign's first, free one (Orlando's ask, 2026-10-18); 0 = edits always free }, saved); } @@ -3110,6 +3198,7 @@ const server = http.createServer(async (req, res) => { if (!(await ads.welcomeGranted(s.email))) { const tour = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl); if (!tour.length) await ads.grantWelcome(s.email); else gauntletPending = true; } const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending, audiences: audiences.list(s.email) }; out.loginSlots = await ads.loginSlots(); // { max, used, free, credits, days }: the Ads screen shows how many are open + out.editFee = editFee(); // credits per edit after each campaign's free one (the editor says which this is) out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id)); out.hours = await ads.hoursFor(out.campaigns.map(c => c.id)); // on-site views per UTC hour, last 7 days out.geo = await ads.geoFor(out.campaigns.map(c => c.id)); // on-site serves per viewer country @@ -3132,10 +3221,7 @@ const server = http.createServer(async (req, res) => { const b = await readBody(req); if (!MEMBER_AD_TYPES.includes(String(b.type || ''))) return json(res, 400, { error: 'LinkSpin runs banner, text and login ads.' }); if (b.audience && !audiences.owns(s.email, b.audience)) return json(res, 400, { error: 'That audience is not one of yours.' }); // Marty 2026-09-29: the three formats members buy - if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player - const fc = await frameCheck(b.targetUrl); - if (!fc.ok) return json(res, 400, { error: fc.reason }); - } + { const ck = await adChecks(String(b.type || ''), { targetUrl: b.targetUrl, imageUrl: b.imageUrl, size: b.size }); if (ck.error) return json(res, 400, { error: ck.error }); } // frame check (banner/text views frame the target) + banner image check, shared with edits // charge the best-funded of the member's positions (main + Qualified Start // wallets). A campaign burns from one member id, so the budget must fit inside it. const ids = (await myMemberIds(s)).ids; @@ -3148,6 +3234,15 @@ const server = http.createServer(async (req, res) => { const r = await ads.createCampaign(s.email, fundId, b, ids); return json(res, r.error ? 400 : 200, r); } + // edit a campaign's link, creative or name (Orlando, 2026-10-18): owner only, the create checks, first edit free + m = /^\/api\/my\/campaigns\/(\d+)\/edit$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await editAd(m[1], b, { owner: s.email, ids: (await myMemberIds(s)).ids }); + return json(res, r.error ? 400 : 200, r); + } m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.exec(p); if (m && req.method === 'POST') { const s = await auth.fromRequest(req); @@ -3251,13 +3346,16 @@ const server = http.createServer(async (req, res) => { if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); - if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { - const fc = await frameCheck(b.targetUrl); - if (!fc.ok) return json(res, 400, { error: fc.reason }); - } + { const ck = await adChecks(String(b.type || ''), { targetUrl: b.targetUrl, imageUrl: b.imageUrl, size: b.size }); if (ck.error) return json(res, 400, { error: ck.error }); } const r = await ads.createHouseCampaign(b); return json(res, r.error ? 400 : 200, r); } + m = /^\/api\/admin\/campaigns\/(\d+)\/edit$/.exec(p); // any campaign, free, never uses up the member's free edit + if (m && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const r = await editAd(m[1], await readBody(req), { admin: true }); + return json(res, r.error ? 400 : 200, r); + } m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); if (m && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' });