diff --git a/catalog/traffic-sources.json b/catalog/traffic-sources.json index 13b26a7..d38882d 100644 --- a/catalog/traffic-sources.json +++ b/catalog/traffic-sources.json @@ -59,6 +59,36 @@ "verified": true, "source": "network" }, + { + "key": "downlinehydra", + "name": "DownlineHydra", + "site": "downlinehydra.com", + "costModel": "", + "params": [ + { + "key": "clickid", + "token": "{clickid}", + "label": "Click id", + "role": "externalId" + }, + { + "key": "placement", + "token": "{program}", + "label": "Program", + "role": "param" + }, + { + "key": "s1", + "token": "{program}", + "label": "Program (sub-id)", + "role": "param" + } + ], + "postbackUrl": "", + "notes": "DownlineHydra downline builder. Your saved referral links for outside programs (wild heads and my heads) go out as LinkSpin links: every click carries the program id as placement and s1, so Reports split them by program.", + "verified": true, + "source": "network" + }, { "key": "instantadpay", "name": "InstantAdPay", diff --git a/qa/partner-dhlinks.test.mjs b/qa/partner-dhlinks.test.mjs new file mode 100644 index 0000000..c688787 --- /dev/null +++ b/qa/partner-dhlinks.test.mjs @@ -0,0 +1,64 @@ +// DownlineHydra tracked program links (/api/partner/dh/links, Marty 2026-11-15). +// Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB, no mail key, no chain keys) and checks: +// the NETWORK_SSO_SECRET signature, account by email then by network username, one link per program on the member's own account +// with the "DownlineHydra" source, the program id as sub-id, the destination following a changed referral URL (same code), the +// clean link host, https-only destinations, the redirect keeping the referral ID intact, and clicks per program in the stats. +// node qa/partner-dhlinks.test.mjs (from the site dir; PORT default 8973) +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { spawn } from 'node:child_process'; + +const PORT = Number(process.env.PORT || 8973); const BASE = 'http://127.0.0.1:' + PORT; const SEC = crypto.randomBytes(32).toString('hex'); +let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 400) : '')); } }; +const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'dh-qa-')); +const now = Date.now(); +const acct = (email, username, memberId) => ({ email, username, code: username.slice(0, 7), memberId, created: now - 86400000, sponsorRef: '' }); +const accounts = { v: 2, byEmail: { 'one@dh.test': acct('one@dh.test', 'dhone', 920001), 'two@dh.test': acct('two@dh.test', 'dhtwo', 920002) }, byAddress: {}, byCode: {}, joins: 2, positions: {} }; +for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email; +fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts)); +fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: 'spin-links.test.org' })); +const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NETWORK_SSO_SECRET: SEC, ADMIN_PASSWORD: 'x'.repeat(16), ADMIN_EMAIL: 'admin@dh.test' }); +for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL']) delete env[k]; +const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); +const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] }); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +async function call(body, o = {}) { + const raw = JSON.stringify(body); const ts = String(o.ts || Date.now()); const sig = crypto.createHmac('sha256', o.sec || SEC).update('net.v1.' + ts + '\n' + raw).digest('hex'); + const r = await fetch(BASE + '/api/partner/dh/links', { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } }); + return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); +} +try { + for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); } + const L1 = [{ program: 'ctb19', name: 'Ads Earn Network', url: 'https://www.adsearnnetwork.com/?one19' }, { program: 'mh3', name: 'My Mailer', url: 'https://mymailer.example.org/r/one' }]; + let r = await call({ email: 'one@dh.test', op: 'ensure', links: L1 }, { sec: 'y'.repeat(64) }); ok(r._status === 401, 'a wrong signature is refused'); + r = await call({ email: 'one@dh.test', op: 'ensure', links: L1 }, { ts: Date.now() - 600000 }); ok(r._status === 401, 'an old timestamp is refused'); + r = await call({ email: 'nobody@dh.test', op: 'ensure', links: L1 }); ok(r._status === 200 && r.account === false, 'no LinkSpin account: account false, nothing made', r); + r = await call({ email: 'one@dh.test', op: 'ensure', links: L1 }); + const c19 = r.links && r.links.ctb19 && r.links.ctb19.code; + ok(r.account && r.host === 'spin-links.test.org' && /^[a-z0-9]{6}$/.test(c19 || '') && r.links.ctb19.created && r.links.mh3.created, 'ensure: one new link per program on the member\'s account, clean host', r); + ok(r.links.ctb19.link === 'https://spin-links.test.org/r/' + c19 + '?s1=ctb19&placement=ctb19', 'the link carries the program id as sub-id (s1) and placement', r.links.ctb19.link); + const src = JSON.parse(fs.readFileSync(path.join(DATA, 'sources.json'), 'utf8')); const mine = (src.items || src.sources || []).filter(x => x.owner === 'one@dh.test'); + ok(mine.length === 1 && mine[0].template === 'downlinehydra' && mine[0].name === 'DownlineHydra' && r.sourceId === mine[0].id, 'the account has one "DownlineHydra" source (network template)', mine); + const rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test'); + ok(rot.length === 2 && rot.every(x => x.sourceId === mine[0].id && /^dh:/.test(x.partner)) && rot.find(x => x.partner === 'dh:ctb19').destinations[0].url === 'https://www.adsearnnetwork.com/?one19', 'the links are tagged with that source and point at the referral URL', rot); + r = await call({ email: 'one@dh.test', op: 'ensure', links: [{ program: 'ctb19', name: 'Ads Earn Network', url: 'https://www.adsearnnetwork.com/?one19new' }] }); + const rot2 = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test'); + ok(r.links.ctb19.code === c19 && !r.links.ctb19.created && rot2.length === 2 && rot2.find(x => x.partner === 'dh:ctb19').destinations[0].url.endsWith('?one19new'), 'a changed referral URL updates the same link (same code, no new link)', r); + r = await call({ email: 'one@dh.test', op: 'ensure', links: [{ program: 'bad', url: 'http://plain.example.org/' }, { program: 'bad id!', url: 'https://x.example.org/' }] }); + ok(r.errors && r.errors.bad && r.errors['bad id!'] && !Object.keys(r.links).length, 'http destinations and bad program ids are refused', r); + r = await call({ username: 'dhtwo', op: 'ensure', links: [{ program: 'ctb19', url: 'https://www.adsearnnetwork.com/?two19' }] }); + ok(r.account && r.username === 'dhtwo' && r.links.ctb19 && r.links.ctb19.code !== c19, 'found by network username when the email is not given; a separate link on that account', r); + // a click through the link keeps the referral ID and counts for the program + const hit = await fetch('https://spin-links.test.org/r/'.replace('https://spin-links.test.org', BASE) + c19 + '?s1=ctb19&placement=ctb19', { redirect: 'manual', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36' } }); + const loc = hit.headers.get('location') || ''; + ok(hit.status >= 300 && hit.status < 400 && loc.startsWith('https://www.adsearnnetwork.com/?one19new'), 'the redirect lands on the program with the member\'s referral ID intact', [hit.status, loc]); + await sleep(300); + r = await call({ email: 'one@dh.test', op: 'stats' }); + ok(r.account && r.stats.ctb19 && r.stats.ctb19.hits === 1 && r.stats.ctb19.hits30 === 1 && r.stats.ctb19.unique30 === 1 && r.stats.mh3.hits === 0 && r.stats.ctb19.link.includes(c19), 'stats: clicks per program for this account only', r.stats); + const rep = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).hits.find(h => h.r === rot.find(x => x.partner === 'dh:ctb19').id); + ok(rep && rep.sr === mine[0].id && rep.q && rep.q.s1 === 'ctb19' && rep.q.placement === 'ctb19', 'the click is recorded under the DownlineHydra source with the program sub-id (Reports split it by program)', rep); +} catch (e) { fail++; console.error(e); } +finally { srv.kill(); await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} } +console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0); diff --git a/rotator.js b/rotator.js index 042d6ea..5fcce2c 100644 --- a/rotator.js +++ b/rotator.js @@ -152,6 +152,36 @@ function ensureFixed(owner, code, name, url) { const r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name: String(name).slice(0, 80), code: c, fallback: '', destinations: [{ id: 1, url: u, label: '', weight: 1, active: true, added: Date.now() }], created: Date.now(), paused: false, nextDest: 2 }; J.db.rotations.push(r); J.save(); return { ok: true, rotation: r, created: true }; } +// DownlineHydra tracked program links (Marty 2026-11-15, /api/partner/dh/links): one link per (account, partner key), e.g. +// key 'dh:ctb19' = the member's Ads Earn Network referral link. Made on the first ask, its one destination follows the member's +// latest referral URL, its traffic source is the account's "DownlineHydra" source. Never past the 100-link account cap. +function ensurePartner(owner, key, name, url, sourceId) { + const k = String(key || ''); if (!/^[a-z]{2,8}:[a-z0-9_-]{1,40}$/i.test(k)) return { error: 'key' }; + const u = cleanUrl(url); if (!u || !/^https:\/\//i.test(u)) return { error: 'Destination must be a full https:// address.' }; + let r = J.db.rotations.find(x => x.owner === norm(owner) && x.partner === k); let created = false; + if (!r) { + if (J.db.rotations.filter(x => x.owner === norm(owner)).length >= 100) return { error: 'This LinkSpin account already has 100 links.' }; + let code = newCode(); while (J.db.rotations.some(x => x.code === code)) code = newCode(); + r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name: String(name || k).slice(0, 80), code, fallback: '', destinations: [{ id: 1, url: u, label: '', weight: 1, active: true, added: Date.now() }], created: Date.now(), paused: false, nextDest: 2, partner: k }; + J.db.rotations.push(r); created = true; + } else { + const d = r.destinations[0]; + if (!d) r.destinations.push({ id: r.nextDest++, url: u, label: '', weight: 1, active: true, added: Date.now() }); + else if (d.url !== u) { d.url = u; d.active = true; delete d.autoPaused; } + if (name) r.name = String(name).slice(0, 80); + } + if (sourceId && !r.sourceId) r.sourceId = String(sourceId); + J.save(); return { ok: true, created, code: r.code, id: r.id }; +} +// clicks on an account's partner links whose key starts with `prefix` ('dh:'): { key: { code, hits, hits30, unique30 } } (non-bot) +function partnerStats(owner, prefix) { + const mine = J.db.rotations.filter(r => r.owner === norm(owner) && r.partner && r.partner.startsWith(prefix)); const ix = new Map(mine.map(r => [r.id, r.partner])); + const since = Date.now() - 30 * DAY; const out = {}; + for (const r of mine) out[r.partner] = { code: r.code, hits: 0, hits30: 0, u: new Set() }; + for (const h of J.db.hits) { const k = ix.get(h.r); if (!k || h.bot) continue; const o = out[k]; o.hits++; if (h.ts >= since) { o.hits30++; o.u.add(h.v); } } + for (const k in out) { out[k].unique30 = out[k].u.size; delete out[k].u; } + return out; +} async function remove(owner, id) { const n = J.db.rotations.length; J.db.rotations = J.db.rotations.filter(r => !(r.id === Number(id) && r.owner === norm(owner))); J.save(); return n !== J.db.rotations.length ? { ok: true } : { error: 'No such rotation.' }; } // opts.max: the admin import path only (BTC4Hits rotators, 2026-11-11) may go past the 25 a member can add, up to IMPORT_MAX const DEST_MAX = 25, IMPORT_MAX = 2000; @@ -366,4 +396,4 @@ function adminAll() { hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; }); } module.exports = { init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24, - pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource, ensureFixed }; + pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource, ensureFixed, ensurePartner, partnerStats }; diff --git a/server.js b/server.js index 160da46..18fd267 100644 --- a/server.js +++ b/server.js @@ -3129,6 +3129,42 @@ const server = http.createServer(async (req, res) => { } return json(res, 200, out, { 'Cache-Control': 'no-store' }); } + // -- DownlineHydra tracked program links (Marty 2026-11-15). Same net.v1 signature as the Banner Spins call above. A DownlineHydra + // member saved a referral link for an outside program (a wild head or a my head); their downline sees a LinkSpin link for it + // on this member's own account, tagged with the account's "DownlineHydra" source and the program id as a sub-id + // (?s1=&placement=, so Reports split clicks by program). Only clean link domains (domains.hosts()). + // { email, username?, op: 'ensure', links: [{ program, name, url }] } -> { account, username, host, links: { program: { code, link } }, errors } + // { email, username?, op: 'stats' } -> { account, host, stats: { program: { code, link, hits, hits30, unique30 } } } + // Nothing else about the account is read or changed. + if (p === '/api/partner/dh/links' && req.method === 'POST') { + let raw = ''; try { raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 65536) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); } catch (e) { return json(res, 400, { error: 'bad body' }); } + const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); const ts = String(req.headers['x-net-ts'] || ''); const sig = String(req.headers['x-net-sig'] || ''); + if (sec.length < 32 || !/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 300000) return json(res, 401, { error: 'unauthorized' }); + const want = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex'); + if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'unauthorized' }); + let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } + const email = String(b.email || '').trim().toLowerCase(); + let a = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) ? await accounts.byEmail(email).catch(() => null) : null; + if ((!a || !a.email) && b.username && /^[A-Za-z0-9_.-]{2,40}$/.test(String(b.username))) a = await accounts.byUsername(String(b.username)).catch(() => null); + if (!a || !a.email) return json(res, 200, { account: false }); + const hs = domains.hosts(); if (!hs.length) return json(res, 503, { error: 'No clean link domain right now.' }); + const host = hs[0].host; const PID = /^[a-z0-9_-]{1,40}$/i; + const linkOf = (code, pid) => 'https://' + host + '/r/' + code + '?s1=' + encodeURIComponent(pid) + '&placement=' + encodeURIComponent(pid); + if (b.op === 'stats') { + const st = rotator.partnerStats(a.email, 'dh:'); const out = {}; + for (const [k, v] of Object.entries(st)) { const pid = k.slice(3); out[pid] = { code: v.code, link: linkOf(v.code, pid), hits: v.hits, hits30: v.hits30, unique30: v.unique30 }; } + return json(res, 200, { account: true, username: a.username || null, host, stats: out }, { 'Cache-Control': 'no-store' }); + } + if (b.op !== 'ensure' || !Array.isArray(b.links) || !b.links.length || b.links.length > 60) return json(res, 400, { error: 'op' }); + const src = sources.networkSource(a.email, 'downlinehydra'); + const links = {}, errors = {}; + for (const x of b.links) { + const pid = String((x && x.program) || ''); if (!PID.test(pid)) { errors[pid.slice(0, 40) || '?'] = 'program'; continue; } + const r = rotator.ensurePartner(a.email, 'dh:' + pid, 'DownlineHydra: ' + String(x.name || pid).slice(0, 60), String(x.url || ''), src ? src.id : null); + if (r.error) errors[pid] = r.error; else links[pid] = { code: r.code, link: linkOf(r.code, pid), created: r.created }; + } + return json(res, 200, { account: true, username: a.username || null, host, sourceId: src ? src.id : null, links, errors }, { 'Cache-Control': 'no-store' }); + } if (p === '/api/partner/clicks' && req.method === 'POST') { const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error }); const owners = convtrack.importOwners(sg.body.owners); // InstantAdPay members' own soft keys first, so their own clicks import as tests diff --git a/sources.js b/sources.js index e554da6..4201e92 100644 --- a/sources.js +++ b/sources.js @@ -142,7 +142,8 @@ function meta(owner) { const m = {}; for (const s of mine(owner)) m[s.id] = { na // carrying ?src= (iap, linkspin, dlb, vbb, stackpol, earnerscorner, or the catalog key) counts under the link owner's // source for that site, made from the network catalog template the first time it is needed. Only network templates qualify. const NET_SRC = { iap: 'instantadpay', instantadpay: 'instantadpay', linkspin: 'linkspin', dlb: 'downlinebanners', downlinebanners: 'downlinebanners', - vbb: 'viralbannerblitz', viralbannerblitz: 'viralbannerblitz', stackpol: 'stackpol', earnerscorner: 'earnerscorner' }; + vbb: 'viralbannerblitz', viralbannerblitz: 'viralbannerblitz', stackpol: 'stackpol', earnerscorner: 'earnerscorner', + dh: 'downlinehydra', downlinehydra: 'downlinehydra' }; function networkTemplate(src) { const k = NET_SRC[String(src || '').trim().toLowerCase()]; const t = k ? template(k) : null; return t && t.source === 'network' ? t : null; } function networkSource(owner, src) { const t = networkTemplate(src); if (!t || !owner) return null;