diff --git a/chatbot.js b/chatbot.js index f6ced89..b263915 100644 --- a/chatbot.js +++ b/chatbot.js @@ -26,7 +26,7 @@ let DATA_DIR = null; let chain = null; const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b'; -const KNOWLEDGE_DATE = '2026-11-15'; // the day the CANNED answers and FACTS below were last checked against the site +const KNOWLEDGE_DATE = '2026-11-17'; // the day the CANNED answers and FACTS below were last checked against the site function init(opts) { if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; const ready = kb.init({ dataDir: DATA_DIR, seeds: seeds() }); @@ -217,6 +217,7 @@ function systemPrompt(kbBlock) { FACTS: - PROHIBITED CONTENT (2026-10-30, Terms section 9, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text. - LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company paid, decided off chain, paid on chain. 3% of every LinkSpin package purchase (the POL actually paid) goes to the buyer's 4th upline on the LinkSpin contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = referral whose first package was $25 or more; same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; company account #1 or nobody qualified = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId); shown on the Wallet screen as 'Level 4 override' with a Polygon link. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split is unchanged. Separate from InstantAdPay's override; qualification does not carry between sites. Never promise amounts. +- AI AD WRITER (LIVE 2026-11-17): on the Ads screen (/ads) pick Text, put your link in Where the click goes (or pick a spin link) and tap "Write my ad from my link": the network ad writer reads that page and suggests 3 text ads (headline up to 60, line up to 140) using only what the page says (no made-up claims, numbers or income promises); tap one to fill the fields, edit, then Launch. In the page builder (/pages) the editor has "Write my headline from my link" under the Subhead: it reads the Button link page and suggests 3 headline + subhead pairs; tap one, edit, Save. 5 writes a day per member (reset at midnight Central); the same page again within 24 hours is free. The same writer is on ViralAdSource, ViralAdBlitz and InstantAdPay. ${refuelFact()}${synFact()}- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/, rotates between destinations by weight; pause any destination; a fallback for when all are off; one-hop redirect; every click recorded with day, country, source, device and a daily-salted visitor hash; bots filtered on the server; click ids and sub ids such as clickid, subid, s1 to s4 pass through to the destination; split tests by tagging the same link with different sub ids; a demo spin on the home page needs no account; DAYPARTING is live: a 7x24 hours grid per spin and per destination, time zone by name or the local time of the visitor, presets, and 'my best hours' from the clicks of the member after 200 clicks; automatic HEALTH CHECKS are live: every destination is checked every 30 minutes, a dead or parked one is paused after three failing checks and resumed when it passes twice, the owner is told once, and Check now runs it on demand). PAGES (page builder: scan any offer URL, get a bridge, review or squeeze page; designs, palettes, layouts and niche presets with hero images; leads to the member's own list with a CSV download, or the member pastes an autoresponder form on a squeeze page and LinkSpin restyles it; there is no lead webhook; published on the pages domain lookfirst.page; sales, advertorial and press-release layouts are coming). ZONES (an ad slot on the member's own site: one async script tag, nine sizes 728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50; waterfall = LinkSpin member campaign, then a network ad for 728x90 and 468x60, then the LinkSpin house banner; pays ad credits per VIEWABLE impression, half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day; rates 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, 1 per 8 on a Verified zone; warm-up: a zone earns after its first 100 on-site views with at least 40 percent viewable and goes on hold below that; origin lock: paid ads serve only on the declared site and its subdomains, elsewhere the house banner shows and nothing is earned; up to 50 zones per account; PUBLISHER PROGRAM at /publishers for site owners, tiers Standard (default) and Verified (admin-reviewed site, better network rate)). AUDIENCES (first-party retargeting: "My visitors" collects everyone who viewed the member's pages and zones for 30 days; a pixel tag /p.js for other sites; campaigns can "show only to" or "never show to" an audience; nothing personal stored). PROMO TOOLS at /tools#promo (social posts, text-a-friend, email swipes, banners, objection bank, hook videos; five hook angles with videos: links, pages, zones, audiences, stack; angle links are the invite link plus ?v=). REPORTS (every link in one view, plus Pages, Zones, and since 2026-10-12 Traffic sources and Placements). BLOG at /blog with RSS at /blog/feed.xml. TRAFFIC SOURCES at /sources (2026-10-12): a source is a record of a network the member buys traffic on, created from a catalog of networks (PropellerAds, Zeropark, Adsterra, ExoClick, HilltopAds, TrafficStars, PopAds and more, with each network's macro tokens and conversion postback URL; account-specific slots such as a goal id are filled in at creation) or defined by hand; a spin link is pointed at one source (Share kit on the Links screen, or the Sources screen), and then the Share kit's first row is the exact campaign URL for that network with its macros already in place; when a click that came through that source converts (join, lead, wallet, purchase, or a partner-reported conversion; the member picks which) LinkSpin fires that network's own postback with the network's click id and the payout, server to server, and only the network that sent the click is told; Reports show clicks, uniques and conversions by source and by placement (the value the network's zone, placement, site, campaign, creative, banner or keyword macro carried); up to 30 sources per account, 20 params each; a source with no postback still builds the campaign URL and shows in Reports; the account-level Postbacks list on the Links screen (for the member's own tracker) still works alongside. TRAFFIC GUIDE at /traffic-guide (2026-10-28, public, linked from the Sources screen header and each source's detail): pick an offer type (free sign-up or email capture; crypto or team-build opportunity; advertising tools and ad credits; games and play-to-earn; software, apps and AI tools; courses and info products; giveaways and freebies) to see each ad format rated best / good / weak / avoid with a reason, a tip, and the catalog networks that sell the good formats (strict-policy networks Google, Microsoft, Facebook, Taboola, Revcontent, MGID left out for the crypto offer; adult-only TrafficJunky only for games and giveaways); cards for the 8 formats (popunder, push, in-page push, native, search, social, banners, domain redirect: what it is, how you pay, what converts, what struggles, landing page); a table of all 30 catalog networks with the formats each sells, adult-heavy and strict-policy flags and best-for; ground rules (test small, track every click under Sources, one change at a time, block zones that waste money, no income promises, mainstream vs adult inventory). The New source picker shows the same format tags and can be searched by format (push, native...). Never promise results; the guide says Reports are the final word. Knowledge checked on ${KNOWLEDGE_DATE}. - CONVERSION PIXEL (LIVE 2026-10-23, Control Room > Conversions at ${SITE_URL}/conversions; InstantAdPay members see the same goals under Campaigns > Conversion tracking, held on their LinkSpin account): a member names GOALS (subscriber, sale, any word, optional default value, up to 20); each goal has a PUBLIC pixel id (px + 10 characters) that can only count clicks the member owns. EVERY CLICK GETS AN ID: LinkSpin ad clicks (banner, text, zones) and InstantAdPay ad clicks add lsclk= to the target address (other params kept); a spin link reached through an ad passes its own id on and inherits the ad as its source; spin links of a member with a goal add lsclk to the destination too, and so do Banner Spin clicks that go straight to a page (since 2026-10-26; a banner pointed at a spin link gets the spin link's id). SETUP, 3 steps: 1) the LANDING TAG on the landing page, one line , keeps the id on the member's own site 30 days (localStorage + a first-party cookie), fills hidden form fields named lsclk, lsid or clickid and adds the id to links that stay on the same site; 2) the GOAL PIXEL on the thank-you page, an image cv.gif?px=PIXEL_ID&goal=NAME (optional &value=19.95) or the script version cv.js that reads what the tag kept; 3) Send a test conversion (recorded apart, never counted). MATCHING ORDER: the click id in the address, then the id the tag kept, then LinkSpin's own cookie, then a 24-hour match on network + browser (a hash, no IP stored); the method is shown per goal so members see how solid each count is. RULES: each goal counts once per click (an ad click and the spin-link click it led to are one click), only within 30 days of a real click, only for the pixel owner's own clicks, rate limited per pixel and per visitor. OWN CLICKS (2026-10-26): the goal owner's own click on ANY click type (ads, spin links, Banner Spins) is kept as a test and never counted: a click made while signed in as the owner, or a click or conversion from a browser (network + browser soft key) the owner has signed in from on LinkSpin or InstantAdPay; the Conversions screen says 'N from your own clicks, kept as tests and left out'. To test, use Send a test conversion and the &test=1 page check, never a sign-up of your own. REPORTS per goal: conversions and cost per goal (the campaign's credits spent / its conversions, in that site's ad credits) by ad campaign (LinkSpin and InstantAdPay), spin link, Banner Spin (banners straight to a page), destination page and traffic source, plus CSV export. ONE PLACE TO LOOK (2026-11-07): Reports > Conversions on LinkSpin and the Conversion tracking card on InstantAdPay list goals together with join, wallet and purchase events, with values, each event once; per-link Conv. counts include goals; the CSV holds goal conversions only. NETWORK EVENTS (2026-11-07, reporting only, it never changes sponsors, payouts or anything on chain): the landing tag adds the kept click id to links to instantadpay.com, linkspin.app and the share domains instantadpay.link, ctbgo.com and mylinehq.com, also inside a member's own redirect link when the address is in one of its parameters (spin and Banner Spin links are left alone; a button that navigates by script instead of a link is not covered); a spin link or Banner Spin pointed straight at those sites adds lsclk with no goal needed. InstantAdPay keeps the click 30 days in a first-party cookie, stores it on the account at sign-up and reports sign-up, wallet link and each package purchase (value = the USD price on the chain event, linked positions included) to LinkSpin, which counts join and wallet once per click and every purchase on its own. Same 30-day rule: an event more than 30 days after the click does not count. The first account on a click owns it. The click owner's own account and own clicks are kept as tests. Postbacks fire for join, wallet and purchase as they do for LinkSpin's own. Nothing is counted back in time: an account without a click stored at sign-up has none. POSTBACKS: a postback or traffic source set to the event 'goal' fires for every goal with {event} = the goal name. AUTORESPONDERS: when Aweber, GetResponse or another provider hosts the thank-you page, set its thank-you (success) redirect to the member's own page that carries the pixel; otherwise the pixel still counts through the cookie or the 24-hour match, less surely. The tag and pixel never break the page if LinkSpin cannot be reached and work inside traffic-exchange frames. SETUP GUIDE (public, 2026-10-24): ${SITE_URL}/conversion-tracking (InstantAdPay's copy: https://instantadpay.com/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, the last test time updates, then remove it), what to do without code on the thank-you page (image pixel = cookie or 24-hour match; LinkSpin.goal(pixelId, name) from the page's own code for a pop-up form; postbacks), how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest, a Banner Spin banner pointed straight at a page now carries its own click id and counts under By Banner Spin; the member's own clicks on ads, spin links and Banner Spins are all kept as tests). Send members there for any setup question. - TOOL LIMITS BY TIER (2026-10-21): spin links and pages each: Free (no package) 3, Starter (any package of your own) 10, Builder (level 2 open, 2 qualifying buyers) 50, Leader (level 3 open, 5 qualifying buyers) unlimited (fair use). Each spin link rotates up to 25 destinations at every tier; clicks are unlimited. Nothing already made is ever removed when a cap applies; new ones wait for the upgrade. Banner Spin has its own ladder (Starter 2 x 5, Builder 5 x 15, Leader 10 x 25). Other limits, same for everyone: 50 zones, 20 audiences, 20 postbacks, 5 linked positions. diff --git a/hubadwriter.js b/hubadwriter.js new file mode 100644 index 0000000..afea097 --- /dev/null +++ b/hubadwriter.js @@ -0,0 +1,54 @@ +// The network AI ad writer, asked through the hub (Marty 2026-11-17: "the AI generation of the ads worked really well. Let's go +// ahead and do it on the other sites too."). The hub reads the member's page, asks the model and filters the copy +// (network-hub lib/adwriter.js); this file only signs the call for this site's signed-in member and passes the answer on. +// status(member?) -> {on, daily, left?} (cached 60 s; on: false when the hub is unset, unreachable or switched off) +// write(member, url, limits) -> {ok, options: [{headline, line?}], url, cached, left} | {error (member-friendly), code, status, left?} +// Signed as HUB_SITE with HUB_SECRET: X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body), like every /v1 call. +// AI_WRITER=0 hides the button on this site. Nothing is posted: the member picks an option, edits it and saves it themselves. +'use strict'; +const crypto = require('crypto'); + +const DEFAULT_SITE = 'linkspin'; +const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, ''); +const secret = () => String(process.env.HUB_SECRET || '').trim(); +const site = () => String(process.env.HUB_SITE || DEFAULT_SITE).trim(); +const configured = () => !/^(0|false|no|off)$/i.test(String(process.env.AI_WRITER || '').trim()) && !!hubUrl() && secret().length >= 32; + +async function call(route, body, timeoutMs) { + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex'); + const r = await fetch(hubUrl() + route, { method: 'POST', body: raw, signal: AbortSignal.timeout(timeoutMs), + headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } }); + let j = null; try { j = await r.json(); } catch (e) { j = null; } + return { status: r.status, body: j || {} }; +} + +let st = { at: 0, v: { on: false, daily: 0 } }; +async function status(member) { + if (!configured()) return { on: false, daily: 0 }; + if (!member && Date.now() - st.at < 60000) return st.v; + try { + const r = await call('/v1/adwriter/status', member ? { member: String(member) } : {}, 3000); + const v = r.status === 200 && r.body && typeof r.body.on === 'boolean' ? r.body : { on: false, daily: 0 }; + if (!member) st = { at: Date.now(), v: { on: v.on, daily: v.daily || 0 } }; + return v; + } catch (e) { if (!member) st = { at: Date.now() - 45000, v: { on: false, daily: 0 } }; return { on: false, daily: 0 }; } // a down hub is asked again in 15 s +} +// the button shows only when the hub says the writer is on (60 s cache, never waits on a slow hub for long) +async function enabled() { return (await status()).on === true; } + +async function write(member, url, limits) { + if (!configured()) return { error: 'The ad writer is switched off right now. You can still write your ad yourself.', code: 'off', status: 503 }; + try { + const r = await call('/v1/adwriter', { member: String(member), url: String(url || '').trim().slice(0, 600), limits }, 75000); + const b = r.body || {}; + if (r.status === 200 && b.ok && Array.isArray(b.options)) return { ok: true, options: b.options, url: b.url, cached: !!b.cached, left: b.left }; + if (r.status === 401 || r.status === 403 || !b.message) { console.error('hubadwriter: hub answered ' + r.status + ' ' + String(b.error || '')); return { error: 'The ad writer is busy right now. Try again in a minute, or write your ad yourself.', code: 'hub', status: 502 }; } + return { error: String(b.message), code: b.error || b.code || 'error', status: r.status >= 400 && r.status < 600 ? r.status : 502, left: b.left }; + } catch (e) { + console.error('hubadwriter: ' + (e.name === 'TimeoutError' || e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120))); + return { error: 'The ad writer did not answer in time. Try again in a minute, or write your ad yourself.', code: 'hub', status: 504 }; + } +} + +module.exports = { status, enabled, write, configured, _reset: () => { st = { at: 0, v: { on: false, daily: 0 } }; } }; diff --git a/public/ads.html b/public/ads.html index 0f95726..21df6fd 100644 --- a/public/ads.html +++ b/public/ads.html @@ -60,6 +60,7 @@ +
@@ -76,7 +77,7 @@ - + diff --git a/public/assets/ads-screen.js b/public/assets/ads-screen.js index d58967d..01dcc5b 100644 --- a/public/assets/ads-screen.js +++ b/public/assets/ads-screen.js @@ -2,7 +2,7 @@ // viewer, member zones and the partner network, and earn credits by viewing. Types are limited to the three Marty chose. (function () { const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog; - let D = null, EARN = null, TYPE = 'banner', SPINS = [], HOSTS = [], IMG = ''; + let D = null, EARN = null, TYPE = 'banner', SPINS = [], HOSTS = [], IMG = '', AIW = false; CR.mount({ active: 'ads', title: 'Ads', sub: 'loading', actions: '' }); const NOTE = { banner: 'Runs in the ad viewer, in every member zone on outside sites, and on the partner network. Views are timed on the server. Spends purchased or earned credits.', @@ -148,7 +148,7 @@ window.addEventListener('storage', e => { if (e.key === 'iap-view-done') earnRefresh(); }); $('earnClaim').addEventListener('click', async () => { try { const r = await api('/api/my/claim', {}); toast('+' + r.credited + ' credits' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Spend them on an ad.'); load(); } catch (e) { toast(e.message, true); } }); // -- composer - function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('fCap').parentElement.hidden = t === 'login'; + function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('aiRow').hidden = t !== 'text' || !AIW; $('fCap').parentElement.hidden = t === 'login'; const L = slotInfo(), full = t === 'login' && !L.free; const fb = $('fBudget'); if (t === 'login') { fb.dataset.keep = fb.dataset.keep || fb.value; fb.value = L.credits; fb.readOnly = true; } else { if (fb.readOnly && fb.dataset.keep) fb.value = fb.dataset.keep; delete fb.dataset.keep; fb.readOnly = false; } $('fGo').disabled = false; $('fGo').textContent = full ? 'Reserve the next slot' : 'Launch'; $('fGo').title = full ? 'All login-ad slots are taken: pay now for a place in line' : ''; @@ -185,6 +185,23 @@ setType(TYPE); }); $('fCancel').addEventListener('click', () => { $('composer').hidden = true; }); + // the AI ad writer (Marty 2026-11-17): 3 text ads the network hub writes only from the member's own page; picking one fills the + // headline and line to edit. Shown only when the hub answers it is on. + CR.get('/api/my/adwriter').then(w => { AIW = !!(w && w.on); if (!$('composer').hidden) setType(TYPE); }).catch(() => { AIW = false; }); + { let opts = []; + $('aiWrite').addEventListener('click', async () => { + const box = $('aiList'), url = $('fTarget').value.trim(); box.hidden = false; + if (!/^https?:\/\/\S+\.\S+/i.test(url)) { box.innerHTML = 'Put your link in Where the click goes first (starting with https://), or pick a spin link, then tap the button again.'; $('fTarget').focus(); return; } + $('aiWrite').disabled = true; box.innerHTML = 'Reading your page and writing 3 ads. This takes a few seconds...'; + let r; try { r = await api('/api/my/adwriter', { url, kind: 'text' }); } catch (e) { r = { error: e.message || 'The ad writer did not answer. Try again in a minute.' }; } + $('aiWrite').disabled = false; + if (r.error) { box.innerHTML = '' + esc(r.error) + ''; return; } + opts = r.options || []; + box.innerHTML = '
Tap one to use it. Check every word is true for your offer before you launch.' + (typeof r.left === 'number' ? ' Ad writes left today: ' + r.left + '.' : '') + '
' + + opts.map((o, i) => '').join(''); + box.querySelectorAll('button[data-ai]').forEach(b => b.addEventListener('click', () => { const o = opts[Number(b.dataset.ai)]; $('fTitle').value = o.headline; $('fBody').value = o.line || ''; box.hidden = true; preview(); toast('Filled in. Edit it as you like, then tap Launch.'); })); + }); + } $('fGo').addEventListener('click', async () => { const body = { type: TYPE, name: $('fName').value, targetUrl: $('fTarget').value.trim(), budget: Number($('fBudget').value), geo: $('fGeo').value }; if (TYPE !== 'login' && $('fCap').value) body.dailyCap = Number($('fCap').value); diff --git a/public/assets/pages-screen.js b/public/assets/pages-screen.js index 9fe0f1b..b0c36d4 100644 --- a/public/assets/pages-screen.js +++ b/public/assets/pages-screen.js @@ -88,6 +88,7 @@ // pasted provider forms: say at paste time which autoresponder the form posts to + (k === 'formEmbed' ? '' : '')).join(''); if ($('imgUpload')) { $('imgUpload').addEventListener('click', () => $('imgFile').click()); $('imgFile').addEventListener('change', () => { uploadFile($('imgFile').files[0]); $('imgFile').value = ''; }); drawImages(); } + aiHeadline(p); if ($('f-formEmbed')) { const fe = $('f-formEmbed'); const upd = () => providerNote(fe.value); fe.addEventListener('input', upd); fe.addEventListener('paste', () => setTimeout(upd, 0)); upd(); } // the Look panel: niche preset, design, colours, layout. Each change saves at once and the gallery/preview refresh. const d = p.design || {}; const setLook = async patch => { try { await api('/api/my/pages/' + p.id, patch); load(true); } catch (e) { toast(e.message, true); } }; @@ -101,6 +102,31 @@ $('layouts').querySelectorAll('button').forEach(b => b.addEventListener('click', () => setLook({ layout: b.dataset.l }))); if (!quiet && window.matchMedia('(max-width:900px)').matches) $('side').scrollIntoView({ behavior: 'smooth' }); } + // the AI ad writer on the headline (Marty 2026-11-17): the network hub reads the button link (or the scanned page) and suggests + // 3 headline + subhead pairs written only from it; picking one fills both fields to edit. Saved only with Save. + let AIW = null; + async function aiHeadline(p) { + const sub = $('f-sub'); if (!sub) return; + if (AIW === null) { try { const w = await CR.get('/api/my/adwriter'); AIW = !!(w && w.on); } catch (e) { AIW = false; } } + if (!AIW || !$('f-sub') || $('aiHead')) return; + const wrap = document.createElement('div'); wrap.id = 'aiHead'; wrap.style.margin = '0 0 10px'; + wrap.innerHTML = ' Reads the Button link page and suggests 3 headlines with a subhead, using only what that page says.'; + $('f-sub').closest('label').after(wrap); + let opts = []; + $('aiHeadBtn').addEventListener('click', async () => { + const box = $('aiHeadList'); box.hidden = false; + const url = (($('f-ctaUrl') && $('f-ctaUrl').value) || (p.scan && p.scan.url) || '').trim(); + if (!/^https?:\/\/\S+\.\S+/i.test(url)) { box.innerHTML = 'Put the offer link in the Button link field first (starting with https://), then tap the button again.'; return; } + $('aiHeadBtn').disabled = true; box.innerHTML = 'Reading the page and writing 3 headlines. This takes a few seconds...'; + let r; try { r = await api('/api/my/adwriter', { url, kind: 'page' }); } catch (e) { r = { error: e.message || 'The ad writer did not answer. Try again in a minute.' }; } + $('aiHeadBtn').disabled = false; + if (r.error) { box.innerHTML = '' + esc(r.error) + ''; return; } + opts = r.options || []; + box.innerHTML = '
Tap one to use it, then Save. Check every word is true for your offer.' + (typeof r.left === 'number' ? ' Writes left today: ' + r.left + '.' : '') + '
' + + opts.map((o, i) => '').join(''); + box.querySelectorAll('button[data-ai]').forEach(b => b.addEventListener('click', () => { const o = opts[Number(b.dataset.ai)]; $('f-headline').value = o.headline; if ($('f-sub')) $('f-sub').value = o.line || ''; box.hidden = true; toast('Filled in. Edit it as you like, then tap Save.'); })); + }); + } function collect(p) { const g = k => { const el = $('f-' + k); return el ? el.value : undefined; }; const c = {}; for (const [k] of F[p.type]) { if (k === 'ctaText' || k === 'ctaUrl') continue; c[k] = g(k); } c.cta = { text: g('ctaText'), url: g('ctaUrl') }; for (const k of ['bullets', 'pros', 'cons']) if (c[k] != null) c[k] = c[k].split('\n'); return c; } $('edSave').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p), title: ($('f-headline').value || p.title).slice(0, 100) }); toast('Saved'); load(true); } catch (e) { toast(e.message, true); } }); $('edPublish').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p) }); const r = await api('/api/my/pages/' + p.id, { status: p.status === 'published' ? 'draft' : 'published' }); toast(r.page.status === 'published' ? 'Live at ' + pageUrl(r.page) : 'Unpublished'); load(true); } catch (e) { toast(e.message, true); } }); diff --git a/public/index.html b/public/index.html index b744318..a10d4cc 100644 --- a/public/index.html +++ b/public/index.html @@ -226,5 +226,6 @@ + diff --git a/public/pages.html b/public/pages.html index 299380a..2b69150 100644 --- a/public/pages.html +++ b/public/pages.html @@ -74,6 +74,6 @@ - + diff --git a/qa/hubadwriter.test.mjs b/qa/hubadwriter.test.mjs new file mode 100644 index 0000000..050f3c3 --- /dev/null +++ b/qa/hubadwriter.test.mjs @@ -0,0 +1,43 @@ +// The network ad writer client (2026-11-17): node qa/hubadwriter.test.mjs +// A stand-in hub checks the signature and answers like network-hub lib/adwriter.js; no real hub, no model, no member. +import http from 'node:http'; +import crypto from 'node:crypto'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); +const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); +let pass = 0, fail = 0; +const ok = (c, m, extra) => { if (c) pass++; else { fail++; console.log('FAIL', m, extra !== undefined ? JSON.stringify(extra).slice(0, 300) : ''); } }; + +const SECRET = 's'.repeat(40); let seen = [], mode = 'good'; +const hub = http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => { + const sig = crypto.createHmac('sha256', SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex'); + r.setHeader('Content-Type', 'application/json'); + if (sig !== q.headers['x-hub-sig']) { r.statusCode = 401; return r.end('{"error":"unauthorized"}'); } + const j = JSON.parse(b); seen.push({ path: q.url, site: q.headers['x-hub-site'], body: j }); + if (q.url === '/v1/adwriter/status') return r.end(JSON.stringify(mode === 'off' ? { on: false, daily: 5 } : { on: true, daily: 5, left: j.member ? 3 : undefined })); + if (mode === 'limit') { r.statusCode = 429; return r.end(JSON.stringify({ ok: false, error: 'member_limit', code: 'member_limit', message: 'You have used your 5 ad writes for today.', left: 0 })); } + if (mode === 'slow') return; + r.end(JSON.stringify({ ok: true, options: [{ headline: 'One link for all your pages', line: 'Share one link that rotates your pages.' }], url: 'https://linkspin.app/', cached: false, left: 4 })); +}); }); +await new Promise(r => hub.listen(0, '127.0.0.1', r)); +process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = SECRET; delete process.env.HUB_SITE; delete process.env.AI_WRITER; +const aw = require(path.join(ROOT, 'hubadwriter.js')); + +ok(await aw.enabled(), 'on when the hub says on'); +ok(seen[0].path === '/v1/adwriter/status' && seen[0].site && seen[0].site !== '__SITE__', 'signed as this site', seen[0]); +let r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 }); +ok(r.ok && r.options.length === 1 && r.left === 4, 'options passed on', r); +ok(seen[1].body.member === 'member-1' && seen[1].body.limits.headline === 60 && seen[1].body.limits.line === 90 && seen[1].body.url === 'https://linkspin.app', 'member, url and this site\'s limits sent', seen[1].body); +mode = 'limit'; r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 }); +ok(r.error === 'You have used your 5 ad writes for today.' && r.status === 429 && r.left === 0, 'the hub message is shown as is', r); +const st = await aw.status('member-1'); ok(st.on && st.left === 3, 'status for a member (left today)', st); +mode = 'off'; aw._reset(); ok(!(await aw.enabled()), 'off when the hub says off'); +process.env.HUB_SECRET = 'w'.repeat(40); mode = 'good'; r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 }); +ok(r.code === 'hub' && /busy/.test(r.error), 'a refused signature: a friendly busy message', r); +aw._reset(); ok(!(await aw.enabled()), 'a refused signature hides the button'); +process.env.HUB_SECRET = SECRET; process.env.AI_WRITER = '0'; aw._reset(); const n0 = seen.length; ok(!(await aw.enabled()) && seen.length === n0, 'AI_WRITER=0 hides it without asking the hub', seen.length); +delete process.env.AI_WRITER; process.env.HUB_URL = 'http://127.0.0.1:1'; aw._reset(); ok(!(await aw.enabled()), 'an unreachable hub hides the button'); +hub.close(); +console.log('hubadwriter: ' + pass + ' passed, ' + fail + ' failed'); +process.exit(fail ? 1 : 0); diff --git a/server.js b/server.js index de9820b..db6bb70 100644 --- a/server.js +++ b/server.js @@ -50,6 +50,7 @@ const registry = require('./registry'); // network registry: who is who ac const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15) const loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event +const adwriter = require('./hubadwriter'); // the network AI ad writer, asked through the hub (2026-11-17): text ads + page headlines const hubsync = require('./hubsync'); // network hub link, inert unless HUB_ENABLED=1 (2026-11-12) const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22) let follow = null, followStore = null; @@ -904,7 +905,7 @@ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': ' '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2', '.gif': 'image/gif', '.webm': 'video/webm', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; -const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; +const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; function baseHeaders(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); @@ -4061,6 +4062,21 @@ const server = http.createServer(async (req, res) => { const r = b.remove ? audiences.remove(s.email, b.id) : b.id ? audiences.rename(s.email, b.id, b.name) : audiences.create(s.email, b.name); return json(res, r.error ? 400 : 200, r); } + // the AI ad writer (Marty 2026-11-17: "do it on the other sites too"): the hub reads the member's page and suggests 3 options written + // only from it. kind 'text' = a text ad (headline 60, one line 140); kind 'page' = a page builder headline (90) + subhead (200). + // Nothing is saved here: the member picks one, edits it and launches or saves it themselves. + if (p === '/api/my/adwriter' && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (req.method === 'GET') { const w = await adwriter.status(s.email); return json(res, 200, { on: !!w.on, daily: w.daily || 0, left: w.left }); } + if (!(await adwriter.enabled())) return json(res, 503, { error: 'The ad writer is switched off right now. You can still write it yourself.' }); + if (supportFlood('aiw:' + clientIp(req), 12, 3600000)) return json(res, 429, { error: 'Too many ad writes from this connection this hour. Try again later, or write it yourself.' }); + const b = await readBody(req); + const limits = b && b.kind === 'page' ? { headline: 90, line: 200 } : { headline: 60, line: 140 }; + const r = await adwriter.write(s.email, String((b && b.url) || '').trim().slice(0, 600), limits); + if (r.error) return json(res, r.status || 400, { error: r.error, code: r.code, left: r.left }); + return json(res, 200, { ok: true, options: r.options, url: r.url, cached: r.cached, left: r.left }); + } if (p === '/api/my/campaigns' && req.method === 'GET') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });