// WebWorthIt: a read-only contract + website risk check (staging at wwi.saasy.top, Marty 2026-11-16). // POST /api/check queues a job (jobs.js) and returns an id; GET /api/check/:id shows the steps and the result. // Free check = short scorecard (DeepSeek v4.1 Flash). Deep report = full report (Opus 5.5), unlocked in staging by the test code // (WWI_TEST_CODE) or a voucher. NO real payments in staging: the pricing buttons say "Payments arrive at launch". // Findings are public facts (tagged, with sources); scores, grade and verdict are our opinion from the published rubric. // Network: hub sign-in (networksso.js, HUB_SSO=on), sponsor line from the hub (hubline.js), hub events (hubevents.js), // network footer (netsites.js), site assistant (chatbot.js + chatcore/kb/netkb, NETKB=0 in staging). 'use strict'; const http = require('http'); const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data'); fs.mkdirSync(DATA_DIR, { recursive: true }); const docstore = require('./docstore'); docstore.install(DATA_DIR); const db = require('./db'); const jobs = require('./jobs'); const website = require('./website'); const sponsor = require('./sponsor'); const networksso = require('./networksso'); const hubpeople = require('./hubpeople'); const hubevents = require('./hubevents'); const netsites = require('./netsites'); const chatbot = require('./chatbot'); const PORT = Number(process.env.PORT || 3000); const STAGING = process.env.STAGING === '1'; const SITE_HOST = process.env.SITE_HOST || 'webworthit.com'; const IS_PROD = process.env.NODE_ENV === 'production'; const PUB = path.join(__dirname, 'public'); const FREE_PER_DAY = 3; const SECRET = (() => { if (process.env.SESSION_SECRET) return process.env.SESSION_SECRET; const f = path.join(DATA_DIR, '.secret'); try { return fs.readFileSync(f, 'utf8').trim(); } catch (e) {} const s = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, s, { mode: 0o600 }); } catch (e) {} return s; })(); const hmac = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex'); const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/; const ID_RE = /^[A-Za-z0-9]{12}$/; // ad zones: LinkSpin zone ids by placement (WWI_ZONES JSON, e.g. {"hero":"ls-xxxx","result":"ls-..","how":"ls-..","foot":"ls-..","side":"ls-.."}). Empty = no ad shown. const ZONES = (() => { try { const z = JSON.parse(process.env.WWI_ZONES || '{}'); return Object.fromEntries(Object.entries(z).filter(([k, v]) => /^[a-z]{2,12}$/.test(k) && /^ls-[a-z0-9]{4,12}$/.test(v))); } catch (e) { return {}; } })(); const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' }; const CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https:; connect-src 'self'; font-src 'self' https://fonts.gstatic.com; frame-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'self'"; // the ad frame page (/f/n.html) is the only place a third-party tag runs, inside its own iframe const CSP_FRAME = "default-src 'none'; script-src 'self' https://linkspin.app; img-src https: data:; style-src 'unsafe-inline'; connect-src https://linkspin.app; frame-src https:; base-uri 'none'; frame-ancestors 'self'"; const headers = (extra, csp) => Object.assign({ 'Content-Security-Policy': csp || CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'SAMEORIGIN' }, STAGING ? { 'X-Robots-Tag': 'noindex, nofollow' } : {}, extra || {}); function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); } function sendFile(res, file, extra, csp) { fs.readFile(file, (err, data) => { if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } const ext = path.extname(file).toLowerCase(); res.writeHead(200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store' : 'public, max-age=600' }, extra), csp)); res.end(data); }); } function readBody(req) { return new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n > 64 * 1024) { req.destroy(); return; } ch.push(c); }); req.on('end', () => { try { const b = Buffer.concat(ch).toString('utf8'); resolve(b ? JSON.parse(b) : {}); } catch (e) { resolve({}); } }); req.on('error', () => resolve({})); }); } function readRaw(req) { return new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n < 512 * 1024) ch.push(c); }); req.on('end', () => resolve(Buffer.concat(ch))); req.on('error', () => resolve(Buffer.alloc(0))); }); } function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; } const cookie = (name, val, age, httpOnly) => name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (IS_PROD ? '; Secure' : ''); function ip(req) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean); return (x.length ? x[x.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, ''); } const ipHash = req => hmac('ip|' + ip(req)).slice(0, 24); const buckets = new Map(); function limited(req, name, max, ms) { const k = name + ':' + ip(req); const now = Date.now(); let b = buckets.get(k); if (!b || now - b.t > ms) { b = { t: now, n: 0 }; buckets.set(k, b); } if (buckets.size > 50000) buckets.clear(); return ++b.n > max; } const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || ''); return t.length >= 16 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); }; const today = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const signed = v => v + '.' + hmac('c|' + v).slice(0, 32); const unsign = s => { const i = String(s || '').lastIndexOf('.'); if (i < 0) return null; const v = s.slice(0, i); return signed(v) === s ? v : null; }; // ---- who is asking: a network member (session) or a browser (holder token) ---- async function member(req) { const sid = cookies(req)['wwi.sid']; if (!sid || !/^[a-f0-9]{48}$/.test(sid)) return null; const s = await db.one('SELECT s.email, s.created, m.username, m.wallet, m.hub_id, m.sponsor FROM sessions s LEFT JOIN members m ON m.email = s.email WHERE s.id = ? AND s.expires > ?', [sid, Date.now()]); return s || null; } function holderOf(req, m) { if (m) return 'm:' + m.email; const t = unsign(cookies(req)['wwi.t']); return t ? 't:' + t : null; } const unlocked = req => unsign(cookies(req)['wwi.unlock']) === 'test'; async function freeLeft(req) { const r = await db.one('SELECT n FROM daily_free WHERE day = ? AND ip_hash = ?', [today(), ipHash(req)]); return Math.max(0, FREE_PER_DAY - (r ? r.n : 0)); } async function creditsOf(holder) { if (!holder) return { deep: 0, free_extra: 0 }; return (await db.one('SELECT deep, free_extra FROM credits WHERE holder = ?', [holder])) || { deep: 0, free_extra: 0 }; } // ---- network sign-in (hub provider; pairwise fallback is off unless NETWORK_SSO_SECRET is set AND the peer lists this site) ---- networksso.init({ self: 'webworthit', hubSite: 'webworthit', peer: 'iap', peerBase: () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''), from: { iap: () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''), linkspin: () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '') }, isProd: IS_PROD, dataDir: DATA_DIR, defaultPath: '/my', db: { enabled: () => true, q: (s, a) => db.q(s, a) }, member: async req => { const m = await member(req); return m ? { email: m.email } : null; }, accept: async email => (email ? { ok: true } : { fallback: 'no email in the token' }), signIn: async (email, req, v) => { email = String(email || '').trim().toLowerCase(); if (!email) return null; let p = null; const r = await hubpeople.resolve({ email }).catch(() => ({ ok: false })); if (r.ok && r.person && !r.person.blocked) p = r.person; if (r.ok && r.person && r.person.blocked) return null; const username = p && p.username ? String(p.username) : (v && v.name && NAME_RE.test(v.name) ? v.name : null); const wallet = (p && hubpeople.wallet(p)) || (v && v.wallet && ADDR_RE.test(v.wallet) ? v.wallet.toLowerCase() : null); await db.q('INSERT INTO members (email, hub_id, username, wallet, sponsor, created, last_seen) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE hub_id = COALESCE(VALUES(hub_id), hub_id), username = COALESCE(VALUES(username), username), wallet = COALESCE(VALUES(wallet), wallet), sponsor = COALESCE(VALUES(sponsor), sponsor), last_seen = VALUES(last_seen)', [email, p ? p.id || null : null, username, wallet, p && p.sponsor ? p.sponsor.username || null : null, Date.now(), Date.now()]); const sid = crypto.randomBytes(24).toString('hex'); await db.q('INSERT INTO sessions (id, email, created, expires) VALUES (?,?,?,?)', [sid, email, Date.now(), Date.now() + 30 * 86400000]); return cookie('wwi.sid', sid, 30 * 86400, true); }, landing: to => to, signinPath: to => '/my?signin=1&to=' + encodeURIComponent(to || '/my') }); hubevents.init({ dataDir: DATA_DIR, site: 'webworthit', end: async who => { const rows = await db.q('SELECT s.id, s.email, s.created, m.hub_id, m.wallet FROM sessions s LEFT JOIN members m ON m.email = s.email'); const ids = rows.filter(s => s.created < who.before && who.match({ email: s.email, hubId: s.hub_id, wallet: s.wallet, address: s.wallet })).map(s => s.id); if (ids.length) await db.q('DELETE FROM sessions WHERE id IN (?)', [ids]); return ids.length; } }); // ---- views ---- const SHORT = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : ''; function publicView(c, opts) { const steps = c.steps_json ? JSON.parse(c.steps_json) : {}; const rep = c.report_json ? JSON.parse(c.report_json) : null; const E = c.evidence_json ? JSON.parse(c.evidence_json) : null; const site = c.site_json ? JSON.parse(c.site_json) : null; const v = { id: c.id, kind: c.kind, status: c.status, created: c.created, website: c.website, chain: c.chain, chainName: (jobs.CHAINS[c.chain] || {}).name, address: c.address, pickedNote: c.picked_note, steps: jobs.STEPS.map(k => Object.assign({ key: k, name: jobs.STEP_NAMES[k] }, steps[k] || { state: 'waiting' })), queuePos: jobs.qpos(c.id), error: c.status === 'failed' ? c.error : null, label: c.public_label, isPublic: !!c.is_public }; if (c.status !== 'done') return v; v.timings = c.timings_json ? JSON.parse(c.timings_json) : null; v.cost = Number(c.cost_usd) || 0; v.model = c.model; v.facts = c.facts_json ? JSON.parse(c.facts_json) : []; v.factcheck = c.factcheck_json ? JSON.parse(c.factcheck_json) : null; v.site = site; v.hasShot = !!(site && site.ok); if (E) v.chainRead = { block: E.read_at && E.read_at.block, time: E.read_at && E.read_at.time_ct, window: E.window, explorer: E.explorer, gaps: E.gaps, notes: E.notes, isContract: E.is_contract, kind: E.kind, name: Object.values(E.verification || {}).map(x => x.name).filter(Boolean)[0] || null }; if (rep) { v.grade = rep.grade; const r = rep.report; if (c.kind === 'free' || !opts.full) v.report = { verdict: r.verdict, scores: r.scores, top_findings: r.top_findings, site_vs_code: r.site_vs_code }; else v.report = r; } return v; } async function startCheck(req, res, b, m) { const kind = b.kind === 'deep' ? 'deep' : 'free'; let site = b.website ? website.normalizeUrl(b.website) : null; if (b.website && !site) return json(res, 400, { error: 'That website address does not look right. Use the full address, like https://example.com' }); const address = String(b.address || '').trim(); if (address && !ADDR_RE.test(address)) return json(res, 400, { error: 'A contract address is 0x followed by 40 letters and numbers.' }); const chain = jobs.CHAINS[b.chain] ? b.chain : 'bsc'; if (!site && !address) return json(res, 400, { error: 'Fill in a website, a contract address, or both.' }); if (site && !(await website.hostOk(new URL(site).hostname))) return json(res, 400, { error: 'That website is not a public internet address.' }); if (limited(req, 'check', 12, 60 * 60000)) return json(res, 429, { error: 'Too many checks from this connection in the last hour. Try again later.' }); const holder = holderOf(req, m); const ih = ipHash(req); let via = null; if (kind === 'free') { if (!unlocked(req)) { const left = await freeLeft(req); if (left <= 0) { const cr = await creditsOf(holder); if (!(cr.free_extra > 0)) return json(res, 429, { error: 'You have used your 3 free checks for today. They come back tomorrow (Central time).', freeLeft: 0 }); await db.q('UPDATE credits SET free_extra = free_extra - 1, updated = ? WHERE holder = ? AND free_extra > 0', [Date.now(), holder]); via = 'voucher credit'; } else { await db.q('INSERT INTO daily_free (day, ip_hash, n) VALUES (?,?,1) ON DUPLICATE KEY UPDATE n = n + 1', [today(), ih]); } } } else { const cr = await creditsOf(holder); if (cr.deep > 0) { const r = await db.q('UPDATE credits SET deep = deep - 1, updated = ? WHERE holder = ? AND deep > 0', [Date.now(), holder]); if (!r.affectedRows) return json(res, 409, { error: 'No deep report credit left.' }); via = 'credit'; } else if (unlocked(req)) via = 'test_code'; else return json(res, 402, { error: STAGING ? 'Deep reports need the staging test code or a voucher. Payments arrive at launch.' : 'Deep reports need a payment or a voucher.' }); } const id = jobs.newId(); await db.q('INSERT INTO checks (id, created, ip_hash, holder, member, kind, website, chain, address, status, steps_json, parent_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', [id, Date.now(), ih, holder, m ? m.email : null, kind, site, chain, address ? address.toLowerCase() : null, 'queued', '{}', ID_RE.test(b.from || '') ? b.from : null]); if (kind === 'deep' && via === 'test_code') { const ref = unsign(cookies(req)['wwi.ref']); await sponsor.record({ buyer: m ? { email: m.email, username: m.username, wallet: m.wallet } : null, ref, item: 'deep1', via: 'test_code', checkId: id, note: 'staging test-code deep report' }).catch(e => console.error('sponsor record', e.message)); if (b.watch) await sponsor.record({ buyer: m ? { email: m.email, username: m.username, wallet: m.wallet } : null, ref, item: 'watch', via: 'test_code', checkId: id, note: 'staging test-code watch add-on (alerts arrive at launch)' }).catch(() => {}); } jobs.enqueue(id); return json(res, 200, { id, kind, via }); } const PAGES = { '/': 'index.html', '/my': 'my.html', '/admin': 'admin.html', '/privacy': 'privacy.html', '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/rubric': 'rubric.html' }; const server = http.createServer(async (req, res) => { let u; try { u = new URL(req.url, 'http://x'); } catch (e) { res.writeHead(400); return res.end(); } const p = u.pathname; try { if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files', jobs: { running: jobs.running(), queued: jobs.queued() } }); if (req.method === 'GET' && await networksso.page(req, res, u)) return; if (req.method === 'GET' && (p.startsWith('/sso/') || p.startsWith('/go/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return; if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin })) return; if (p === '/api/hub/events' && req.method === 'POST') { const raw = await readRaw(req); const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body); } if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res); // pages if (req.method === 'GET' && (PAGES[p] || /^\/c\/[A-Za-z0-9]{12}$/.test(p))) { const set = []; const ck = cookies(req); if (!unsign(ck['wwi.t'])) set.push(cookie('wwi.t', signed(crypto.randomBytes(12).toString('hex')), 365 * 86400, true)); const ref = u.searchParams.get('ref'); if (ref && NAME_RE.test(ref)) set.push(cookie('wwi.ref', signed(ref.toLowerCase()), 30 * 86400, true)); return sendFile(res, path.join(PUB, PAGES[p] || 'report.html'), set.length ? { 'Set-Cookie': set } : null); } if (req.method === 'GET' && (p === '/f/n.html' || p === '/f/n.js')) return sendFile(res, path.join(PUB, 'f', p.slice(3)), { 'Cache-Control': 'public, max-age=600' }, CSP_FRAME); if (req.method === 'GET' && (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/robots.txt' || p === '/favicon.ico')) { const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? 'art/mark.svg' : p)); if (!f.startsWith(PUB)) { res.writeHead(403); return res.end(); } return sendFile(res, f); } // api if (p === '/api/config' && req.method === 'GET') { const m = await member(req); const holder = holderOf(req, m); const cr = await creditsOf(holder); return json(res, 200, { staging: STAGING, freeLeft: unlocked(req) ? null : await freeLeft(req), freePerDay: FREE_PER_DAY, unlocked: unlocked(req), credits: cr, member: m ? { username: m.username, wallet: m.wallet ? SHORT(m.wallet) : null, sponsor: m.sponsor, refLink: m.username ? 'https://' + SITE_HOST + '/?ref=' + encodeURIComponent(m.username) : null } : null, sso: networksso.hubOn(), zones: ZONES, prices: sponsor.ITEMS, sponsorPct: { levels: sponsor.LEVEL_PCT, company: sponsor.COMPANY_PCT } }); } if (p === '/api/check' && req.method === 'POST') { const b = await readBody(req); return startCheck(req, res, b, await member(req)); } let mm; if ((mm = /^\/api\/check\/([A-Za-z0-9]{12})$/.exec(p)) && req.method === 'GET') { const c = await db.one('SELECT * FROM checks WHERE id = ?', [mm[1]]); if (!c) return json(res, 404, { error: 'No check with that id.' }); return json(res, 200, publicView(c, { full: true })); } if ((mm = /^\/api\/check\/([A-Za-z0-9]{12})\/shot\.jpg$/.exec(p)) && req.method === 'GET') { const s = await db.one('SELECT mime, bytes FROM screenshots WHERE check_id = ?', [mm[1]]); if (!s) { res.writeHead(404, headers()); return res.end(); } res.writeHead(200, headers({ 'Content-Type': s.mime, 'Cache-Control': 'public, max-age=86400' })); return res.end(s.bytes); } if ((mm = /^\/api\/check\/([A-Za-z0-9]{12})\/evidence$/.exec(p)) && req.method === 'GET') { const c = await db.one('SELECT pack_md FROM checks WHERE id = ?', [mm[1]]); if (!c || !c.pack_md) return json(res, 404, { error: 'No evidence pack for this check.' }); res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' })); return res.end(c.pack_md); } if (p === '/api/network-checks' && req.method === 'GET') { const rows = await db.q("SELECT id, kind, chain, address, public_label, report_json, finished FROM checks WHERE is_public = 1 AND status = 'done' ORDER BY finished DESC LIMIT 60"); return json(res, 200, { checks: rows.map(r => { const g = r.report_json ? JSON.parse(r.report_json).grade : null; return { id: r.id, kind: r.kind, chain: r.chain, address: r.address, label: r.public_label, grade: g ? g.grade : null, overall: g ? g.overall : null, finished: r.finished }; }) }); } if (p === '/api/unlock' && req.method === 'POST') { if (limited(req, 'unlock', 8, 15 * 60000)) return json(res, 429, { error: 'Too many tries. Wait 15 minutes.' }); const b = await readBody(req); const code = String(b.code || '').trim(); const want = String(process.env.WWI_TEST_CODE || ''); if (!want || code.length !== want.length || !crypto.timingSafeEqual(Buffer.from(code), Buffer.from(want))) return json(res, 403, { error: 'That code is not right.' }); await db.q('INSERT INTO unlock_codes (code_hash, label, created, uses) VALUES (?,?,?,1) ON DUPLICATE KEY UPDATE uses = uses + 1', [crypto.createHash('sha256').update(code).digest('hex'), 'WWI_TEST_CODE', Date.now()]); return json(res, 200, { ok: true }, { 'Set-Cookie': cookie('wwi.unlock', signed('test'), 30 * 86400, true) }); } if (p === '/api/lock' && req.method === 'POST') return json(res, 200, { ok: true }, { 'Set-Cookie': cookie('wwi.unlock', '', 0, true) }); if (p === '/api/redeem' && req.method === 'POST') { if (limited(req, 'redeem', 6, 15 * 60000)) return json(res, 429, { error: 'Too many tries. Wait 15 minutes.' }); const b = await readBody(req); const code = String(b.code || '').trim().toUpperCase(); if (!/^[A-Z0-9-]{4,40}$/.test(code)) return json(res, 400, { error: 'That code is not right.' }); const m = await member(req); const holder = holderOf(req, m); if (!holder) return json(res, 400, { error: 'Reload the page and try again.' }); const pc = await db.one('SELECT * FROM promo_codes WHERE code = ?', [code]); if (!pc || pc.disabled) return json(res, 404, { error: 'That code is not right.' }); if (pc.expires && pc.expires < Date.now()) return json(res, 410, { error: 'That code has expired.' }); if (pc.per_holder_once && await db.one('SELECT id FROM promo_redemptions WHERE code = ? AND holder = ?', [code, holder])) return json(res, 409, { error: 'You already used this code.' }); const r = await db.q('UPDATE promo_codes SET uses = uses + 1 WHERE code = ? AND uses < max_uses AND disabled = 0', [code]); if (!r.affectedRows) return json(res, 410, { error: 'That code has been used up.' }); const col = pc.kind === 'deep' ? 'deep' : 'free_extra'; await db.q('INSERT INTO credits (holder, ' + col + ', updated) VALUES (?,?,?) ON DUPLICATE KEY UPDATE ' + col + ' = ' + col + ' + VALUES(' + col + '), updated = VALUES(updated)', [holder, pc.amount, Date.now()]); await db.q('INSERT INTO promo_redemptions (code, holder, at, kind, amount, ip_hash) VALUES (?,?,?,?,?,?)', [code, holder, Date.now(), pc.kind, pc.amount, ipHash(req)]); return json(res, 200, { ok: true, kind: pc.kind, amount: pc.amount, credits: await creditsOf(holder) }); } if (p === '/api/test-purchase' && req.method === 'POST') { if (!unlocked(req)) return json(res, 403, { error: 'Payments arrive at launch.' }); const b = await readBody(req); const item = sponsor.ITEMS[b.item] ? b.item : null; if (!item || item === 'watch') return json(res, 400, { error: 'Unknown item.' }); const m = await member(req); const holder = holderOf(req, m); const r = await sponsor.record({ buyer: m ? { email: m.email, username: m.username, wallet: m.wallet } : null, ref: unsign(cookies(req)['wwi.ref']), item, via: 'test_code', note: 'staging test purchase' }); const n = item === 'deep10' ? 10 : 1; await db.q('INSERT INTO credits (holder, deep, updated) VALUES (?,?,?) ON DUPLICATE KEY UPDATE deep = deep + VALUES(deep), updated = VALUES(updated)', [holder, n, Date.now()]); return json(res, 200, { ok: true, credits: await creditsOf(holder), split: r.split }); } if (p === '/api/me' && req.method === 'GET') { const m = await member(req); if (!m) return json(res, 200, { member: null, sso: networksso.hubOn() }); const checks = await db.q('SELECT id, kind, website, chain, address, status, created FROM checks WHERE member = ? ORDER BY created DESC LIMIT 30', [m.email]); return json(res, 200, { member: { username: m.username, wallet: m.wallet ? SHORT(m.wallet) : null, sponsor: m.sponsor, refLink: m.username ? 'https://' + SITE_HOST + '/?ref=' + encodeURIComponent(m.username) : null }, checks, credits: await creditsOf(holderOf(req, m)) }); } if (p === '/api/signout' && req.method === 'POST') { const sid = cookies(req)['wwi.sid']; if (sid) await db.q('DELETE FROM sessions WHERE id = ?', [sid]); return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('wwi.sid', '', 0, true), networksso.offCookie()] }); } // admin if (p.startsWith('/api/admin/')) { if (!isAdmin(req)) return json(res, 401, { error: 'Admin token needed.' }); if (p === '/api/admin/overview' && req.method === 'GET') { const checks = await db.q('SELECT id, created, kind, website, chain, address, status, step, model, cost_usd, tokens_in, tokens_out, pack_chars, timings_json, error, is_public, public_label, member, factcheck_json IS NOT NULL fc FROM checks ORDER BY created DESC LIMIT 200'); const purchases = await db.q('SELECT * FROM purchases ORDER BY at DESC LIMIT 200'); const promos = await db.q('SELECT * FROM promo_codes ORDER BY created DESC'); const redemptions = await db.q('SELECT * FROM promo_redemptions ORDER BY at DESC LIMIT 300'); const cost = await db.one('SELECT COUNT(*) n, SUM(cost_usd) usd FROM checks'); return json(res, 200, { checks, purchases: purchases.map(x => Object.assign(x, { line: JSON.parse(x.line_json || 'null'), split: JSON.parse(x.split_json || 'null') })), promos, redemptions, cost, staging: STAGING, zones: ZONES, sso: networksso.hubOn(), hub: hubpeople.view ? hubpeople.view() : null }); } if (p === '/api/admin/promo' && req.method === 'POST') { const b = await readBody(req); const code = String(b.code || crypto.randomBytes(5).toString('hex')).trim().toUpperCase(); if (!/^[A-Z0-9-]{4,40}$/.test(code)) return json(res, 400, { error: 'Code: 4 to 40 letters, numbers or dashes.' }); const kind = b.kind === 'deep' ? 'deep' : 'free'; const amount = Math.max(1, Math.min(100, parseInt(b.amount, 10) || 1)); const maxUses = Math.max(1, Math.min(100000, parseInt(b.maxUses, 10) || 1)); const exp = b.expires ? Date.parse(b.expires) : null; await db.q('INSERT INTO promo_codes (code, kind, amount, max_uses, per_holder_once, expires, note, created) VALUES (?,?,?,?,?,?,?,?)', [code, kind, amount, maxUses, b.perHolderOnce === false ? 0 : 1, isFinite(exp) ? exp : null, String(b.note || '').slice(0, 300), Date.now()]); return json(res, 200, { ok: true, code }); } if (p === '/api/admin/promo/disable' && req.method === 'POST') { const b = await readBody(req); await db.q('UPDATE promo_codes SET disabled = ? WHERE code = ?', [b.enable ? 0 : 1, String(b.code || '').toUpperCase()]); return json(res, 200, { ok: true }); } if (p === '/api/admin/publish' && req.method === 'POST') { const b = await readBody(req); await db.q('UPDATE checks SET is_public = ?, public_label = ? WHERE id = ?', [b.public ? 1 : 0, String(b.label || '').slice(0, 120) || null, String(b.id || '')]); return json(res, 200, { ok: true }); } if (p === '/api/admin/check' && req.method === 'POST') { // admin-run check (network scorecards): no daily limit, deep allowed, optional public label; nothing is paid or recorded as a sale const b = await readBody(req); const kind = b.kind === 'deep' ? 'deep' : 'free'; if (!ADDR_RE.test(String(b.address || '')) && !b.website) return json(res, 400, { error: 'address or website' }); const id = jobs.newId(); await db.q('INSERT INTO checks (id, created, ip_hash, holder, kind, website, chain, address, status, steps_json, is_public, public_label) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', [id, Date.now(), 'admin', 'admin', kind, b.website ? website.normalizeUrl(b.website) : null, jobs.CHAINS[b.chain] ? b.chain : 'bsc', b.address ? String(b.address).toLowerCase() : null, 'queued', '{}', b.public ? 1 : 0, b.label ? String(b.label).slice(0, 120) : null]); jobs.enqueue(id); return json(res, 200, { id }); } return json(res, 404, { error: 'Not found' }); } if (req.method === 'GET' && !p.startsWith('/api/')) return sendFile(res, path.join(PUB, '404.html')); return json(res, 404, { error: 'Not found' }); } catch (e) { console.error('request', p, e); if (!res.headersSent) json(res, 500, { error: 'Something went wrong on our side.' }); else try { res.end(); } catch (x) {} } }); (async () => { await docstore.init({ splits: [] }); await db.init(process.env.DOCSTORE_URL); await chatbot.init(); await jobs.resume(); process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); }); server.listen(PORT, () => console.log('WebWorthIt on :' + PORT + (STAGING ? ' (staging)' : '') + ', store ' + (docstore.isOn() ? 'MySQL' : 'files') + ', hub sign-in ' + (networksso.hubOn() ? 'on' : 'off'))); })().catch(e => { console.error('boot failed', e); process.exit(1); });