From 7be213311f25f85a75b561b23c82aedb45776f8c Mon Sep 17 00:00:00 2001 From: martbost Date: Sun, 18 Oct 2026 19:24:05 -0500 Subject: [PATCH 1/2] Ad editing: fix the link, image, text or name of a running ad; first edit free, then campaignEditFee credits Orlando (#30) could only pause, resume or top up a banner or login ad with a wrong link. - POST /api/my/campaigns//edit (owner) and /api/admin/campaigns//edit (any ad, free, never uses the member's free edit). Banner: link, image, name. Text: link, headline, line, name. Login and the rest: link, name. Type, size, budget, geo, schedule, audience are refused. - Create and edit share one path: checkName/checkTarget/checkBannerImage/checkTextCopy in ads.js (validate() now calls them) and adChecks() in server.js (frame check + a new banner image check: loads, is a real PNG/JPG/GIF/WebP, up to 3 MB; own uploads read off the volume). - Fee: campaigns.edits counts member edits; the first is free, each later one costs the site setting campaignEditFee (default 100, admin Settings). Charged from the engine pool via spendEarned (earned first, then credited purchased); with neither, a burn row on the best-funded position (the normal burn queue). Guarded claim so two saves cannot both be free; a failed save refunds exactly what was taken. - History: campaigns.edit_log (ts, by, fields, old/new values, fee), last 50. - NAS: clicks already route through /api/ads/click/, so a new link needs no write; a new image or text goes to the NAS row via nas.updateCreative. Failures never block the edit and retry on the next reconcile pass. Open ad-viewer tokens get the new link. - UI: Edit button on the Ads screen (CR.dialog editor, real-size preview, upload, free/fee note and confirm), /ads#edit= deep link from the /tools list, admin Member content shows edit count + history with an Edit action. Chatbot canned answer + FACTS. - qa/adedit.mjs: 51 checks against a throwaway DATA_DIR, Playwright screenshots in D:/tmp/ad-edit. Co-Authored-By: Claude Opus 5.5 --- ads.js | Bin 96157 -> 106944 bytes chatbot.js | 4 +- content.js | 6 +- db.js | 2 + nas.js | 10 +- public/admin.html | 2 +- public/ads.html | 2 +- public/assets/admin.js | 28 +++- public/assets/ads-screen.js | 35 ++++- public/assets/my.js | 1 + public/my.html | 2 +- qa/adedit.mjs | 257 ++++++++++++++++++++++++++++++++++++ server.js | 113 ++++++++++++++-- 13 files changed, 444 insertions(+), 18 deletions(-) create mode 100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: []; 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..17714b1 100644 --- a/server.js +++ b/server.js @@ -454,6 +454,90 @@ 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); + 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 +658,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 +3195,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 +3218,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 +3231,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 +3343,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' }); From d05d5527c5dd5ace281a957458a9b9958381629d Mon Sep 17 00:00:00 2001 From: martbost Date: Sun, 18 Oct 2026 19:24:59 -0500 Subject: [PATCH 2/2] Ad image check: a host that is slow or blocks the checker gives a warning, not a refusal (only a too-big file or a missing upload refuses) Co-Authored-By: Claude Opus 5.5 --- server.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server.js b/server.js index 17714b1..326056b 100644 --- a/server.js +++ b/server.js @@ -502,6 +502,9 @@ async function imageCheck(url, size) { } } 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.' };