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/<id>/edit (owner) and /api/admin/campaigns/<id>/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/<id>, 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=<id> 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 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-18 19:24:05 -05:00
parent 77c2037dee
commit 7be213311f
13 changed files with 444 additions and 18 deletions
+104 -9
View File
@@ -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/<brand>
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' });