Network sign-in: the way back after signing in on InstantAdPay (Marty 2026-11-17)

networksso.js (the shared file, same in every network site): providers now also know every
site in the hub's GET /v1/sso-sites, ?return=<site>&to=/path links on IAP/LinkSpin remember
the way back, a missing wallet sends the member to the provider's wallet step first and then
back, and the deliberate-tap state lives 1 hour (was 20 minutes) so a sign-up has time.
Join links to InstantAdPay carry ?return=<this site>&to=/my.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-17 07:09:33 -06:00
parent 65cc5ea565
commit 828abce0fd
3 changed files with 134 additions and 19 deletions
+111 -14
View File
@@ -37,6 +37,17 @@
// Activity (Marty 2026-11-15, DownlineHydra "Wake it", the CRM score): a signed-in member's page load pings POST <hub>/v1/activity
// {email|wallet, kind 'visit'} at most once per member per day, fire and forget (HUB_URL + HUB_SECRET; HUB_ACTIVITY=0 turns it off).
// signOutEverywhere(session): POST <hub>/v1/sso/signout; the hub ends every hub sign-in of that person and tells hooked sites.
//
// ONE SITES LIST + THE WAY BACK (Marty 2026-11-17: "I logged in to Instant Ad Pay from Viral Ad Source, and it never had a return
// path back"). Before, each provider (IAP, LinkSpin) kept its own hand-written `wallets` list; a site missing from it (5xYourTeam
// 11-15, ViralAdSource 11-17) was refused at /sso/check and the member was dropped on the provider's dashboard with no way back.
// Sites list: a provider also knows every site in the hub's public GET <hub>/v1/sso-sites (HUB_SSO_SITES there; the same list the
// hub signs in for). Read at start, every 5 minutes, and once more (2 s at most) when an unknown site asks. Hand-written entries win.
// Return links: any provider page with ?return=<site>&to=/path (a known site only, never an open redirect) remembers the way back
// in nsso.ret (1 day) and reloads without the two parameters. Signed in already: straight back. After the email-code sign-in (and
// after the username step for a new account) the provider's dashboard goes to /sso/resume, which finishes it: /go/<site>?to=/path.
// No wallet yet (a wallet site needs one): with C.walletPath the member goes to the provider's wallet step first (nsso.wait), and
// afterWallet(req) gives the wallet-link answer its next hop, /sso/resume. The same holds for a deliberate tap (nsso.back).
'use strict';
const crypto = require('crypto');
const fs = require('fs');
@@ -47,8 +58,9 @@ const enabled = () => SECRET().length >= 32;
const TTL = 60 * 1000; // token life
const SKEW = 30 * 1000; // clock skew allowed between the two servers
const STATE_AGE = 300; // seconds: the state cookie
const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
const GO_STATE_AGE = 3600; // seconds: the state cookie on a deliberate tap (time to sign in, pick a username and link a wallet on the provider first; 20 minutes until 2026-11-17)
const BACK_AGE = 3600; // seconds: the provider remembers an unfinished deliberate check while the member signs in (20 minutes until 2026-11-17)
const RET_AGE = 86400; // seconds: a ?return=<site> link remembers the way back (2026-11-17)
const TRIED_AGE = 120; // seconds: one silent check per browser per 2 minutes (loop guard only; 30 minutes until 2026-11-15)
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
@@ -74,8 +86,25 @@ async function hubUp() {
return Date.now() - hubSeen < 120000;
}
// the hub's sign-in sites {site: base} (2026-11-17): providers answer every site the hub knows, not only their hand-written list
let hubSites = {}, hubSitesAt = 0, hubSitesAsking = null;
const SITE_RE = /^[a-z0-9_-]{1,64}$/, BASE_RE = /^https?:\/\/[a-z0-9.:-]+$/i;
function loadHubSites() {
if (hubSitesAsking) return hubSitesAsking;
if (!BASE_RE.test(HUB_BASE()) || typeof fetch !== 'function' || String(process.env.NSSO_HUB_SITES || '') === '0') return Promise.resolve();
hubSitesAt = Date.now();
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
hubSitesAsking = fetch(HUB_BASE() + '/v1/sso-sites', { signal: ac ? ac.signal : undefined }).then(r => (r.ok ? r.json() : null)).then(j => {
if (!j || !j.sites || typeof j.sites !== 'object') return;
const out = {}; for (const [k, v] of Object.entries(j.sites)) { const b = String(v || '').replace(/\/+$/, ''); if (SITE_RE.test(k) && BASE_RE.test(b)) out[k] = b; }
hubSites = out;
}).catch(() => {}).finally(() => { clearTimeout(tm); hubSitesAsking = null; });
return hubSitesAsking;
}
const freshSites = () => { if (C && C.wallet && Date.now() - hubSitesAt > 5 * 60 * 1000) loadHubSites(); };
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() }, walletPath?: the provider's wallet step }
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
@@ -167,6 +196,17 @@ function activity(w) {
const k = w.email || w.wallet; if (pinged.has(k)) return; pinged.set(k, 1);
hubCall('/v1/activity', Object.assign({ kind: 'visit' }, w), 5000).then(r => { if (r.status >= 500) pinged.delete(k); }).catch(() => { pinged.delete(k); });
}
// a signed-in request the site already answers (2026-11-16, Marty: "LinkSpin never reports activity"): /api/me, the dashboard
// heartbeat (/api/my/ping) and the admin portal call this, so a Control Room tab kept open for days, a browser that sends no
// Sec-Fetch headers and a wallet-only session still count the day's visit. The page-load ping in page() only sees full navigations.
// s = {email} and/or {address}. Same once-a-day rule as page(). -> true when a ping was due or already sent today.
function seen(s) {
try {
if (!C || !hubCreds()) return false;
const w = who(s && s.email ? s : s && s.address ? { address: s.address } : null); if (!w) return false;
activity(w); return true;
} catch (e) { return false; }
}
// a real top-level page load of a page (never an API call, an asset, a fetch, a bot or one of our own hops)
function pageLoad(req, p) {
if (req.method !== 'GET' || isBot(req)) return false;
@@ -221,7 +261,25 @@ const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/;
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); if (hubOn()) { hubSeen = 0; hubChecked = 0; hubUp().catch(() => {}); } }
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); if (hubOn()) { hubSeen = 0; hubChecked = 0; hubUp().catch(() => {}); } hubSites = {}; hubSitesAt = 0; if (C.wallet) loadHubSites(); }
// a site this provider answers for: its own list first, then the hub's (never itself, never the peer, which has its own path)
function siteBase(x) {
if (!C || !C.wallet || !SITE_RE.test(String(x || '')) || x === C.self || x === C.peer) return null;
if (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x)) return C.wallets[x];
if (Object.prototype.hasOwnProperty.call(hubSites, x)) { const b = hubSites[x]; return () => b; }
return null;
}
// an unknown site asking: ask the hub once more (at most every 30 s, 2 s at most) before refusing
async function siteBaseFresh(x) { let b = siteBase(x); if (!b && C && C.wallet && SITE_RE.test(String(x || '')) && Date.now() - hubSitesAt > 30000) { await loadHubSites(); b = siteBase(x); } return b; }
const siteName = x => NAMES[x] || ({ viraladsource: 'ViralAdSource', webworthit: 'WebWorthIt', stackpol: 'Stack POL' })[x] || x;
const retOf = req => { const m = /^([a-z0-9_-]{1,64})\|(\/.*)$/.exec(cookies(req)['nsso.ret'] || ''); return m ? { site: m[1], to: safePath(m[2], '/') } : null; };
// signed in here, on the way back to a site: its wallet step first when the site needs a wallet this account does not have yet
async function backHop(s, site, to, set) {
let w = null; try { w = await C.wallet(s); } catch (e) {}
if ((!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) && C.walletPath) { set.push(ck('nsso.wait', '1', BACK_AGE, true)); log('back: wallet step first', s.email, 'for ' + siteName(site)); return C.walletPath; }
return '/go/' + site + '?to=' + encodeURIComponent(to);
}
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
@@ -230,9 +288,24 @@ const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
async function handle(req, res, u) {
if (!C || req.method !== 'GET') return false;
const p = u.pathname;
if (C.wallet && u.searchParams.has('return') && !/^\/(sso|api|go)(\/|$)/.test(p)) { // a site's "sign in / join on <provider>" link: remember the way back (2026-11-17)
const site = String(u.searchParams.get('return') || '').toLowerCase(); const to = safePath(u.searchParams.get('to'), '/');
const clean = new URL(u.pathname + u.search, 'http://x.invalid'); clean.searchParams.delete('return'); clean.searchParams.delete('to');
const here = safePath(clean.pathname + clean.search, '/');
const base = isBot(req) ? null : await siteBaseFresh(site);
if (!base) return go(res, here); // unknown site (or a bot): the page itself, nothing remembered
let s = null; try { s = await C.member(req); } catch (e) {}
if (s && s.email) { // signed in here already: straight back (wallet step first when the site needs one)
const set = []; const hop = await backHop(s, site, to, set);
set.push(hop === C.walletPath ? ck('nsso.ret', site + '|' + to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
return go(res, hop, set);
}
log('return link remembered', null, 'for ' + siteName(site));
return go(res, here, [ck('nsso.ret', site + '|' + to, RET_AGE, true), ck('nsso.wait', '', 0, true)]);
}
const peerName = NAMES[C.peer] || C.peer;
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
const walletBase = siteBase; freshSites(); // the hand-written list, then the hub's sign-in sites (2026-11-17)
if (goTo && (goTo === C.peer || walletBase(goTo))) {
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
const to = safePath(u.searchParams.get('to'), '/');
@@ -266,17 +339,25 @@ async function handle(req, res, u) {
}
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
const clear = [ck('nsso.back', '', 0, true)];
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
const clear = [ck('nsso.back', '', 0, true), ck('nsso.wait', '', 0, true)];
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) { // no deliberate tap waiting: a ?return=<site> link may be (2026-11-17)
const ret = retOf(req);
if (!ret || !siteBase(ret.site)) return go(res, C.defaultPath, clear.concat(ck('nsso.ret', '', 0, true)));
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) return go(res, C.signinPath(C.defaultPath)); // not signed in yet: keep it for after the sign-in
const set = clear.slice(); const hop = await backHop(s, ret.site, ret.to, set);
set.push(hop === C.walletPath ? ck('nsso.ret', ret.site + '|' + ret.to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
log('back to ' + siteName(ret.site), s.email); return go(res, hop, set);
}
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')) + '&m=go', clear); // m=go: still a deliberate tap (the wallet step when one is missing)
}
if (p === '/sso/check') {
const st = String(u.searchParams.get('st') || '');
const to = safePath(u.searchParams.get('to'), '/');
const r = String(u.searchParams.get('r') || '');
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
const wb = r && r !== C.peer ? await siteBaseFresh(r) : null; // a wallet site asking: the token carries the wallet (the hub's sign-in sites too, 2026-11-17)
if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin)
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = siteName(aud);
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
let s = null; try { s = await C.member(req); } catch (e) {}
@@ -289,7 +370,13 @@ async function handle(req, res, u) {
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
}
let w = null;
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) {
if (u.searchParams.get('m') === 'go' && C.walletPath && !isBot(req)) { // a deliberate tap: link a wallet here first, then /sso/resume finishes the trip (2026-11-17)
log('check: no wallet on the account, wallet step first', s.email, 'for ' + forName);
const back = new URLSearchParams({ st, to, m: 'go' }); if (r) back.set('r', r);
return go(res, C.walletPath, [ck('nsso.back', back.toString(), BACK_AGE, true), ck('nsso.wait', '1', BACK_AGE, true)]);
}
log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
log('token issued', s.email, 'for ' + forName);
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
}
@@ -349,7 +436,17 @@ async function page(req, res, u) {
return false;
}
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
const pendingBack = req => !!cookies(req)['nsso.back'];
// true when this browser came here from a deliberate network tap (nsso.back) or a ?return=<site> link (nsso.ret) and still has to
// finish it after signing in. False while it waits on the wallet step (nsso.wait): the dashboard must not bounce it back and forth.
const pendingBack = req => { const c = cookies(req); return !!(c['nsso.back'] || retOf(req)) && !c['nsso.wait']; };
// the wallet was just linked: the next hop when a way back is waiting (2026-11-17), else null
const afterWallet = req => { const c = cookies(req); return c['nsso.back'] || retOf(req) ? '/sso/resume' : null; };
// the name of the site a member is on the way back to, for a line on the provider's dashboard; null when none
function backName(req) {
const c = cookies(req); const ret = retOf(req);
if (ret) return siteName(ret.site);
if (!c['nsso.back']) return null;
const r = new URLSearchParams(c['nsso.back']).get('r'); return siteName(r || (C && C.peer) || '') || null;
}
module.exports = { init, handle, page, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES, hubOn, hubCreds, signOutEverywhere, mintHub, verifyHub, _hubSeen: t => { hubSeen = t == null ? Date.now() : t; hubChecked = Date.now(); }, _pinged: pinged };
module.exports = { init, handle, page, seen, enabled, pendingBack, afterWallet, backName, siteBase, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES, hubOn, hubCreds, signOutEverywhere, mintHub, verifyHub, _hubSeen: t => { hubSeen = t == null ? Date.now() : t; hubChecked = Date.now(); }, _pinged: pinged, _hubSites: o => { if (o) { hubSites = o; hubSitesAt = Date.now(); } return hubSites; } };
+3 -2
View File
@@ -23,7 +23,7 @@
<h2 style="font-size:26px">Sign in</h2>
<p class="muted" style="margin:8px 0 0">Use your network account (one account across the network), or sign with your wallet: a free signature that cannot move funds.</p>
<div class="row" style="margin-top:16px"><a class="btn ink" href="/sso/start?mode=go&amp;to=/my">Sign in with my network account</a><button class="btn" id="walletBtn" type="button">Sign in with my wallet</button></div>
<p class="muted" style="font-size:14px;margin:12px 0 0">Wallet: SafePal or any other crypto wallet on Polygon. Not a member yet? <a id="joinLink" href="https://instantadpay.com/join">Join free</a>.</p>
<p class="muted" style="font-size:14px;margin:12px 0 0">Wallet: SafePal or any other crypto wallet on Polygon. Not a member yet? <a id="joinLink" href="https://instantadpay.com/?return=viraladsource&amp;to=%2Fmy">Join free</a>.</p>
</section>
<div id="dash" hidden>
<p class="muted" id="who" style="margin:8px 0 0"></p>
@@ -36,6 +36,7 @@
<label class="f">First line<input type="text" id="line1" maxlength="90" required></label>
<label class="f">Second line <small>optional</small><input type="text" id="line2" maxlength="90"></label>
<label class="f">Your link <small>an https page that loads, or one of your own LinkSpin spin links</small><input type="url" id="link" placeholder="https://" required></label>
<div class="picker" id="aiBox" hidden><div class="ph"><span>No words yet? Let AI write it from your link</span><button type="button" class="btn sm" id="aiWrite" style="min-height:30px">Write my ad from my link</button></div><p class="muted" id="aiHelp" style="margin:0;padding:8px 12px;font-size:13px">Put your link in the box above first. We read that page and suggest 3 ads using only what it says. Pick one to fill in your headline and first line, then change any words you like. Nothing is posted until you tap Post.</p><div id="aiList"></div></div>
<div class="picker" id="picker"><div class="ph"><span>Use one of my spin links</span><button type="button" class="btn sm" id="loadSpins" style="min-height:30px">Show my spin links</button></div><div id="spinList"></div></div>
<label class="row" style="gap:8px;font-size:14px"><input type="checkbox" id="track" checked> Track clicks with LinkSpin (a tracked link on your own LinkSpin account)</label>
<button class="btn coral" type="submit" id="saveAd">Post my free ad</button>
@@ -67,6 +68,6 @@
<script src="/assets/common.js?v=2"></script>
<script src="/assets/chat.js?v=1" defer></script>
<script src="/assets/wallet.js?v=2"></script>
<script src="/assets/my.js?v=2"></script>
<script src="/assets/my.js?v=20261117a"></script>
</body>
</html>
+20 -3
View File
@@ -33,6 +33,7 @@ const proof = require('./proof');
const netsites = require('./netsites');
const lstrack = require('./lstrack');
const chatbot = require('./chatbot');
const adwriter = require('./adwriter');
const PUB = path.join(__dirname, 'public');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
@@ -187,7 +188,10 @@ function issueTicket(req, page, shown, src, via) {
return t;
}
const todayStats = () => { const t = store.today(); return { views: t.views || 0, vclicks: t.vclicks || 0, reshares: t.reshares || 0, joins: t.confirms || 0, ads: store.liveAds().length }; };
const joinUrl = ref => ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join('');
// a join link to InstantAdPay or LinkSpin carries the way back here (2026-11-17, Marty: "it never had a return path back"): the
// provider remembers ?return=<this site>&to=/my and, after the sign-up or sign-in (and the wallet step), sends the member back
const withReturn = url => { try { const x = new URL(url); if (!/^(www\.)?(instantadpay\.com|linkspin\.app)$/.test(x.hostname) && x.origin !== new URL(C.iapBase).origin) return url; x.searchParams.set('return', C.siteId); x.searchParams.set('to', '/my'); return x.toString(); } catch (e) { return url; } };
const joinUrl = ref => withReturn(ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join(''));
const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/gi;
function clickLink(a, placement) {
const l = String(a.link || ''); if (!l.match(MACRO)) return l;
@@ -271,7 +275,8 @@ const server = http.createServer(async (req, res) => {
return json(res, 200, { site: C.site, siteName: C.siteName, staging: C.staging, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
boost: C.boost, split: live ? { resharerBps: live.resharerBps, potBps: live.potBps, levelBps: live.levelBps, maxDepth: 20, live: true } : Object.assign({ proposal: true }, C.split),
reward: { cents: C.reward.cents, dailyCap: C.reward.dailyCap, payouts: C.reward.payouts, tiers: C.reward.tiers, proposal: true }, credits: C.credits, visitSeconds: C.visitSeconds, ad: C.ad,
sso: networksso.enabled() || networksso.hubOn(), shop: { live: shop.watching() && shop.signerOn(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl('') });
sso: networksso.enabled() || networksso.hubOn(), shop: { live: shop.watching() && shop.signerOn(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl(''),
aiWriter: adwriter.enabled() ? { daily: adwriter.dailyCap() } : null });
}
// everything a page shows, with its visit ticket. page=front|share|other, s=<share code> on share pages
if (p === '/api/wire' && req.method === 'GET') {
@@ -472,6 +477,17 @@ const server = http.createServer(async (req, res) => {
catch (e) { console.error('order failed:', String(e && e.message || e).slice(0, 200)); return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
// the AI ad writer (2026-11-17): 3 suggested ads written only from the member's own page; nothing is posted (adwriter.js)
if (p === '/api/my/adwriter' && req.method === 'POST') {
if (!adwriter.enabled()) return json(res, 503, { error: adwriter.MSG.off });
if (limited(req, 'adwriter', 12, 3600000)) return json(res, 429, { error: 'Too many ad writes from this connection this hour. Try again later, or write your ad yourself.' });
const m = store.member(me); await verifyNet(me).catch(() => {});
if (!netVerified(m)) return json(res, 403, { error: 'The ad writer is for network members. Sign in with your network account first.' });
const b = await readBody(req);
const r = await adwriter.write(me, String(b.url || '').trim().slice(0, 600));
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 });
}
return json(res, 404, { error: 'Not found' });
}
@@ -484,7 +500,7 @@ const server = http.createServer(async (req, res) => {
today: store.today(), totals: S.totals, members: store.members().length, ads: { live: store.liveAds().length, all: store.ads().length }, shares: S.shares.length,
rows: { visits: store.visits().length, clicks: store.clicks().length, signups: store.signups().length, rewards: store.rewards().length },
signup: signup.view(), shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), sso: { hub: networksso.hubOn(), pairwise: networksso.enabled() },
linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length, adWriter: adwriter.view() });
}
if (p === '/api/admin/signups' && req.method === 'GET') {
const st0 = String(u.searchParams.get('status') || '');
@@ -551,6 +567,7 @@ const server = http.createServer(async (req, res) => {
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
if (C.reward.payouts) setInterval(() => signup.payDue().catch(() => {}), 60000).unref();
chatbot.init();
adwriter.init({ store, ad: C.ad });
lstrack.init(C, store);
{ let busy = false; const tick = () => { if (busy) return; busy = true; lstrack.sweep(25).catch(() => {}).finally(() => { busy = false; }); };
setTimeout(tick, Number(process.env.LS_SWEEP_FIRST_MS || 20000)).unref(); setInterval(tick, Number(process.env.LS_SWEEP_MS || 120000)).unref(); }