Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)

Same design as InstantAdPay (shared sponsorfollow.js). Deliberate sponsor changes (tank adoption, rescue, release,
adoption window ending, admin edit) are recorded and travel on the iapsync rows; InstantAdPay's deliberate changes are
applied here only when the member is not bound or binding on the LinkSpin contract (memberId, wallet on chain, or an
engine activation in flight), newer than our own, and both sides agreed before (or no sponsor here). Bound / diverged /
race cases change nothing and are logged. Ordinary rows keep the fill-empty rule, except a sponsor emptied on purpose
here is not refilled by an ordinary row.

Carry: an InstantAdPay batch holds its members (carry.hold) so no auto-activation starts mid-batch; ensureOnChain waits,
then re-reads the account so the contract binds the settled sponsor; wallets from a batch are linked after every sponsor
decision; the wallet hook skips activation while a follow is pending and activates once it is settled.
Registry keeps the follow record (loop guard) and a deliberate clear. Network tank, Admin > Members > Sponsor check and
the partner endpoints as on InstantAdPay. Rows without the new facts hash as before (no resend on deploy).

Tests: qa/sponsorfollow.test.cjs 27/27, qa/carry-hold.test.cjs ok, two-server e2e (in the InstantAdPay repo) 20/20,
QA member walk 0 bugs. No sponsor was changed on production.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-22 09:05:20 -05:00
parent eedbd7280f
commit a5c2c38106
11 changed files with 889 additions and 33 deletions
+21 -2
View File
@@ -21,6 +21,18 @@ const ABI = ['function activateFor(address account, uint32 sponsorId) returns (u
const norm = e => String(e || '').trim().toLowerCase(); const norm = e => String(e || '').trim().toLowerCase();
function init(opts) { X = opts; } function init(opts) { X = opts; }
// ---- sponsor-follow guards (2026-10-22, sponsorfollow.js) ----
// hold(emails): an InstantAdPay registry batch is being applied for these people; an activation that starts meanwhile
// (a wallet arriving in the same batch fires onWalletLinked) waits until the batch is done and then re-reads the account,
// so it binds the sponsor the batch settled on, never the one from before it.
// isBinding(email): an engine activation for this person is in flight; the follow rule treats them as binding (bound).
const holds = new Map(); const inflight = new Set();
function hold(emails) { for (const e of emails || []) { const k = norm(e); if (k) holds.set(k, (holds.get(k) || 0) + 1); } }
function unhold(emails) { for (const e of emails || []) { const k = norm(e); const c = (holds.get(k) || 0) - 1; if (c > 0) holds.set(k, c); else holds.delete(k); } }
const isHeld = email => holds.has(norm(email));
const isBinding = email => inflight.has(norm(email));
async function waitUnheld(email, maxMs) { const t0 = Date.now(); while (isHeld(email) && Date.now() - t0 < (maxMs || 20000)) await sleep(250); }
function claimDays() { const n = Number((X.siteConfig && X.siteConfig().carryClaimDays) || 3); return n > 0 ? n : 3; } function claimDays() { const n = Number((X.siteConfig && X.siteConfig().carryClaimDays) || 3); return n > 0 ? n : 3; }
const STATE = () => path.join(X.dataDir, 'carry-state.json'); const STATE = () => path.join(X.dataDir, 'carry-state.json');
function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return { claims: {}, log: [] }; } } function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return { claims: {}, log: [] }; } }
@@ -129,8 +141,13 @@ async function nearestWithWallet(email) {
// activate `acct` on this contract via the engine, after its own sponsor is there (recursive, bounded) // activate `acct` on this contract via the engine, after its own sponsor is there (recursive, bounded)
async function ensureOnChain(acct, depth, why) { async function ensureOnChain(acct, depth, why) {
if (!acct || !acct.address) return 0; if (!acct || !acct.address) return 0;
// a registry batch is still settling this person's sponsor: wait for it, then use the account as it is NOW
if (acct.email && isHeld(acct.email)) await waitUnheld(acct.email);
if (acct.email) { try { const fresh = await X.accounts.byEmail(acct.email); if (fresh && fresh.address) acct = fresh; } catch (e) {} }
try { const id = await X.chain.memberIdByAccount(acct.address); if (id) { if (Number(acct.memberId) !== Number(id)) await X.accounts.setMemberId(acct.email, id).catch(() => {}); return id; } } catch (e) {} try { const id = await X.chain.memberIdByAccount(acct.address); if (id) { if (Number(acct.memberId) !== Number(id)) await X.accounts.setMemberId(acct.email, id).catch(() => {}); return id; } } catch (e) {}
if (!engineReady() || depth > 25) return 0; if (!engineReady() || depth > 25) return 0;
const me = norm(acct.email); inflight.add(me); let id = 0; // binding from here: the sponsor read below is the one the contract gets
try {
let sponsorId = 0; let sponsorId = 0;
if (acct.sponsorRef) { if (acct.sponsorRef) {
let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef); let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef);
@@ -140,7 +157,7 @@ async function ensureOnChain(acct, depth, why) {
try { if (sponsorId > await X.chain.memberCount()) sponsorId = 0; } catch (e) {} // first member on a fresh contract: no catch position exists yet try { if (sponsorId > await X.chain.memberCount()) sponsorId = 0; } catch (e) {} // first member on a fresh contract: no catch position exists yet
// send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations // send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations
// mined while a 403 on the follow-up read logged them as failures and skipped their notices) // mined while a 403 on the follow-up read logged them as failures and skipped their notices)
let id = 0, txHash = null, lastErr = null; let txHash = null, lastErr = null;
for (let attempt = 0; attempt < 3 && !id; attempt++) { for (let attempt = 0; attempt < 3 && !id; attempt++) {
try { try {
const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w); const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w);
@@ -149,11 +166,13 @@ async function ensureOnChain(acct, depth, why) {
} catch (e) { lastErr = e; } } catch (e) { lastErr = e; }
for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(acct.address)) || 0; } catch (e) {} if (!id) await sleep(3000); } for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(acct.address)) || 0; } catch (e) {} if (!id) await sleep(3000); }
} }
} finally { if (!id) inflight.delete(me); } // on success the flag stays until the member number is saved below
if (!id) { logEvent({ type: 'activateFailed', email: acct.email, error: String((lastErr && (lastErr.shortMessage || lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return 0; } if (!id) { logEvent({ type: 'activateFailed', email: acct.email, error: String((lastErr && (lastErr.shortMessage || lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return 0; }
logEvent({ type: 'activated', email: acct.email, id, sponsorId, tx: txHash }); logEvent({ type: 'activated', email: acct.email, id, sponsorId, tx: txHash });
// keep the member number on the account: the ledger and every name lookup go by it (2026-10-18: 340 engine // keep the member number on the account: the ledger and every name lookup go by it (2026-10-18: 340 engine
// activations had none, so the live ledger showed "member #352" instead of the username) // activations had none, so the live ledger showed "member #352" instead of the username)
await X.accounts.setMemberId(acct.email, id).catch(() => {}); await X.accounts.setMemberId(acct.email, id).catch(() => {});
inflight.delete(me);
await noticeActivated(acct, why); await noticeActivated(acct, why);
return id; return id;
} }
@@ -205,4 +224,4 @@ async function seedAll(limit) {
} }
function status() { const s = state(); return { engine: engineReady(), claims: Object.values(s.claims || {}), log: (s.log || []).slice(-50).reverse(), claimDays: claimDays() }; } function status() { const s = state(); return { engine: engineReady(), claims: Object.values(s.claims || {}), log: (s.log || []).slice(-50).reverse(), claimDays: claimDays() }; }
module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady, backfillMemberIds }; module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady, backfillMemberIds, hold, unhold, isHeld, isBinding };
+23 -6
View File
@@ -22,7 +22,14 @@
// 4. InstantAdPay ignores no-op rows, records its own lssync hash for rows whose result equals what we sent (so it does // 4. InstantAdPay ignores no-op rows, records its own lssync hash for rows whose result equals what we sent (so it does
// not echo them), and at most echoes ONCE where its facts differ (kept sponsor, skipped wallet). LinkSpin's inbound // not echo them), and at most echoes ONCE where its facts differ (kept sponsor, skipped wallet). LinkSpin's inbound
// handler only fills empty fields, so that echo changes no LinkSpin account, and rule 1 stops a resend. // handler only fills empty fields, so that echo changes no LinkSpin account, and rule 1 stops a resend.
//
// SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
// sponsorSetOrigin while the sponsor is the result of a deliberate change (tank adoption, rescue, release, window expiry,
// admin edit), and `tank` (LinkSpin's own adoptions of the person, or null). Rows without them hash as before (no resend
// on deploy). Rule 2 also compares the follow facts, so a change InstantAdPay made and we applied is not sent back.
// Until InstantAdPay answers proto 2, the hash of a row carrying the new facts is not recorded (sent again later).
'use strict'; 'use strict';
const SF = require('./sponsorfollow');
const crypto = require('crypto'); const crypto = require('crypto');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@@ -42,7 +49,7 @@ function load() {
} }
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} } function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
function init(deps) { R = deps; load(); } // { dataDir, accounts, registry, host } function init(deps) { R = deps; load(); } // { dataDir, accounts, registry, host, follow (sponsorfollow store), tank: () => tank }
const PUBLIC = () => String(process.env.PUBLIC_URL || ('https://' + (R.host || 'linkspin.app'))).replace(/\/+$/, ''); const PUBLIC = () => String(process.env.PUBLIC_URL || ('https://' + (R.host || 'linkspin.app'))).replace(/\/+$/, '');
function profileOf(a) { function profileOf(a) {
let socials = null; try { socials = a.socials ? (typeof a.socials === 'string' ? JSON.parse(a.socials) : a.socials) : null; } catch (e) { socials = null; } let socials = null; try { socials = a.socials ? (typeof a.socials === 'string' ? JSON.parse(a.socials) : a.socials) : null; } catch (e) { socials = null; }
@@ -52,13 +59,18 @@ function profileOf(a) {
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null; if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null }; return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
} }
async function rowFor(acct, byRef) { async function rowFor(acct, byRef, tankMap) {
const ref = norm(acct.sponsorRef); let sponsorEmail = null; const ref = norm(acct.sponsorRef); let sponsorEmail = null;
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; } if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
return { email: norm(acct.email), username: acct.username || null, wallet: acct.address ? norm(acct.address) : null, sponsorEmail, joinedAt: Number(acct.created) || null, profile: profileOf(acct) }; const row = { email: norm(acct.email), username: acct.username || null, wallet: acct.address ? norm(acct.address) : null, sponsorEmail, joinedAt: Number(acct.created) || null, profile: profileOf(acct) };
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
const T = R.tank && R.tank();
if (T) { try { row.tank = (tankMap ? tankMap.get(norm(acct.email)) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
return row;
} }
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
const canon = o => { if (!o || typeof o !== 'object') return JSON.stringify(o == null ? null : o); return '{' + Object.keys(o).sort().filter(k => o[k] != null).map(k => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'; }; const canon = o => { if (!o || typeof o !== 'object') return JSON.stringify(o == null ? null : o); return '{' + Object.keys(o).sort().filter(k => o[k] != null).map(k => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'; };
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.profile ? canon(r.profile) : ''].join('|')).digest('hex').slice(0, 16); const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.profile ? canon(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
// does the registry (= what InstantAdPay told us) already say everything this row says? // does the registry (= what InstantAdPay told us) already say everything this row says?
function sameAsRegistry(r, reg) { function sameAsRegistry(r, reg) {
if (!reg) return false; if (!reg) return false;
@@ -66,6 +78,9 @@ function sameAsRegistry(r, reg) {
if (r.wallet && norm(r.wallet) !== norm(reg.wallet)) return false; if (r.wallet && norm(r.wallet) !== norm(reg.wallet)) return false;
if (r.sponsorEmail && norm(r.sponsorEmail) !== norm(reg.sponsorEmail)) return false; if (r.sponsorEmail && norm(r.sponsorEmail) !== norm(reg.sponsorEmail)) return false;
if (r.profile && canon(r.profile) !== canon(reg.profile)) return false; if (r.profile && canon(r.profile) !== canon(reg.profile)) return false;
// a deliberate change travels unless the registry (= InstantAdPay) already holds that very change
if (r.sponsorSetBy && (Number(r.sponsorSetAt) !== Number(reg.sponsorSetAt) || norm(r.sponsorEmail) !== norm(reg.sponsorEmail))) return false;
if (r.tank) return false; // our own adoptions are news to InstantAdPay (the registry holds only its side); the hash stops a resend
return true; return true;
} }
// rows worth sending: changed since our last push and not just InstantAdPay's own facts coming back // rows worth sending: changed since our last push and not just InstantAdPay's own facts coming back
@@ -91,8 +106,9 @@ async function push(rows) {
const st = load(); let sent = 0; let result = null; const st = load(); let sent = 0; let result = null;
for (let i = 0; i < rows.length; i += 100) { for (let i = 0; i < rows.length; i += 100) {
const chunk = rows.slice(i, i + 100); result = await post(chunk); sent += chunk.length; const chunk = rows.slice(i, i + 100); result = await post(chunk); sent += chunk.length;
const peerNew = Number(result && result.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
for (const r of chunk) { for (const r of chunk) {
st.hashes[r.email] = hashOf(r); if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); // an old InstantAdPay ignored the new facts: send again later
// a LinkSpin-first member becomes part of the network registry, labelled as such (rule 3 above) // a LinkSpin-first member becomes part of the network registry, labelled as such (rule 3 above)
if (!(await R.registry.get(r.email))) { try { await R.registry.upsert({ email: r.email, username: r.username, wallet: r.wallet, sponsorEmail: r.sponsorEmail, joinedAt: r.joinedAt, profile: r.profile, firstProperty: 'linkspin' }); } catch (e) {} } if (!(await R.registry.get(r.email))) { try { await R.registry.upsert({ email: r.email, username: r.username, wallet: r.wallet, sponsorEmail: r.sponsorEmail, joinedAt: r.joinedAt, profile: r.profile, firstProperty: 'linkspin' }); } catch (e) {} }
} }
@@ -114,7 +130,8 @@ async function tick(force) {
try { try {
const all = await R.accounts.listAll(50000); const st = load(); const all = await R.accounts.listAll(50000); const st = load();
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(norm(a.username), a); if (a.code) byRef.set(norm(a.code), a); } const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(norm(a.username), a); if (a.code) byRef.set(norm(a.code), a); }
const rows = []; for (const a of all) { if (!a.email) continue; rows.push(await rowFor(a, byRef)); } const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
const rows = []; for (const a of all) { if (!a.email) continue; rows.push(await rowFor(a, byRef, tankMap || (T ? new Map() : null))); }
if (force) for (const r of rows) delete st.hashes[r.email]; if (force) for (const r of rows) delete st.hashes[r.email];
const go = await select(rows); const go = await select(rows);
const sent = go.length ? await push(go) : 0; const sent = go.length ? await push(go) : 0;
+8 -1
View File
@@ -210,6 +210,13 @@
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p> <p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div> <div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
</div> </div>
<div class="card">
<div class="card-head"><h3>Sponsor check: InstantAdPay and LinkSpin</h3><span class="sub" id="scSub">members on both sites whose sponsor differs</span></div>
<p class="small muted">Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.</p>
<p><button class="btn small" id="scRun" type="button">Run the check</button></p>
<div class="tablewrap"><table class="adm-table" id="scTable"></table></div>
<details style="margin-top:10px"><summary class="small muted">Recent sponsor follow activity on both sites</summary><div class="tablewrap"><table class="adm-table" id="scLog"></table></div></details>
</div>
<div class="card"> <div class="card">
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div> <div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
<p style="margin:0 0 10px"><input id="memFilter" placeholder="Filter by email, username, member # or sponsor" style="width:100%"></p> <p style="margin:0 0 10px"><input id="memFilter" placeholder="Filter by email, username, member # or sponsor" style="width:100%"></p>
@@ -500,6 +507,6 @@
<script src="/assets/common.js?v=20261018p25"></script> <script src="/assets/common.js?v=20261018p25"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script> <script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261020m1"></script> <script src="/assets/admin.js?v=20261020m1"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
</body> </body>
</html> </html>
+64
View File
@@ -0,0 +1,64 @@
// Admin > Members > Sponsor check (2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
// Lists members on both sites whose sponsor differs (or is set on one side only), with when and how each side's sponsor
// was set and whether each side is bound on its contract. "Use X's sponsor" applies X's sponsor on the OTHER site; the
// server refuses when the member is already bound there. Nothing runs until the admin presses "Run the check".
(function () {
const $ = id => document.getElementById(id);
if (!$('scRun')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit' };
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
function side(f) {
if (!f) return '<span class="muted">no account</span>';
const sp = f.sponsorEmail ? esc(f.sponsorName || f.sponsorEmail) + '<br><span class="small muted">' + esc(f.sponsorEmail) + '</span>' : f.deadLink ? '<span class="badge amber">dead link: ' + esc(f.sponsorRef) + '</span>' : '<span class="muted">none (in the tank)</span>';
const how = [];
if (f.prov) how.push('<b>' + esc(HOW[f.prov.by] || f.prov.by) + '</b> ' + esc(day(f.prov.at)) + (f.prov.origin ? ' on ' + esc(NAME[f.prov.origin] || f.prov.origin) : '') + (f.prov.prevEmail ? ', before: ' + esc(f.prov.prevEmail) : ''));
else how.push('no deliberate change on record; account made ' + esc(day(f.created)) + (f.joinedVia ? ' via ' + esc(f.joinedVia) : '') + (f.joinedRef ? ' (' + esc(f.joinedRef) + ')' : ''));
for (const a of (f.adoptions || []).slice(-3)) how.push('tank: ' + esc(a.status) + ' by ' + esc(a.adopter) + ' ' + esc(day(a.ts)));
if (f.remoteTank && f.remoteTank.open) how.push('adopted on the other site by ' + esc(f.remoteTank.adopterEmail));
if (f.pending) how.push('<span class="badge amber">follow waiting: ' + esc(f.pending.why || '') + '</span>');
for (const l of (f.log || []).filter(x => x.conflict).slice(0, 2)) how.push('<span class="badge amber">' + esc(l.action) + '</span> ' + esc(l.reason || '') + ' ' + esc(day(l.ts)));
const bound = f.bound ? '<span class="badge">bound on chain' + (f.memberId ? ': member #' + f.memberId : '') + (f.activation ? ', on-chain sponsor #' + f.activation.sponsorId + ', block ' + f.activation.block : '') + '</span>' : '<span class="muted small">not bound on chain' + (f.wallet ? ' (wallet linked)' : '') + '</span>';
return sp + '<div class="small" style="margin-top:4px">' + how.join('<br>') + '</div><div style="margin-top:4px">' + bound + '</div>';
}
let last = null;
async function run() {
$('scRun').disabled = true; $('scSub').textContent = 'checking both sites...';
try {
const r = await (await fetch('/api/admin/sponsor-check', { cache: 'no-store' })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
last = r;
if (r.peerError) { $('scSub').textContent = 'could not read the other site: ' + r.peerError; $('scTable').innerHTML = ''; return; }
const differ = r.rows.filter(x => x.kind === 'differ').length;
$('scSub').textContent = r.shared + ' on both sites, ' + r.same + ' match, ' + differ + ' differ, ' + (r.rows.length - differ) + ' set on one side only (' + day(r.at) + ')';
$('scTable').innerHTML = '<tr><th>Member</th><th>InstantAdPay sponsor</th><th>LinkSpin sponsor</th><th>Settle it</th></tr>' + (r.rows.length ? r.rows.map(x => {
const iapBound = !!(x.iap && x.iap.bound), lsBound = !!(x.ls && x.ls.bound);
return '<tr><td>' + esc(x.username ? '@' + x.username : '') + '<br><span class="small muted">' + esc(x.email) + '</span><br><span class="small muted">' + esc(x.kind === 'differ' ? 'different sponsors' : x.kind === 'iap-only' ? 'sponsor on InstantAdPay only' : 'sponsor on LinkSpin only') + '</span></td>'
+ '<td>' + side(x.iap) + '</td><td>' + side(x.ls) + '</td><td class="act">'
+ '<button class="btn small sec" data-scuse="instantadpay" data-email="' + esc(x.email) + '"' + (lsBound ? ' disabled title="bound on the LinkSpin contract: its sponsor there cannot change"' : '') + '>Use InstantAdPay\'s sponsor</button><br>'
+ '<button class="btn small sec" style="margin-top:6px" data-scuse="linkspin" data-email="' + esc(x.email) + '"' + (iapBound ? ' disabled title="bound on the InstantAdPay contract: its sponsor there cannot change"' : '') + '>Use LinkSpin\'s sponsor</button></td></tr>';
}).join('') : '<tr><td colspan="4" class="muted">Every shared member has the same sponsor on both sites.</td></tr>');
const logs = [].concat((r.follow && r.follow.recent) || []).map(l => Object.assign({ where: r.here }, l)).concat(((r.peerFollow && r.peerFollow.recent) || []).map(l => Object.assign({ where: r.here === 'linkspin' ? 'instantadpay' : 'linkspin' }, l))).sort((a, b) => b.ts - a.ts).slice(0, 60);
$('scLog').innerHTML = '<tr><th>When</th><th>Site</th><th>Member</th><th>What</th><th>From</th><th>To</th><th>Why</th></tr>' + (logs.length ? logs.map(l => '<tr><td class="when">' + esc(day(l.ts)) + '</td><td>' + esc(NAME[l.where] || l.where) + '</td><td class="small">' + esc(l.email || '') + '</td><td>' + (l.conflict ? '<span class="badge amber">' + esc(l.action) + '</span>' : esc(l.action)) + (l.by ? ' <span class="small muted">' + esc(HOW[l.by] || l.by) + '</span>' : '') + '</td><td class="small">' + esc(l.from || '-') + '</td><td class="small">' + esc(l.to || '(tank)') + '</td><td class="small muted">' + esc(l.reason || '') + '</td></tr>').join('') : '<tr><td colspan="7" class="muted">nothing yet</td></tr>');
} catch (e) { $('scSub').textContent = e.message; say(e.message, 'bad'); }
finally { $('scRun').disabled = false; }
}
$('scRun').addEventListener('click', run);
document.addEventListener('click', async e => {
const b = e.target.closest('[data-scuse]'); if (!b || b.disabled) return;
const use = b.dataset.scuse, email = b.dataset.email; const row = last && last.rows.find(x => x.email === email); if (!row) return;
const from = use === 'instantadpay' ? row.iap : row.ls; const target = use === 'instantadpay' ? 'LinkSpin' : 'InstantAdPay';
const who = from && from.sponsorEmail ? (from.sponsorName || from.sponsorEmail) : 'no sponsor (back to the holding tank)';
let ok = false;
try { ok = await IAP.confirmBox('Set ' + email + "'s sponsor on " + target + ' to ' + who + '? The other site keeps what it has. This is refused if the member is already bound on the ' + target + ' contract.', { title: 'Use ' + NAME[use] + "'s sponsor", ok: 'Apply on ' + target, cancel: 'Cancel' }); } catch (err) { ok = false; }
if (!ok) return;
b.disabled = true;
try {
const r = await (await fetch('/api/admin/sponsor-check/resolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, use }) })).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
say('Done: ' + email + ' now has ' + who + ' on ' + target + '.', 'ok'); await run();
} catch (err) { say(err.message, 'bad'); b.disabled = false; }
});
})();
+22
View File
@@ -0,0 +1,22 @@
// carry.js guards for the sponsor follow (2026-10-22): an activation that starts while an InstantAdPay registry batch is
// settling the member's sponsor waits for the batch and then re-reads the account; isBinding() is on while an engine
// activation is in flight. No chain, no engine key: the chain is a stub. node qa/carry-hold.test.cjs
'use strict';
const assert = require('assert');
const path = require('path');
const carry = require(path.join(__dirname, '..', 'carry.js'));
(async () => {
let acct = { email: 'm@x.co', address: '0x' + '1'.repeat(40), sponsorRef: 'old', memberId: 0 };
const reads = []; let unheldAt = 0;
carry.init({ dataDir: require('os').tmpdir(), accounts: { byEmail: async e => { reads.push(Date.now()); return Object.assign({}, acct); }, setMemberId: async () => {} },
chain: { memberIdByAccount: async () => { reads.push('chain@' + Date.now()); return 0; }, getConfig: () => ({}) }, siteConfig: () => ({}) });
carry.hold(['M@x.co']); assert.ok(carry.isHeld('m@x.co'));
const run = carry.ensureOnChain({ email: 'm@x.co', address: acct.address, sponsorRef: 'old' }, 0, 'wallet');
await new Promise(r => setTimeout(r, 900));
assert.strictEqual(reads.length, 0, 'nothing read while the batch holds the member');
acct.sponsorRef = 'new'; unheldAt = Date.now(); carry.unhold(['m@x.co']);
const id = await run; assert.strictEqual(id, 0); // no engine key: returns 0 without sending
assert.ok(reads.length >= 2 && reads[0] >= unheldAt, 'account re-read after the batch, then the chain checked');
assert.ok(!carry.isBinding('m@x.co'), 'not binding after it returned');
console.log('carry-hold: ok');
})().catch(e => { console.error('carry-hold: FAIL', e.message); process.exit(1); });
+4
View File
@@ -5,6 +5,7 @@
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min) # bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
# bash qa/run.sh all # public + member + earn # bash qa/run.sh all # public + member + earn
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter # bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no # Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/. # mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u set -u
@@ -30,6 +31,9 @@ if [ "$MODE" = "public" ]; then
node qa/walk.mjs public || status=1 node qa/walk.mjs public || status=1
elif [ "$MODE" = "member" ]; then elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/carry-hold.test.cjs || status=1
elif [ "$MODE" = "kb" ]; then elif [ "$MODE" = "kb" ]; then
node qa/kb-retrieval.cjs || status=1 node qa/kb-retrieval.cjs || status=1
node qa/kb-chat.mjs || status=1 node qa/kb-chat.mjs || status=1
+295
View File
@@ -0,0 +1,295 @@
// Unit tests for the sponsor follow rule + the one network holding tank (sponsorfollow.js, tank.js). The SAME file ships in
// InstantAdPay and LinkSpin. No server, no network, no chain: two in-process "platforms" (two instances of this repo's
// tank.js, each with its own in-memory accounts, follow store and throwaway data dir) and a mini sync that builds rows the
// way lssync.js / iapsync.js do (rowFields + tank summary) and delivers them the way the inbound handlers do.
// node qa/sponsorfollow.test.cjs
'use strict';
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const SITE = path.join(__dirname, '..');
const SF = require(path.join(SITE, 'sponsorfollow.js'));
delete process.env.DATABASE_URL; // JSON stores only
let passed = 0, failed = 0; const results = [];
async function t(name, fn) { try { await fn(); passed++; results.push('ok ' + name); } catch (e) { failed++; results.push('FAIL ' + name + '\n ' + (e && e.stack || e).split('\n').slice(0, 3).join('\n ')); } }
// ---------- pure rule ----------
const H = 3600000, T0 = Date.UTC(2026, 9, 22, 15, 0, 0);
const inc = (o) => Object.assign({ sponsorEmail: 'a@x.co', at: T0, by: 'adopt', prevEmail: null, origin: 'instantadpay' }, o);
const loc = (o) => Object.assign({ sponsorEmail: null, prov: null, bound: false }, o);
async function pure() {
await t('ordinary incoming row (no sponsorSetBy) is left to the first-platform rule', () => {
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), { sponsorEmail: 'a@x.co' }).action, 'ordinary');
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'join' })).action, 'ordinary');
assert.strictEqual(SF.incomingOf({ sponsorEmail: 'a@x.co', sponsorSetBy: 'join', sponsorSetAt: T0 }), null);
});
await t('deliberate adoption fills an empty sponsor (one network tank)', () => {
const d = SF.decide(loc(), inc()); assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
});
await t('bound member never changes, even for a newer deliberate change', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', bound: true }), inc({ prevEmail: 'b@x.co' })); assert.strictEqual(d.action, 'bound'); assert.ok(!d.apply); assert.ok(d.conflict);
assert.strictEqual(SF.decide(loc({ bound: true }), inc()).action, 'bound');
});
await t('newer deliberate change wins when both sides agreed before it', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'rescue', sponsorEmail: null, prevEmail: 'b@x.co' }));
assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
});
await t('clear back to the tank applies (sponsorEmail null)', () => {
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0 - 9 * 86400000, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ by: 'expire', sponsorEmail: null, prevEmail: 'a@x.co', at: T0 }));
assert.strictEqual(d.action, 'apply');
});
await t('ordinary sponsor that already differed from the sender is NOT moved (diverged, reported)', () => {
const d = SF.decide(loc({ sponsorEmail: 'c@x.co' }), inc({ prevEmail: null }));
assert.strictEqual(d.action, 'diverged'); assert.ok(!d.apply); assert.ok(d.conflict);
});
await t('older incoming deliberate change loses to a newer local one (stale)', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 2 * H, by: 'admin', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'stale'); assert.ok(!d.apply);
});
await t('newer incoming deliberate change beats an older local deliberate one', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 2 * H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'apply');
});
await t('conflict window: earlier incoming wins over a later local change, flagged', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'conflict-apply'); assert.ok(d.apply); assert.ok(d.conflict);
});
await t('conflict window: later incoming loses to an earlier local change, flagged, not applied', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'conflict-keep'); assert.ok(!d.apply); assert.ok(d.conflict);
});
await t('two changes from the same platform minutes apart are sequential, not a race', () => {
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ at: T0 + 60000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'a@x.co' }));
assert.strictEqual(d.action, 'apply');
});
await t('a sender that built on our current sponsor is sequential, not a race', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 + 120000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'b@x.co', origin: 'instantadpay' }));
assert.strictEqual(d.action, 'apply');
});
await t('same sponsor already: no-op (the ping-pong stopper)', () => {
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'A@x.co ' }), inc()).action, 'same');
});
await t('a local record that no longer describes the current sponsor is ignored (later ordinary change)', () => {
const d = SF.decide(loc({ sponsorEmail: 'w@x.co', prov: { at: T0 + H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0, prevEmail: null }));
assert.strictEqual(d.action, 'diverged');
assert.strictEqual(SF.rowFields({ at: T0, by: 'adopt', sponsorEmail: 'b@x.co' }, 'w@x.co'), null);
});
await t('back-compat: rows without the new facts hash exactly as before (no resend on deploy)', () => {
assert.strictEqual(SF.hashExtra({ email: 'm@x.co', sponsorEmail: 'a@x.co', tank: null }), '');
assert.notStrictEqual(SF.hashExtra({ sponsorSetBy: 'adopt', sponsorSetAt: T0 }), '');
});
}
// ---------- two platforms in one process ----------
function fakeAccounts() {
const by = new Map(); let nextId = 100;
const pub = a => a ? Object.assign({}, a) : null;
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
return {
_by: by,
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: T0 - 30 * 86400000, lastSeen: T0 - H }, o || {}); by.set(email, a); return pub(a); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true, account: pub(a) }; },
async listAll() { return [...by.values()].map(pub); },
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); },
async setMemberId(e, id) { const a = by.get(e); if (a) a.memberId = id; }
};
}
function platform(name, peerName) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-' + name + '-'));
delete require.cache[require.resolve(path.join(SITE, 'tank.js'))];
const tank = require(path.join(SITE, 'tank.js'));
const accounts = fakeAccounts();
const purchases = [];
const chain = { recentEvents: () => purchases, getConfig: () => ({}) };
const chats = [];
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 };
const store = SF.create({ dataDir: dir, platform: name });
const bound = new Set();
const glue = SF.glue({ store, accounts, tank: () => tank, peer: peerName,
isBound: async a => Number(a.memberId) > 0 || bound.has(a.email) ? { bound: true, why: name + ' member #' + a.memberId } : { bound: false },
sponsorAccount: em => accounts.byEmail(em),
wouldCycle: async (email, sp) => { let cur = sp; for (let i = 0; cur && i < 60; i++) { if (cur.email === email) return true; cur = await accounts.sponsorOf(cur.email); } return false; } });
tank.init({ dataDir: dir, chain, accounts, messages, mailer: null, site: 'https://' + name + '.test', follow: glue, store });
const P = { name, dir, tank, accounts, store, glue, chats, purchases, bound, hashes: {} };
// what the sync module would send for one account (lssync/iapsync rowFor)
P.rowFor = async email => {
const a = await accounts.byEmail(email); const sp = await accounts.sponsorOf(email);
const row = { email, username: a.username, sponsorEmail: sp && sp.email !== email ? sp.email : null };
Object.assign(row, SF.rowFields(store.get(email), row.sponsorEmail) || {});
row.tank = (await tank.summaryFor(email)) || null;
return row;
};
return P;
}
// deliver one row from P to Q the way the inbound handlers do (tank state first, then the follow rule)
async function deliver(P, Q, email) {
const row = await P.rowFor(email);
if (Object.prototype.hasOwnProperty.call(row, 'tank')) Q.store.setRemote(email, row.tank);
const d = await Q.glue.applyIncoming(email, row);
return { row, d };
}
// a mini "both sides synced" loop: push changed rows both ways until nothing changes (with a guard against ping-pong)
async function settle(P, Q, emails) {
let rounds = 0, moves = 0;
for (; rounds < 6; rounds++) {
let changed = 0;
for (const [X, Y] of [[P, Q], [Q, P]]) for (const e of emails) {
const row = await X.rowFor(e); const h = JSON.stringify(row);
if (X.hashes[e] === h) continue; X.hashes[e] = h; changed++;
Y.store.setRemote(e, row.tank); const d = await Y.glue.applyIncoming(e, row); if (d.apply) moves++;
}
if (!changed) break;
}
return { rounds, moves };
}
const spOf = async (P, e) => { const s = await P.accounts.sponsorOf(e); return s ? s.email : null; };
function people(P, Q) {
for (const X of [P, Q]) {
X.accounts.add('adopter@x.co', { memberId: 7, username: 'adopter' });
X.accounts.add('other@x.co', { memberId: 8, username: 'otheradopter' });
X.accounts.add('lead@x.co', { username: 'lead' });
X.accounts.add('old@x.co', { username: 'oldsponsor', memberId: 9 });
X.purchases.push({ type: 'Purchase', buyerId: 7, priceCents: 2500 }, { type: 'Purchase', buyerId: 8, priceCents: 2500 });
}
}
async function network() {
await t('network tank: adopting on one platform makes the person adopted on both (same adopter), notices only once', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'));
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
const r = await P.tank.adopt('adopter@x.co', 'lead', 'hi'); assert.ok(r.ok, JSON.stringify(r));
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'apply');
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'), 'hidden on the other side');
assert.strictEqual(P.chats.length, 1); assert.strictEqual(Q.chats.length, 0, 'no chat on the quiet side');
const qr = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(qr.error, 'cannot be adopted twice across the network');
});
await t('ping-pong guard: the applied change comes back as "same" and settles in one round trip', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await P.tank.adopt('adopter@x.co', 'lead');
const s = await settle(P, Q, ['lead@x.co']);
assert.strictEqual(s.moves, 1); assert.ok(s.rounds <= 3, 'rounds ' + s.rounds);
const back = await Q.rowFor('lead@x.co'); const fromP = await P.rowFor('lead@x.co');
assert.strictEqual(back.sponsorSetAt, fromP.sponsorSetAt); assert.strictEqual(back.sponsorSetOrigin, 'instantadpay');
assert.strictEqual((await P.glue.applyIncoming('lead@x.co', back)).action, 'same');
});
await t('waiting list hides someone with an open adoption elsewhere even if the follow could not apply', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
Q.bound.add('lead@x.co'); // say LinkSpin cannot take the change
await P.tank.adopt('adopter@x.co', 'lead');
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'bound');
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
assert.ok(Q.store.recent(5).some(x => x.action === 'bound' && x.conflict), 'logged for the report');
});
await t('release mirrors: releasing on the quiet side clears both and closes the open adoption as dropped', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
// the 3-day commitment counts on the quiet side too
const early = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(early.error && /commitment/.test(early.error), JSON.stringify(early));
// four days later
const realNow = Date.now; Date.now = () => realNow() + 4 * 86400000;
try {
const r = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(r.ok, JSON.stringify(r));
await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(P, 'lead@x.co'), null); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
const pad = (await P.tank.adminView()).adoptions.find(a => a.adoptee === 'lead@x.co');
assert.strictEqual(pad.status, 'dropped');
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'), 'back in the tank on both');
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
} finally { Date.now = realNow; }
});
await t('expiry mirrors: the adopting side ends the window and the other side follows the clear', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
const realNow = Date.now; Date.now = () => realNow() + 8 * 86400000;
try {
const sw = await P.tank.sweep(); assert.strictEqual(sw.back, 1);
await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
assert.strictEqual(Q.store.get('lead@x.co').by, 'expire');
} finally { Date.now = realNow; }
});
await t('two adoptions per person count across both platforms', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
try {
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
off = 8 * 86400000; await P.tank.sweep(); await settle(P, Q, ['lead@x.co']);
const r2 = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(r2.ok, JSON.stringify(r2)); await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(P, 'lead@x.co'), 'other@x.co');
off = 16 * 86400000; await Q.tank.sweep(); await settle(P, Q, ['lead@x.co']);
// adopted once on each side now: a third adoption anywhere is refused
if (!(await P.tank.waiting()).some(w => w.email === 'lead@x.co')) { /* kept where they are after two */ }
const r3 = await P.tank.adopt('adopter@x.co', 'lead'); assert.ok(r3.error, JSON.stringify(r3));
} finally { Date.now = realNow; }
});
await t('race: both sides adopt within minutes -> the earlier adoption wins on both, the later one is a conflict', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
try {
await P.tank.adopt('adopter@x.co', 'lead');
off = 90000; await Q.tank.adopt('other@x.co', 'lead'); // 90 s later on LinkSpin, before the sync arrived
off = 100000;
const a = await deliver(Q, P, 'lead@x.co'); // the later change reaches the earlier side: kept, flagged
assert.strictEqual(a.d.action, 'conflict-keep');
const b = await deliver(P, Q, 'lead@x.co'); // the earlier change reaches the later side: applied, flagged
assert.strictEqual(b.d.action, 'conflict-apply');
await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(P, 'lead@x.co'), 'adopter@x.co'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
const qad = (await Q.tank.adminView()).adoptions.find(x => x.adopter === 'other@x.co');
assert.strictEqual(qad.status, 'conflict');
assert.ok(P.store.recent(10).some(x => x.action === 'conflict-keep'));
} finally { Date.now = realNow; }
});
await t('ordinary join on the other side is never overwritten by an adoption here (diverged, reported)', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await Q.accounts.setSponsorRef('lead@x.co', 'oldsponsor'); // joined LinkSpin through @oldsponsor's link
await P.tank.adopt('adopter@x.co', 'lead');
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'diverged'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'old@x.co');
});
await t('rescue clears the other side when both had the same sponsor', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
for (const X of [P, Q]) await X.accounts.setSponsorRef('lead@x.co', 'oldsponsor');
await P.glue.setDeliberate('lead@x.co', '', 'rescue', 'test');
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'apply'); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
});
await t('admin pick from the mismatch report applies on the unbound side and refuses on a bound one', async () => {
const P = platform('instantadpay', 'linkspin'); P.accounts.add('m@x.co'); P.accounts.add('s@x.co', { username: 'sss' });
const ok = await P.glue.adminApply('m@x.co', 's@x.co'); assert.ok(ok.ok, JSON.stringify(ok)); assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
assert.strictEqual(P.store.get('m@x.co').by, 'admin');
P.bound.add('m@x.co'); const no = await P.glue.adminApply('m@x.co', null); assert.ok(no.error && /bound/.test(no.error));
assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
});
await t('mismatch report: differ / one-sided rows, matches counted', async () => {
const r = SF.mismatches([{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's1' }, { email: 'c@x', sponsorEmail: null }, { email: 'd@x', sponsorEmail: 's2' }],
[{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's2' }, { email: 'c@x', sponsorEmail: 's3' }, { email: 'e@x', sponsorEmail: 's4' }]);
assert.strictEqual(r.shared, 3); assert.strictEqual(r.same, 1); assert.deepStrictEqual(r.rows.map(x => x.email + ':' + x.kind), ['b@x:differ', 'c@x:ls-only']);
});
await t('pending follow: retried later and settled (sponsor account arrives)', async () => {
const Q = platform('linkspin', 'instantadpay'); Q.accounts.add('lead@x.co');
const row = { email: 'lead@x.co', sponsorEmail: 'late@x.co', sponsorSetAt: T0, sponsorSetBy: 'adopt', sponsorPrevEmail: null, sponsorSetOrigin: 'instantadpay' };
assert.strictEqual((await Q.glue.applyIncoming('lead@x.co', row)).action, 'pending');
Q.accounts.add('late@x.co', { username: 'late' });
const rr = await Q.glue.retryPending(); assert.strictEqual(rr.settled, 1);
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'late@x.co'); assert.strictEqual(Q.store.pendingFor('lead@x.co'), null);
});
}
(async () => {
await pure(); await network();
console.log(results.join('\n'));
console.log('\nsponsorfollow: ' + passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
})();
+7
View File
@@ -28,6 +28,13 @@ const J = {
if (k === 'firstProperty' && cur.firstProperty) continue; // first contact is history: an InstantAdPay echo of a LinkSpin-first row must not relabel it (2026-10-15) if (k === 'firstProperty' && cur.firstProperty) continue; // first contact is history: an InstantAdPay echo of a LinkSpin-first row must not relabel it (2026-10-15)
cur[k] = k === 'wallet' || k === 'sponsorEmail' ? norm(rec[k]) : rec[k]; cur[k] = k === 'wallet' || k === 'sponsorEmail' ? norm(rec[k]) : rec[k];
} }
// a deliberate sponsor change on InstantAdPay (sponsorfollow.js, 2026-10-22): the registry holds that record too, so
// iapsync can tell our echo of it apart from a change of our own; a deliberate clear (back to the tank) clears it here
if (rec.sponsorSetBy && Number(rec.sponsorSetAt) > 0) {
cur.sponsorSetAt = Number(rec.sponsorSetAt); cur.sponsorSetBy = String(rec.sponsorSetBy);
cur.sponsorPrevEmail = rec.sponsorPrevEmail ? norm(rec.sponsorPrevEmail) : null; cur.sponsorSetOrigin = rec.sponsorSetOrigin ? norm(rec.sponsorSetOrigin) : null;
if (!rec.sponsorEmail) cur.sponsorEmail = null;
}
cur.updated = Date.now(); this.db.byEmail[e] = cur; this.save(); return cur; cur.updated = Date.now(); this.db.byEmail[e] = cur; this.save(); return cur;
}, },
async all() { if (!this.db) this.load(); return Object.values(this.db.byEmail); }, async all() { if (!this.db) this.load(); return Object.values(this.db.byEmail); },
+97 -10
View File
@@ -43,6 +43,21 @@ const leaderboard = require('./leaderboard');
const toolkit = require('./toolkit'); const toolkit = require('./toolkit');
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15) const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15) const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22)
let follow = null, followStore = null;
const IAP_BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
let activationCache = { at: 0, map: null };
function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor)
if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map;
const m = new Map(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'MemberActivated' && ev.account) { const k = String(ev.account).toLowerCase(); if (!m.has(k)) m.set(k, { id: ev.id, sponsorId: ev.sponsorId, block: ev.block, tx: ev.tx }); }
activationCache = { at: Date.now(), map: m }; return m;
}
// signed partner body (registry sync secret, see sponsorfollow.verify): resolves { body } or { status, error }
async function readPartnerSigned(req, maxBytes) {
let raw; try { raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > maxBytes) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); } catch (e) { return { status: 413, error: 'too big' }; }
const bad = SF.verify(raw, req.headers); if (bad) return bad;
try { return { body: JSON.parse(raw || '{}') }; } catch (e) { return { status: 400, error: 'bad json' }; }
}
const helpdesk = require('./helpdesk'); // support: Help screen, /support, ticket link, chat hand-off, all on InstantAdPay's one desk (2026-10-16) const helpdesk = require('./helpdesk'); // support: Help screen, /support, ticket link, chat hand-off, all on InstantAdPay's one desk (2026-10-16)
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
const rotator = require('./rotator'); const rotator = require('./rotator');
@@ -601,12 +616,32 @@ async function boot() {
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain }); pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
registry.init({ dataDir: DATA_DIR }); registry.init({ dataDir: DATA_DIR });
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST }); carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
// payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first // sponsor follow (sponsorfollow.js): deliberate changes (tank adoption, rescue, release, window expiry, admin edit) are
accounts.onWalletLinked(async email => { const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); }); // recorded and follow to InstantAdPay, and InstantAdPay's are applied here, until the member is bound or binding on the
// LinkSpin contract (memberId, wallet already on chain, or an engine activation in flight). Ordinary bindings: first platform.
followStore = SF.create({ dataDir: DATA_DIR, platform: 'linkspin' });
follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'instantadpay',
isBound: async a => {
if (Number(a.memberId) > 0) return { bound: true, why: 'LinkSpin member #' + a.memberId };
if (carry.isBinding(a.email)) return { retry: true, why: 'a LinkSpin activation is in flight' };
if (!a.address) return { bound: false };
try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) { await accounts.setMemberId(a.email, id).catch(() => {}); return { bound: true, why: 'wallet is LinkSpin member #' + id }; } return { bound: false }; }
catch (e) { return { retry: true, why: 'LinkSpin chain read failed' }; }
},
sponsorAccount: em => accounts.byEmail(em),
wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; },
activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null,
// a follow that waited (chain read, activation in flight, sponsor not here yet) is settled: switch payouts on now if the
// wallet arrived meanwhile (the wallet hook below skipped it so the contract would not bind the old sponsor)
afterResolve: async email => { const a = await accounts.byEmail(email); if (a && a.address && !(Number(a.memberId) > 0)) await carry.ensureOnChain(a, 0, 'wallet'); } });
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000);
// payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first.
// Not while a deliberate sponsor change from InstantAdPay is still waiting to be applied (afterResolve above does it then).
accounts.onWalletLinked(async email => { if (followStore.pendingFor(email)) { console.log('activation deferred: sponsor follow pending for', email); return; } const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); });
// member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone // member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000); setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest // reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST }); accounts.onChange(email => iapsync.touch(email)); iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => iapsync.touch(email));
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
@@ -629,7 +664,7 @@ async function boot() {
zonereport.init({ dataDir: DATA_DIR }); zonereport.init({ dataDir: DATA_DIR });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } }); snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL }); tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore });
legacy.init({ dataDir: DATA_DIR }); legacy.init({ dataDir: DATA_DIR });
traffic.init({ dataDir: DATA_DIR }); traffic.init({ dataDir: DATA_DIR });
promos.init({ dataDir: DATA_DIR }); promos.init({ dataDir: DATA_DIR });
@@ -1920,7 +1955,7 @@ const server = http.createServer(async (req, res) => {
const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r); const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r);
console.log('admin username', e, un); console.log('admin username', e, un);
} }
if (b.sponsorRef !== undefined) { const r = await accounts.setSponsorRef(e, String(b.sponsorRef || '').trim()); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } if (b.sponsorRef !== undefined) { const r = await follow.setDeliberate(e, String(b.sponsorRef || '').trim(), 'admin', 'admin member card'); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } // deliberate: follows to InstantAdPay until bound
if (b.address !== undefined) { if (b.address !== undefined) {
const a = String(b.address || '').trim().toLowerCase(); const a = String(b.address || '').trim().toLowerCase();
if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' }); if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' });
@@ -2554,14 +2589,21 @@ const server = http.createServer(async (req, res) => {
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' }); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' });
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : []; const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : [];
const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0; // sponsor follow (2026-10-22): no engine activation may start for these people until the batch has settled their
// sponsor (carry.hold); wallets are linked LAST, after every sponsor decision, for the same reason
const held = rows.map(r => String(r.email || '').trim().toLowerCase()).filter(Boolean); carry.hold(held);
try {
const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0, followed = 0, kept = 0, wallets = [];
for (const r of rows) { for (const r of rows) {
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue; const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
let a = await accounts.byEmail(e); let a = await accounts.byEmail(e);
const created = !a;
if (!a) { const x = await accounts.ensure(e, '', 'carried', 'network'); if (x.created) shells++; a = await accounts.byEmail(e); } if (!a) { const x = await accounts.ensure(e, '', 'carried', 'network'); if (x.created) shells++; a = await accounts.byEmail(e); }
if (!a) continue; if (!a) continue;
if (Object.prototype.hasOwnProperty.call(r, 'tank')) followStore.setRemote(e, r.tank); // network tank: InstantAdPay's own adoptions of them
if (created && SF.incomingOf(r)) { const inc = SF.incomingOf(r); followStore.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'instantadpay' }); } // a new shell carries the same record (no echo)
if (r.username && !a.username) { try { await accounts.setUsername(e, r.username); updated++; } catch (err) {} } if (r.username && !a.username) { try { await accounts.setUsername(e, r.username); updated++; } catch (err) {} }
if (r.wallet && !a.address) { try { await accounts.linkWallet(e, r.wallet); updated++; } catch (err) {} } if (r.wallet && !a.address) wallets.push([e, r.wallet]);
if (r.profile && typeof r.profile === 'object') { // the InstantAdPay profile fills only what is still empty here; the member can change it on this side any time (Marty 2026-10-11) if (r.profile && typeof r.profile === 'object') { // the InstantAdPay profile fills only what is still empty here; the member can change it on this side any time (Marty 2026-10-11)
const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300; const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300;
const av = String(pf.avatarUrl || '').trim(); const bio = String(pf.bio || '').trim().slice(0, 600); let soc = null; const av = String(pf.avatarUrl || '').trim(); const bio = String(pf.bio || '').trim().slice(0, 600); let soc = null;
@@ -2573,11 +2615,56 @@ const server = http.createServer(async (req, res) => {
// sponsors in a second pass: a batch is newest-first, so a member's row usually comes BEFORE their sponsor's, whose // sponsors in a second pass: a batch is newest-first, so a member's row usually comes BEFORE their sponsor's, whose
// shell did not exist yet in the first pass (the sponsor line was left empty until the next change, 2026-10-15) // shell did not exist yet in the first pass (the sponsor line was left empty until the next change, 2026-10-15)
for (const r of rows) { for (const r of rows) {
const e = String(r.email || '').trim().toLowerCase(); if (!e || !r.sponsorEmail) continue; const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
if (SF.incomingOf(r)) { // a DELIBERATE change on InstantAdPay: the follow rule decides (never on a member bound here)
try { const d = await follow.applyIncoming(e, r); if (d.apply) followed++; else if (d.action !== 'same' && d.action !== 'ordinary') kept++; } catch (err) { console.error('sponsor follow', e, err.message); }
continue; // decided by the follow rule (a refusal is logged for the Sponsor check), never by the fill-empty rule below
}
if (!r.sponsorEmail) continue;
const a = await accounts.byEmail(e); if (!a || a.sponsorRef) continue; const a = await accounts.byEmail(e); if (!a || a.sponsorRef) continue;
const pv = followStore.get(e); if (pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail) continue; // emptied on purpose (released / rescued here): an ordinary row does not refill it
const sp = await accounts.byEmail(r.sponsorEmail); if (sp && sp.email !== a.email && (sp.username || sp.code)) { try { await accounts.setSponsorRef(e, sp.username || sp.code); updated++; } catch (err) {} } const sp = await accounts.byEmail(r.sponsorEmail); if (sp && sp.email !== a.email && (sp.username || sp.code)) { try { await accounts.setSponsorRef(e, sp.username || sp.code); updated++; } catch (err) {} }
} }
return json(res, 200, { ok: true, rows: rows.length, imported: n, shells, updated, registry: await registry.count() }); for (const [e, w] of wallets) { try { const x = await accounts.linkWallet(e, w); if (x && !x.error) updated++; } catch (err) {} } // last: activation reads the settled sponsor
return json(res, 200, { ok: true, proto: SF.PROTO, rows: rows.length, imported: n, shells, updated, followed, followKept: kept, registry: await registry.count() });
} finally { carry.unhold(held); }
}
// -- sponsor check between LinkSpin and InstantAdPay (2026-10-22, sponsorfollow.js). Partner side: InstantAdPay reads our
// facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here).
if (p === '/api/partner/sponsor-facts' && req.method === 'POST') {
const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
const emails = Array.isArray(sg.body.emails) ? sg.body.emails.slice(0, 5000) : null;
return json(res, 200, { ok: true, proto: SF.PROTO, platform: 'linkspin', rows: await follow.facts(emails), view: followStore.view() });
}
if (p === '/api/partner/sponsor-apply' && req.method === 'POST') {
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
const b = sg.body; const r = await follow.adminApply(b.email, b.sponsorEmail || null, { note: String(b.note || 'Sponsor check on InstantAdPay').slice(0, 120) });
console.log('sponsor check (from InstantAdPay)', b.email, '->', b.sponsorEmail || '(tank)', r.error || 'ok');
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/sponsor-check' && (req.method === 'GET' || req.method === 'POST')) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const mine = await follow.facts(); let peer = null, peerError = null;
try { peer = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; }
const mm = peer ? SF.mismatches(peer.rows || [], mine) : { shared: 0, same: 0, rows: [] };
return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'linkspin', peerError, follow: followStore.view(), peerFollow: peer ? peer.view : null }, mm), { 'Cache-Control': 'no-store' });
}
if (p === '/api/admin/sponsor-check/resolve' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const email = String(b.email || '').trim().toLowerCase();
if (!email) return json(res, 400, { error: 'Which member?' });
let r;
if (b.use === 'instantadpay') { // InstantAdPay's sponsor, applied HERE (refused when bound here)
const peer = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message }));
if (peer.error) return json(res, 502, { error: 'Could not read InstantAdPay: ' + peer.error });
const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' });
r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used InstantAdPay's sponsor" });
} else if (b.use === 'linkspin') { // our sponsor, applied ON INSTANTADPAY (InstantAdPay refuses when bound there)
const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' });
r = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on LinkSpin: used LinkSpin's sponsor" }, 30000).catch(e => ({ error: e.message }));
} else return json(res, 400, { error: 'use must be instantadpay or linkspin' });
console.log('sponsor check resolve', email, b.use, r.error || 'ok');
return json(res, r.error ? 400 : 200, r);
} }
if (p === '/api/admin/iapsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, iapsync.adminView()); } if (p === '/api/admin/iapsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, iapsync.adminView()); }
if (p === '/api/admin/iapsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await iapsync.tick(!!(b && b.force))); } if (p === '/api/admin/iapsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await iapsync.tick(!!(b && b.force))); }
@@ -3434,7 +3521,7 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const b = await readBody(req);
if (!b.email) return json(res, 400, { error: 'Which member?' }); if (!b.email) return json(res, 400, { error: 'Which member?' });
const r = await accounts.setSponsorRef(b.email, b.sponsorRef); const r = await follow.setDeliberate(b.email, b.sponsorRef, 'admin', 'admin members table'); // deliberate: follows to InstantAdPay until bound
return json(res, r.error ? 400 : 200, r); return json(res, r.error ? 400 : 200, r);
} }
if (p === '/api/admin/campaigns' && req.method === 'GET') { if (p === '/api/admin/campaigns' && req.method === 'GET') {
+286
View File
@@ -0,0 +1,286 @@
// Sponsor follow + one network holding tank (Marty, 2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
//
// Background: the registry sync between the two sites (IAP lssync.js / lsinbound.js, LinkSpin iapsync.js + its
// /api/partner/registry) never overwrites a sponsor (first-platform rule). That is right for ordinary bindings (join link,
// cookie, last touch, carry-over), but a DELIBERATE change on one side (tank adoption, dormant-lead rescue, release to the
// tank, an adoption falling back at the end of its window, an admin edit) stayed on that side only.
//
// The follow rule (decide() below, unit-tested in qa/sponsorfollow.test.cjs / tests/sponsorfollow.test.cjs):
// - A deliberate change is recorded here with when, how and the sponsor before it (record()). Sync rows carry it as
// sponsorSetAt / sponsorSetBy / sponsorPrevEmail / sponsorSetOrigin, and only while it still describes the current
// sponsor (rowFields()), so a later ordinary change never travels as if it were deliberate.
// - The receiver applies the incoming sponsor (a clear back to the tank included) only when ALL hold:
// the change is deliberate; the member is NOT bound (or binding) on the receiver's contract; it is newer than the
// receiver's own deliberate change; and the receiver either agreed with the sender before the change
// (receiver's sponsor == sponsorPrevEmail), has no sponsor, or has an older deliberate change of its own.
// Otherwise nothing moves: 'bound' and 'diverged' are logged for the admin mismatch report (conservative: when the
// two sides already disagreed before the change, a person decides).
// - Race: both sides changed independently within WINDOW_MS -> the EARLIER change wins on both sides and the case is
// logged as a conflict (the later one is undone on the side that made it, and reported, never silently kept).
// - Ping-pong: the receiver stores the incoming record unchanged (same at/by/origin), so its own row carries the same
// facts back and the sender sees 'same' (plus the hash / registry loop guards of the sync modules).
// - Accounts with no record (everything before this shipped) are "old, non-deliberate": nothing is rewritten on deploy.
//
// Network tank: each platform keeps its own adoptions; rows carry a small tank summary (own adoption count and the open
// adoption, if any) which the other side stores as remote state: its waiting list hides a member with an open adoption
// elsewhere, and the two-adoptions-per-person lifetime limit counts both platforms. The adoption itself reaches the other
// side as an ordinary deliberate follow (by 'adopt'), applied quietly (no chat, mail or feed post there).
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const DELIBERATE = ['adopt', 'rescue', 'release', 'expire', 'admin'];
const WINDOW_MS = 15 * 60 * 1000;
const PROTO = 2; // wire version: 2 = rows may carry sponsorSet* + tank, peers answer { proto: 2 }
const n = v => String(v == null ? '' : v).trim().toLowerCase();
const isDeliberate = by => DELIBERATE.includes(String(by || ''));
// ---- the rule (pure) ----
// local { sponsorEmail, prov: {at, by, sponsorEmail, prevEmail, origin} | null, bound: bool }
// incoming { sponsorEmail, at, by, prevEmail, origin }
// -> { action, apply: bool, conflict: bool, reason }
// actions: ordinary (caller keeps today's fill-empty rule) | same | bound | stale | conflict-keep | conflict-apply |
// diverged | apply
function decide(local, incoming, opts) {
const win = (opts && opts.windowMs) || WINDOW_MS;
const inc = incoming || {}; const loc = local || {};
if (!isDeliberate(inc.by) || !(Number(inc.at) > 0)) return { action: 'ordinary', apply: false, reason: 'not a deliberate change' };
if (n(inc.sponsorEmail) === n(loc.sponsorEmail)) return { action: 'same', apply: false, reason: 'already the same sponsor' };
if (loc.bound) return { action: 'bound', apply: false, conflict: true, reason: 'member is bound on this contract; the sponsor here cannot move' };
const lp = loc.prov && isDeliberate(loc.prov.by) && Number(loc.prov.at) > 0 && n(loc.prov.sponsorEmail) === n(loc.sponsorEmail) ? loc.prov : null;
const at = Number(inc.at);
if (lp) {
const lat = Number(lp.at);
// sequential, not a race: the earlier record came from the same platform, or the sender built on our current sponsor
const sequential = (lp.origin && inc.origin && n(lp.origin) === n(inc.origin)) || n(inc.prevEmail) === n(loc.sponsorEmail);
if (at === lat && !sequential) return { action: 'conflict-keep', apply: false, conflict: true, reason: 'two different changes with the same time; nothing moved' };
if (!sequential && Math.abs(at - lat) <= win) {
if (at < lat) return { action: 'conflict-apply', apply: true, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (incoming) wins on both' };
return { action: 'conflict-keep', apply: false, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (this side) wins on both' };
}
if (at <= lat) return { action: 'stale', apply: false, reason: 'this side has a newer deliberate change' };
return { action: 'apply', apply: true, reason: 'newer deliberate change' };
}
if (!n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'no sponsor here' };
if (n(inc.prevEmail) === n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'both sides had the same sponsor before the change' };
return { action: 'diverged', apply: false, conflict: true, reason: 'the two sides already had different sponsors before this change; left for the admin' };
}
// the follow fields a sync row carries for an account (only while the record still describes the current sponsor)
function rowFields(prov, currentSponsorEmail) {
if (!prov || !isDeliberate(prov.by) || !(Number(prov.at) > 0)) return null;
if (n(prov.sponsorEmail) !== n(currentSponsorEmail)) return null;
return { sponsorSetAt: Number(prov.at), sponsorSetBy: prov.by, sponsorPrevEmail: prov.prevEmail ? n(prov.prevEmail) : null, sponsorSetOrigin: prov.origin || null };
}
// what a received row says about a deliberate change (null when it says nothing)
function incomingOf(row) {
if (!row || !isDeliberate(row.sponsorSetBy) || !(Number(row.sponsorSetAt) > 0)) return null;
return { sponsorEmail: row.sponsorEmail ? n(row.sponsorEmail) : null, at: Number(row.sponsorSetAt), by: String(row.sponsorSetBy), prevEmail: row.sponsorPrevEmail ? n(row.sponsorPrevEmail) : null, origin: row.sponsorSetOrigin ? n(row.sponsorSetOrigin) : null };
}
// hash suffix: empty when the row has none of the new fields, so every existing row hashes exactly as before (no resend)
function hashExtra(r) {
const parts = [];
if (r && r.sponsorSetBy) parts.push('f:' + [r.sponsorSetAt, r.sponsorSetBy, r.sponsorPrevEmail || '', r.sponsorSetOrigin || ''].join(','));
if (r && r.tank) parts.push('t:' + [r.tank.count || 0, r.tank.open ? 1 : 0, r.tank.adopterEmail || '', r.tank.ts || '', r.tank.expires || ''].join(','));
return parts.length ? '|' + parts.join('|') : '';
}
function cleanTank(t) {
if (!t || typeof t !== 'object') return null;
const count = Math.max(0, Math.min(99, Number(t.count) || 0)); const open = !!t.open;
if (!count && !open) return null;
return { count, open, adopterEmail: open && t.adopterEmail ? n(t.adopterEmail) : null, ts: open ? Number(t.ts) || null : null, expires: open ? Number(t.expires) || null : null };
}
// ---- store: records, remote tank state, pending follows, the conflict log ----
function create(opts) {
const platform = n(opts.platform); const dataDir = opts.dataDir;
const FILE = () => path.join(dataDir, 'sponsorfollow.json');
let st = null;
function load() {
if (st) return st;
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
if (!st || typeof st !== 'object') st = {};
st.prov = st.prov || {}; st.remote = st.remote || {}; st.pending = st.pending || {}; st.log = st.log || []; st.peer = st.peer || {};
return st;
}
function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('sponsorfollow save', e.message); } }
const api = {
platform, PROTO, WINDOW_MS, DELIBERATE, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate,
get(email) { return load().prov[n(email)] || null; },
// a deliberate change made on this platform (origin = this platform), or one received and applied (origin kept)
record(email, rec) {
const e = n(email); if (!e || !isDeliberate(rec.by)) return null;
const r = { at: Number(rec.at) || Date.now(), by: rec.by, sponsorEmail: rec.sponsorEmail ? n(rec.sponsorEmail) : null, prevEmail: rec.prevEmail ? n(rec.prevEmail) : null, origin: n(rec.origin || platform) };
if (rec.note) r.note = String(rec.note).slice(0, 160);
load().prov[e] = r; save(); return r;
},
remote(email) { return load().remote[n(email)] || null; },
setRemote(email, tank) {
const e = n(email); const t = cleanTank(tank); const s = load();
const cur = s.remote[e] ? JSON.stringify(s.remote[e]) : null;
if (!t) { if (cur) { delete s.remote[e]; save(); } return; }
if (cur !== JSON.stringify(t)) { s.remote[e] = t; save(); }
},
remoteOpen(email, now) { const t = api.remote(email); return !!(t && t.open && (!t.expires || t.expires > (now || Date.now()))); },
remoteCount(email) { const t = api.remote(email); return t ? Number(t.count) || 0 : 0; },
pending() { return Object.assign({}, load().pending); },
pendingFor(email) { return load().pending[n(email)] || null; },
setPending(email, incoming, why) { const s = load(); s.pending[n(email)] = Object.assign({}, incoming, { why: String(why || '').slice(0, 120), since: (s.pending[n(email)] && s.pending[n(email)].since) || Date.now() }); save(); },
clearPending(email) { const s = load(); if (s.pending[n(email)]) { delete s.pending[n(email)]; save(); } },
note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 500) s.log = s.log.slice(-500); save(); },
recent(k) { return load().log.slice(-(k || 100)).reverse(); },
conflictsFor(email) { const e = n(email); return load().log.filter(x => x.email === e && x.conflict); },
setPeer(proto) { const s = load(); if (s.peer.proto !== proto) { s.peer.proto = proto; s.peer.at = Date.now(); save(); } },
peerProto() { return Number(load().peer.proto) || 1; },
view() { const s = load(); return { records: Object.keys(s.prov).length, remoteTank: Object.keys(s.remote).length, pending: Object.keys(s.pending).length, peerProto: Number(s.peer.proto) || 1, recent: s.log.slice(-40).reverse() }; },
_state: load, _reset() { st = null; }
};
return api;
}
// ---- signed partner calls (the same HMAC the registry sync uses: hex HMAC-SHA256(ts + "\n" + raw), LS_SYNC_SECRET) ----
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
function verify(raw, headers) {
const secret = SECRET(); if (secret.length < 32) return { status: 503, error: 'sync not configured' };
const ts = String(headers['x-ls-ts'] || ''), sig = String(headers['x-ls-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' };
const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
return null;
}
async function peerPost(baseUrl, pth, body, timeoutMs) {
const secret = SECRET(); if (secret.length < 32) throw new Error('sync not configured (LS_SYNC_SECRET)');
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(String(baseUrl).replace(/\/+$/, '') + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 30000) });
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
if (!r.ok) throw new Error((j && j.error) || ('peer ' + r.status + ' ' + txt.slice(0, 120)));
return j || {};
}
// ---- the admin mismatch report (pure): both sides' facts -> rows that differ ----
// facts row: { email, username, sponsorEmail, sponsorRef, prov, bound, boundWhy, memberId, created, joinedVia, adoptions, activation }
function mismatches(iapRows, lsRows) {
const L = new Map((lsRows || []).map(r => [n(r.email), r]));
const out = []; let shared = 0, same = 0;
for (const a of iapRows || []) {
const b = L.get(n(a.email)); if (!b) continue; shared++;
const sa = n(a.sponsorEmail), sb = n(b.sponsorEmail);
if (sa === sb) { same++; continue; }
out.push({ email: n(a.email), username: a.username || b.username || null, kind: sa && sb ? 'differ' : sa ? 'iap-only' : 'ls-only', iap: a, ls: b });
}
out.sort((x, y) => (x.kind === 'differ' ? 0 : 1) - (y.kind === 'differ' ? 0 : 1) || x.email.localeCompare(y.email));
return { shared, same, rows: out };
}
// ---- the platform glue: one implementation, per-platform hooks ----
// deps: { store, accounts, tank: () => tankModule|null, peer: 'linkspin'|'instantadpay',
// isBound: async acct => { bound, why, retry }, // retry = cannot tell right now (chain read failed, activation in flight)
// sponsorAccount: async email => acct|null, // the sponsor's account here (may build a waiting shell)
// wouldCycle: async (email, spAcct) => bool, // optional
// activationOf: acct => { id, sponsorId, block, tx } | null,
// afterResolve: async email => {} } // optional, after a pending follow is settled
function glue(deps) {
const S = deps.store, A = deps.accounts;
const tokenOf = a => a.username || a.code || (a.memberId ? String(a.memberId) : '');
async function accountOfRef(ref) {
const t = n(ref); if (!t) return null;
return (await A.byUsername(t).catch(() => null)) || (await A.byCode(t).catch(() => null)) || (/^\d+$/.test(t) && A.byMemberId ? await A.byMemberId(Number(t)).catch(() => null) : null) || null;
}
async function emailOfRef(ref) { const a = await accountOfRef(ref); return a ? n(a.email) : null; }
// a deliberate change made on THIS platform: record first (so the ~3 s sync touch already carries it), then write
async function setDeliberate(email, token, by, note) {
const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No such account.' };
const prev = await emailOfRef(a.sponsorRef); const tok = n(token);
const next = tok ? await emailOfRef(tok) : null;
if (isDeliberate(by)) S.record(e, { by, sponsorEmail: next, prevEmail: prev, note });
return A.setSponsorRef(e, tok);
}
async function closeLocalAdoptions(email, inc, d) {
const T = deps.tank && deps.tank(); if (!T || !T.onFollow) return;
try { await T.onFollow(email, inc, d); } catch (e) { console.error('tank onFollow', e.message); }
}
// a row from the other platform that carries a deliberate change
async function applyIncoming(email, row, opts) {
const inc = incomingOf(row); if (!inc) return { action: 'ordinary' };
const e = n(email); const a = await A.byEmail(e); if (!a) return { action: 'no-account' };
const cur = await emailOfRef(a.sponsorRef);
if (n(cur) === n(inc.sponsorEmail)) { S.clearPending(e); return { action: 'same', apply: false }; } // nothing to move (no chain read needed)
const b = (await deps.isBound(a).catch(err => ({ retry: true, why: 'bound check failed: ' + err.message }))) || {};
if (b.retry && !b.bound) { S.setPending(e, inc, b.why); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: b.why }); return { action: 'pending', reason: b.why }; }
const d = decide({ sponsorEmail: cur, prov: S.get(e), bound: !!b.bound }, inc, opts);
if (!d.apply) {
S.clearPending(e);
if (d.action !== 'same') S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, prev: inc.prevEmail, reason: d.reason + (b.bound && b.why ? ' (' + b.why + ')' : ''), conflict: !!d.conflict });
return d;
}
let tok = '';
if (inc.sponsorEmail) {
const sp = await ((opts && opts.sponsorAccount) || deps.sponsorAccount)(inc.sponsorEmail);
if (!sp) { S.setPending(e, inc, 'the new sponsor has no account here yet'); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'sponsor account missing' }); return { action: 'pending', reason: 'sponsor account missing' }; }
if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) { S.clearPending(e); S.note({ email: e, action: 'refused', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'would sponsor themselves or close a loop', conflict: true }); return { action: 'refused', reason: 'loop' }; }
tok = tokenOf(sp);
if (!tok) { S.setPending(e, inc, 'the new sponsor has no username or code here yet'); return { action: 'pending', reason: 'sponsor token missing' }; }
}
S.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || deps.peer });
const r = await A.setSponsorRef(e, tok);
if (r && r.error) { S.note({ email: e, action: 'error', reason: r.error, conflict: true }); return { action: 'error', reason: r.error }; }
await closeLocalAdoptions(e, inc, d);
S.clearPending(e);
S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, reason: d.reason, conflict: !!d.conflict });
return d;
}
// follows that could not be settled yet (chain unreadable, activation in flight, sponsor not here yet): retried on the sync tick
async function retryPending(maxAgeMs) {
const out = { tried: 0, settled: 0, dropped: 0 }; const now = Date.now();
for (const [e, p] of Object.entries(S.pending())) {
if (now - (p.since || now) > (maxAgeMs || 7 * 86400000)) { S.clearPending(e); S.note({ email: e, action: 'gave-up', by: p.by, to: p.sponsorEmail, reason: 'pending for 7 days: ' + (p.why || ''), conflict: true }); out.dropped++; continue; }
out.tried++;
const r = await applyIncoming(e, { sponsorEmail: p.sponsorEmail, sponsorSetAt: p.at, sponsorSetBy: p.by, sponsorPrevEmail: p.prevEmail, sponsorSetOrigin: p.origin }).catch(err => ({ action: 'error', reason: err.message }));
if (r.action !== 'pending') { out.settled++; if (deps.afterResolve) { try { await deps.afterResolve(e); } catch (err) {} } }
}
return out;
}
// the admin's pick in the mismatch report: apply `sponsorEmail` (null = back to the tank) here unless bound here
async function adminApply(email, sponsorEmail, opts) {
const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No account for ' + e + ' here.' };
const b = (await deps.isBound(a).catch(err => ({ retry: true, why: err.message }))) || {};
if (b.bound) return { error: 'Refused: ' + e + ' is already bound on this platform\'s contract (' + (b.why || 'on chain') + '). Its sponsor here cannot change.' };
if (b.retry) return { error: 'Could not confirm that ' + e + ' is not on the contract yet (' + (b.why || 'chain read failed') + '). Nothing changed. Try again in a minute.' };
let tok = '';
if (sponsorEmail) {
const sp = await deps.sponsorAccount(n(sponsorEmail));
if (!sp) return { error: 'The sponsor ' + n(sponsorEmail) + ' has no account here. Nothing changed.' };
if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) return { error: 'That would make the member their own upline. Nothing changed.' };
tok = tokenOf(sp); if (!tok) return { error: 'The sponsor has no username or code here yet. Nothing changed.' };
}
const prev = await emailOfRef(a.sponsorRef);
S.record(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null, prevEmail: prev, origin: (opts && opts.origin) || S.platform, note: (opts && opts.note) || 'mismatch report' });
const r = await A.setSponsorRef(e, tok); if (r && r.error) return r;
await closeLocalAdoptions(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null }, { action: 'admin' });
S.clearPending(e);
S.note({ email: e, action: 'admin-fix', by: 'admin', from: prev, to: sponsorEmail ? n(sponsorEmail) : null, reason: (opts && opts.note) || 'mismatch report' });
return { ok: true, email: e, from: prev, to: sponsorEmail ? n(sponsorEmail) : null };
}
// this platform's facts for the mismatch report (no chain reads: memberId + the indexed activation event)
async function facts(onlyEmails) {
const all = await A.listAll(50000, { shells: true });
const only = onlyEmails && onlyEmails.length ? new Set(onlyEmails.map(n)) : null;
const byTok = new Map(); for (const a of all) { if (a.username) byTok.set(n(a.username), a); if (a.code) byTok.set(n(a.code), a); if (a.memberId) byTok.set(String(a.memberId), a); }
const T = deps.tank && deps.tank();
const hist = T && T.historyMap ? await T.historyMap().catch(() => new Map()) : new Map();
const logBy = new Map(); for (const x of S.recent(500)) { if (!x.email) continue; if (!logBy.has(x.email)) logBy.set(x.email, []); if (logBy.get(x.email).length < 6) logBy.get(x.email).push(x); }
return all.filter(a => a.email && (!only || only.has(n(a.email)))).map(a => {
const e = n(a.email); const sp = a.sponsorRef ? byTok.get(n(a.sponsorRef)) : null;
const act = deps.activationOf ? deps.activationOf(a) : null;
return { email: e, username: a.username || null, sponsorRef: a.sponsorRef || '', sponsorEmail: sp && n(sp.email) !== e ? n(sp.email) : null, sponsorName: sp ? (sp.username ? '@' + sp.username : n(sp.email)) : null,
deadLink: !!(a.sponsorRef && !sp), prov: S.get(e), memberId: Number(a.memberId) || 0, bound: Number(a.memberId) > 0 || !!act, activation: act || null,
created: Number(a.created) || null, joinedVia: a.joinedVia || null, joinedRef: a.joinedRef || null, lastSeen: Number(a.lastSeen) || 0, wallet: !!a.address,
adoptions: hist.get(e) || [], remoteTank: S.remote(e), pending: S.pendingFor(e), log: logBy.get(e) || [] };
});
}
return { setDeliberate, applyIncoming, retryPending, adminApply, facts, emailOfRef, accountOfRef, tokenOf };
}
module.exports = { create, glue, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate, verify, peerPost, mismatches, DELIBERATE, WINDOW_MS, PROTO };
+62 -14
View File
@@ -16,6 +16,9 @@ const CAP_OPEN = 2; // open adoptions per adopter
const TTL_MS = 7 * 86400000; // an adoption's window to convert const TTL_MS = 7 * 86400000; // an adoption's window to convert
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13) const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13) const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js)
const NOT_COUNTED = ['released', 'conflict'];
const MIN_OWN_BUY_CENTS = 2500; // adopter must have bought a qualifying ($25+) package themselves const MIN_OWN_BUY_CENTS = 2500; // adopter must have bought a qualifying ($25+) package themselves
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old) const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
@@ -29,10 +32,11 @@ const J = {
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }, save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
async add(a) { const row = Object.assign({ id: this.db.nextId++ }, a); this.db.adoptions.push(row); this.save(); return row; }, async add(a) { const row = Object.assign({ id: this.db.nextId++ }, a); this.db.adoptions.push(row); this.save(); return row; },
async open(adopter) { return this.db.adoptions.filter(x => x.status === 'open' && (!adopter || x.adopter === adopter)); }, async open(adopter) { return this.db.adoptions.filter(x => x.status === 'open' && (!adopter || x.adopter === adopter)); },
async countFor(adoptee) { return this.db.adoptions.filter(x => x.adoptee === adoptee && x.status !== 'released').length; }, async countFor(adoptee) { return this.db.adoptions.filter(x => x.adoptee === adoptee && !NOT_COUNTED.includes(x.status)).length; },
async setStatus(id, status) { const x = this.db.adoptions.find(r => r.id === id); if (x) { x.status = status; x.closed = Date.now(); this.save(); } }, async setStatus(id, status) { const x = this.db.adoptions.find(r => r.id === id); if (x) { x.status = status; x.closed = Date.now(); this.save(); } },
async recent(n) { return this.db.adoptions.slice(-(n || 100)).reverse(); }, async recent(n) { return this.db.adoptions.slice(-(n || 100)).reverse(); },
async hasRecord(adoptee) { return this.db.adoptions.some(x => x.adoptee === adoptee && x.status !== 'released'); }, async hasRecord(adoptee) { return this.db.adoptions.some(x => x.adoptee === adoptee && !NOT_COUNTED.includes(x.status)); },
async all() { return this.db.adoptions.slice(); },
async mark(lead) { return this.db.marks[lead] || null; }, async mark(lead) { return this.db.marks[lead] || null; },
async setMark(lead, f) { this.db.marks[lead] = Object.assign(this.db.marks[lead] || {}, f); this.save(); } async setMark(lead, f) { this.db.marks[lead] = Object.assign(this.db.marks[lead] || {}, f); this.save(); }
}; };
@@ -45,10 +49,11 @@ const D = {
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'"); const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
return rows.map(rowA); return rows.map(rowA);
}, },
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status<>'released'", [adoptee]); return Number(r[0].n); }, async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [adoptee]); return Number(r[0].n); },
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); }, async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); }, async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status<>'released'", [adoptee]); return Number(r[0].n) > 0; }, async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [adoptee]); return Number(r[0].n) > 0; },
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; }, async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
async setMark(lead, f) { async setMark(lead, f) {
const cur = (await this.mark(lead)) || {}; const m = Object.assign(cur, f); const cur = (await this.mark(lead)) || {}; const m = Object.assign(cur, f);
@@ -58,7 +63,15 @@ const D = {
const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Number(r.ts), expires: Number(r.expires), status: r.status, note: r.note || null, closed: r.closed ? Number(r.closed) : null }); const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Number(r.ts), expires: Number(r.expires), status: r.status, note: r.note || null, closed: r.closed ? Number(r.closed) : null });
const impl = () => db.enabled() ? D : J; const impl = () => db.enabled() ? D : J;
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; if (opts.site) siteUrl = opts.site; J.load(); } function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load(); }
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to InstantAdPay
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
let follow = null, store = null;
const setSponsor = (email, token, by, note) => follow ? follow.setDeliberate(email, token, by, note) : accounts.setSponsorRef(email, token);
const OTHER = 'InstantAdPay';
const remoteOpen = email => !!(store && store.remoteOpen(email));
const remoteCount = email => store ? store.remoteCount(email) : 0;
const countAll = async email => (await impl().countFor(email)) + remoteCount(email); // the two-adoptions limit counts both platforms
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email)); const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
@@ -67,7 +80,7 @@ const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or
// waiting list: newest sign-in first so a live one is easy to spot // waiting list: newest sign-in first so a live one is easy to spot
async function waiting() { async function waiting() {
const all = await accounts.listAll(2000); const all = await accounts.listAll(2000);
return all.filter(inTank).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: false })) return all.filter(a => inTank(a) && !remoteOpen(a.email)).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: false }))
.sort((a, b) => (b.lastSeen || b.joined) - (a.lastSeen || a.joined)); .sort((a, b) => (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
} }
@@ -108,9 +121,10 @@ async function adopt(adopterEmail, who, note) {
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key); const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
if (!target) return { error: 'That member is no longer in the tank.' }; if (!target) return { error: 'That member is no longer in the tank.' };
if (target.email === e) return { error: 'That is you.' }; if (target.email === e) return { error: 'That is you.' };
if (await impl().countFor(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
if (await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' };
const token = me.username || me.code || String(me.memberId); const token = me.username || me.code || String(me.memberId);
const r = await accounts.setSponsorRef(target.email, token); const r = await setSponsor(target.email, token, 'adopt');
if (r.error) return r; if (r.error) return r;
const now = Date.now(); const now = Date.now();
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined LinkSpin without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.'); const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined LinkSpin without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
@@ -135,12 +149,15 @@ async function release(ownerEmail, directEmail) {
if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' }; if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' };
// picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13) // picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13)
const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d); const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d);
const young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS); let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
// adopted on InstantAdPay by this same member: the same 3-day commitment applies here
const rt = store && store.remote(d);
if (!young && rt && rt.open && rt.adopterEmail === o && rt.ts && Date.now() - rt.ts < HOLD_MS && remoteOpen(d)) young = { ts: rt.ts };
if (young) { if (young) {
const hrs = Math.ceil((HOLD_MS - (Date.now() - young.ts)) / 3600000); const hrs = Math.ceil((HOLD_MS - (Date.now() - young.ts)) / 3600000);
return { error: 'You picked ' + nameOf(direct) + ' up from the tank ' + Math.max(1, Math.round((Date.now() - young.ts) / 3600000)) + ' hour(s) ago. An adoption is a commitment: message them, help them link a wallet, and if it goes nowhere you can release them in ' + hrs + ' hour(s).' }; return { error: 'You picked ' + nameOf(direct) + ' up from the tank ' + Math.max(1, Math.round((Date.now() - young.ts) / 3600000)) + ' hour(s) ago. An adoption is a commitment: message them, help them link a wallet, and if it goes nowhere you can release them in ' + hrs + ' hour(s).' };
} }
const r = await accounts.setSponsorRef(d, ''); const r = await setSponsor(d, '', 'release');
if (r.error) return r; if (r.error) return r;
// an open adoption of this person closes as dropped, and a dropped adoption still counts toward their two // an open adoption of this person closes as dropped, and a dropped adoption still counts toward their two
let closed = 0; let closed = 0;
@@ -160,7 +177,7 @@ async function sweep() {
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; } if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; } if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; } if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
await accounts.setSponsorRef(ad.adoptee, ''); await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended');
await impl().setStatus(ad.id, 'expired'); back++; await impl().setStatus(ad.id, 'expired'); back++;
} }
const r = await rescueSweep(); const r = await rescueSweep();
@@ -230,10 +247,12 @@ async function rescueSweep() {
for (const a of await accounts.listAll(5000)) { for (const a of await accounts.listAll(5000)) {
if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank
if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules
const pv = store && store.get(a.email);
if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on InstantAdPay: the tank's window rules there
const sp = await sponsorOf(a); const sp = await sponsorOf(a);
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
if (now - (a.created || 0) < 86400000) continue; if (now - (a.created || 0) < 86400000) continue;
await accounts.setSponsorRef(a.email, ''); await setSponsor(a.email, '', 'rescue', 'dead sponsor link ' + a.sponsorRef);
await impl().add({ adoptee: a.email, adopter: 'dead:' + a.sponsorRef, ts: now, expires: now, status: 'rescued', note: 'sponsor link ' + a.sponsorRef + ' resolves to nobody' }); await impl().add({ adoptee: a.email, adopter: 'dead:' + a.sponsorRef, ts: now, expires: now, status: 'rescued', note: 'sponsor link ' + a.sponsorRef + ' resolves to nobody' });
dead++; continue; dead++; continue;
} }
@@ -249,7 +268,7 @@ async function rescueSweep() {
warned++; continue; warned++; continue;
} }
if (days >= RESCUE_DAYS && now - m.warned >= (RESCUE_DAYS - WARN_DAYS) * 86400000) { if (days >= RESCUE_DAYS && now - m.warned >= (RESCUE_DAYS - WARN_DAYS) * 86400000) {
await accounts.setSponsorRef(a.email, ''); await setSponsor(a.email, '', 'rescue', 'no contact for ' + Math.floor(days) + ' days');
await impl().add({ adoptee: a.email, adopter: sp.email, ts: now, expires: now, status: 'rescued', note: 'rescued from ' + nameOf(sp) + ' after ' + Math.floor(days) + ' days without contact' }); await impl().add({ adoptee: a.email, adopter: sp.email, ts: now, expires: now, status: 'rescued', note: 'rescued from ' + nameOf(sp) + ' after ' + Math.floor(days) + ' days without contact' });
if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, 'LinkSpin: ' + nameOf(a) + ' moved to the holding tank', if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, 'LinkSpin: ' + nameOf(a) + ' moved to the holding tank',
nameOf(a) + ' joined through your link ' + Math.floor(days) + ' days ago and was never contacted, so they have moved to the holding tank where another member can pick them up. Nothing on-chain changed. Your other referrals are unaffected.\n\n' + siteUrl + '/my#line'); } catch (e) {} } nameOf(a) + ' joined through your link ' + Math.floor(days) + ' days ago and was never contacted, so they have moved to the holding tank where another member can pick them up. Nothing on-chain changed. Your other referrals are unaffected.\n\n' + siteUrl + '/my#line'); } catch (e) {} }
@@ -259,6 +278,35 @@ async function rescueSweep() {
return { warned, rescued, dead }; return { warned, rescued, dead };
} }
// -- network tank (sponsorfollow.js) --
// a deliberate sponsor change arrived from InstantAdPay and was applied here: open adoptions of this person by someone else
// close quietly (no chat, no mail: the platform where it happened already told everyone)
async function onFollow(email, inc, d) {
const e = String(email || '').toLowerCase(); const to = String((inc && inc.sponsorEmail) || '').toLowerCase();
const status = d && d.conflict ? 'conflict' : ({ release: 'dropped', expire: 'expired', rescue: 'expired' }[inc && inc.by] || 'moved');
let closed = 0;
for (const ad of await impl().open(null)) if (ad.adoptee === e && ad.adopter !== to) { await impl().setStatus(ad.id, status); closed++; }
return closed;
}
// what a sync row says about this platform's own adoptions of a person: how many count, and the open one if any
function summaryOf(rows) {
let count = 0, open = null;
for (const x of rows) { if (!NOT_COUNTED.includes(x.status)) count++; if (x.status === 'open' && (!open || x.ts > open.ts)) open = x; }
if (!count && !open) return null;
return { count, open: !!open, adopterEmail: open ? open.adopter : null, ts: open ? open.ts : null, expires: open ? open.expires : null };
}
async function summaryMap() {
const by = new Map(); for (const x of await impl().all()) { if (!by.has(x.adoptee)) by.set(x.adoptee, []); by.get(x.adoptee).push(x); }
const out = new Map(); for (const [k, rows] of by) { const s = summaryOf(rows); if (s) out.set(k, s); } return out;
}
async function summaryFor(email) { const e = String(email || '').toLowerCase(); return summaryOf((await impl().all()).filter(x => x.adoptee === e)); }
async function historyMap() {
const out = new Map();
for (const x of await impl().all()) { if (!out.has(x.adoptee)) out.set(x.adoptee, []); out.get(x.adoptee).push({ adopter: x.adopter, ts: x.ts, status: x.status, closed: x.closed || null, note: x.status === 'open' ? null : (x.note || null) }); }
for (const v of out.values()) v.splice(0, Math.max(0, v.length - 6));
return out;
}
async function adminView() { async function adminView() {
const recent = await impl().recent(200); const recent = await impl().recent(200);
const names = {}; const names = {};
@@ -266,4 +314,4 @@ async function adminView() {
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000 }; return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000 };
} }
module.exports = { init, view, adopt, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS }; module.exports = { init, view, adopt, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };