Watch-to-earn videos on Social Tube: signed partner calls /api/partner/watch/next|done

The serve and complete halves of a watch-to-earn video are now videoNextFor / videoDoneFor, used by the member area and by the partner
calls, so the daily cap, server-clock watch floor, once-a-day-per-video, advertiser charge and viewer credit are one piece of code.
Partner calls: site 'socialtube', member named by email, HMAC with SITE_INVITE_SECRET under the prefix 'watch.v1.', 5 minutes.
Credit line reads 'Watched a video on Social Tube'. Chatbot: answer socialtube-earn + prompt line (Marty 2026-11-22).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-22 10:32:38 -06:00
parent 543bdefda2
commit d322971d7d
2 changed files with 72 additions and 32 deletions
+68 -32
View File
@@ -217,6 +217,45 @@ function loadOpenTokens() {
}
const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor)
const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor)
// One watch-to-earn video for a member, and the completion of it (2026-11-22). Shared by the member area (/api/my/videos,
// /api/my/videowatch) and the signed partner calls (/api/partner/watch/*, Social Tube), so the daily cap, the server-clock
// watch floor, once-a-day-per-video, the advertiser charge and the viewer credit are one piece of code wherever the video plays.
async function videoNextFor(email, orientation, g) {
const status = await ads.videoStatus(email);
if (status.left <= 0) return { ad: null, status };
const ad = await ads.serveVideo(Object.assign({ excludeEmail: email, orientation }, g)); // never your own video
if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13)
let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: email, orientation, ignoreSeen: true }, g))); } catch (e) {}
// this surface is empty but the other one may not be: the Watch tab holds the landscape
// videos and Shorts holds the portrait ones, and they share one daily cap, so a member
// who runs the tab dry still has clips waiting (Marty, 2026-09-22)
let otherFormat = null;
if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) {
const alt = orientation === 'landscape' ? 'portrait' : 'landscape';
try { if (await ads.serveVideo(Object.assign({ excludeEmail: email, orientation: alt }, g))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {}
}
return { ad: null, status, allWatched, otherFormat };
}
const token = crypto.randomBytes(16).toString('hex');
videoTokens.set(email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs });
return { ad, token, status };
}
async function videoDoneFor(email, tokenIn, where) { // -> { code, body }; where = '' or a short place name for the credit line (' on Social Tube')
const t = videoTokens.get(email);
if (!t || t.token !== String(tokenIn || '')) return { code: 400, body: { error: 'That video is no longer open. Load the next one.' } };
const age = Date.now() - t.ts;
if (age < t.secs * 1000 - 600) return { code: 400, body: { error: 'Watch the full video first.' } };
if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(email); return { code: 400, body: { error: 'That watch went stale. Load a fresh video.' } }; }
videoTokens.delete(email); // single use
if (await ads.hasWatchedVideoToday(email, t.id)) // once-per-day-per-video: no double earning
return { code: 200, body: { ok: true, credited: 0, status: await ads.videoStatus(email), already: true } };
const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry
if (!tier) return { code: 200, body: { ok: true, credited: 0, status: await ads.videoStatus(email), gone: true } };
await ads.addEarned(email, tier.reward, { log: { kind: 'earn', note: 'Watched a video' + (where || '') + ' (' + tier.secs + 's)' } });
await ads.markVideoSeen(email, t.id);
const status = await ads.recordVideoWatch(email);
return { code: 200, body: { ok: true, credited: tier.reward, status } };
}
const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit)
const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor)
// walk the referral chain upward via sponsorRef (code/username/member id)
@@ -3946,6 +3985,32 @@ const server = http.createServer(async (req, res) => {
const r = await siteinvite.handle(op, sg.body);
return json(res, r.error ? 400 : 200, r);
}
// -- watch-to-earn videos played on another network site (Social Tube, Marty 2026-11-22: "a member watching on Social Tube earns the same
// InstantAdPay credits"). The other site only shows the video: this app picks it, times it on its own clock, charges the advertiser and
// credits the viewer through videoNextFor / videoDoneFor, so every rule and the daily cap are shared with the member area.
// POST /api/partner/watch/next { site:'socialtube', email, ip?, orientation? } -> { ad, token, status } | { ad:null, status, ... }
// POST /api/partner/watch/done { site:'socialtube', email, token } -> { ok, credited, status, already?, gone? }
// Signature: X-Watch-Ts (ms) + X-Watch-Sig = hex HMAC-SHA256(SITE_INVITE_SECRET, 'watch.v1.' + ts + '\n' + raw body), 5 minutes.
if (p.startsWith('/api/partner/watch/') && req.method === 'POST') {
const secret = String(process.env.SITE_INVITE_SECRET || '').trim(); if (secret.length < 32) return json(res, 503, { error: 'not configured' });
let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
const ts = String(req.headers['x-watch-ts'] || ''), sig = String(req.headers['x-watch-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return json(res, 401, { error: 'stale' });
if (!gpSigOk(crypto.createHmac('sha256', secret).update('watch.v1.' + ts + '\n' + raw).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
if (!b || String(b.site) !== 'socialtube') return json(res, 400, { error: 'unknown site' });
const who = await gpResolve(0, b.email); if (!who) return json(res, 404, { error: 'no such member' });
if (fraud.isSuspended(who.email)) return json(res, 403, { error: 'suspended' });
const op = p.slice('/api/partner/watch/'.length);
if (op === 'next') {
const cc = geo.countryOf(String(b.ip || '').slice(0, 60) || 'unknown'), ori = ['portrait', 'landscape'].includes(b.orientation) ? b.orientation : '';
const r = await videoNextFor(who.email, ori, { cc, tier: geo.tierOf(cc, siteConfig()) });
if (r.ad) r.ad = Object.assign({}, r.ad, { ctaUrl: 'https://instantadpay.com' + r.ad.ctaUrl, videoUrl: /^\//.test(r.ad.videoUrl || '') ? 'https://instantadpay.com' + r.ad.videoUrl : r.ad.videoUrl });
return json(res, 200, r);
}
if (op === 'done') { const vd = await videoDoneFor(who.email, b.token, ' on Social Tube'); return json(res, vd.code, vd.body); }
return json(res, 404, { error: 'unknown op' });
}
if (p === '/api/admin/site-invites' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await siteinvite.adminView()); }
if (p === '/api/admin/site-invites/sample' && req.method === 'POST') { // one sample of the invite email to the admin address only
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); if (!ADMIN_EMAIL) return json(res, 400, { error: 'no admin email set' });
@@ -5501,44 +5566,15 @@ const server = http.createServer(async (req, res) => {
if (p === '/api/my/videos' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const status = await ads.videoStatus(s.email);
if (status.left <= 0) return json(res, 200, { ad: null, status });
const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab
const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video
if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13)
let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {}
// this surface is empty but the other one may not be: the Watch tab holds the landscape
// videos and Shorts holds the portrait ones, and they share one daily cap, so a member
// who runs the tab dry still has clips waiting (Marty, 2026-09-22)
let otherFormat = null;
if (status.left > 0 && (orientation === 'landscape' || orientation === 'portrait')) {
const alt = orientation === 'landscape' ? 'portrait' : 'landscape';
try { if (await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation: alt }, viewerGeo(req)))) otherFormat = alt === 'portrait' ? 'shorts' : 'watch'; } catch (e) {}
}
return json(res, 200, { ad: null, status, allWatched, otherFormat });
}
const token = crypto.randomBytes(16).toString('hex');
videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs });
return json(res, 200, { ad, token, status });
return json(res, 200, await videoNextFor(s.email, orientation, viewerGeo(req)));
}
if (p === '/api/my/videowatch' && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const t = videoTokens.get(s.email);
if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' });
const age = Date.now() - t.ts;
if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' });
if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); }
videoTokens.delete(s.email); // single use
if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning
return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true });
const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry
if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true });
await ads.addEarned(s.email, tier.reward, { log: { kind: 'earn', note: 'Watched a video (' + tier.secs + 's)' } });
await ads.markVideoSeen(s.email, t.id);
const status = await ads.recordVideoWatch(s.email);
return json(res, 200, { ok: true, credited: tier.reward, status });
const vd = await videoDoneFor(s.email, b.token, '');
return json(res, vd.code, vd.body);
}
// -- verified visits: view a member's site (new tab) for the dwell, pass a
// human check, and it counts as one guaranteed unique visit for the pack