Road Agent hooks: per-game door round trip (fuel stops under RA_SSO_SECRET, callbacks to RA_URL), /api/my/roadagent hand-off, registry + strip entries (not live), wallet nudges ask Road Agent, door page words itself as a fuel stop
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
@@ -1416,6 +1416,32 @@ function sdOpen(token, expiredMsg) {
|
||||
if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || 'That link has expired. Go back to Spooky Doors and try again.' };
|
||||
return { ok: true, claims: c };
|
||||
}
|
||||
// -- Road Agent (2026-10-07): the same door round trip under its own secret; a fuel stop is a door with game: 'roadagent'
|
||||
const RA_SECRET = () => String(process.env.RA_SSO_SECRET || '').trim();
|
||||
const RA_URL = () => String(process.env.RA_URL || 'https://roadagent.app').replace(/\/+$/, '');
|
||||
const DOOR_GAMES = () => ({ spookydoors: { name: 'Spooky Doors', secret: SD_SECRET(), url: SD_URL(), hdr: 'SD', back: 'Go back to Spooky Doors and knock again.' },
|
||||
roadagent: { name: 'Road Agent', secret: RA_SECRET(), url: RA_URL(), hdr: 'RA', back: 'Go back to Road Agent and fuel up again.' } });
|
||||
const gSign = (g, p) => drB64u(crypto.createHmac('sha256', g.secret).update(p).digest());
|
||||
function gMint(g, claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + gSign(g, payload); }
|
||||
// open a door token from whichever game signed it: { ok, claims, game } or { error }
|
||||
function doorOpen(token, expiredMsg) {
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
const G = DOOR_GAMES(); const key = G[c.game] ? c.game : 'spookydoors'; const g = G[key];
|
||||
if (!g.secret || g.secret.length < 32) return { error: g.name + ' is not connected yet.' };
|
||||
const want = gSign(g, payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
|
||||
if (!c.exp || Date.now() > c.exp) return { error: expiredMsg || ('That link has expired. ' + g.back) };
|
||||
return { ok: true, claims: c, game: key };
|
||||
}
|
||||
const gameUrlOk = (key, x) => String(x || '').startsWith(DOOR_GAMES()[key].url + '/');
|
||||
async function gameCallback(key, body) { // door done -> the game's server, signed over ts + newline + raw body
|
||||
const g = DOOR_GAMES()[key]; const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', g.secret).update(ts + '\n' + raw).digest('hex');
|
||||
const h = { 'Content-Type': 'application/json' }; h['X-' + g.hdr + '-Ts'] = ts; h['X-' + g.hdr + '-Sig'] = sig;
|
||||
try { const r = await fetch(g.url + '/api/door/callback', { method: 'POST', headers: h, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; }
|
||||
catch (e) { console.warn(key + ' callback', e.message); return false; }
|
||||
}
|
||||
const doorTokens = persistedMap('door'); // nonce -> { kind, email, memberId, id, title, target|videoUrl, host, ts, ret, challenge, done, doneRet }
|
||||
const sdOrders = persistedMap('sdorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts }
|
||||
const sdIsGameUrl = x => String(x || '').startsWith(SD_URL() + '/');
|
||||
@@ -1480,6 +1506,8 @@ function GAMES() {
|
||||
return withPerks([
|
||||
{ slug: 'spookydoors', name: 'Spooky Doors', tag: 'Halloween \u00b7 Oct 4 to 31', blurb: 'Trick or treat! Walk the street, knock on doors and fill your candy bucket. Every door is a short visit to a member\u2019s page or ad, and candy climbs a ladder with POL at set levels. Gone after Halloween night.',
|
||||
art: SD_URL() + '/og-spookydoors.jpg', play: '/api/my/spookydoors', pays: 'POL at set candy levels', season: { start: SD_SEASON.start, end: SD_SEASON.end }, progress: sdProgress },
|
||||
{ slug: 'roadagent', name: 'Road Agent', tag: 'Night highway shooter', blurb: 'Drive the night highway, shoot the hostiles that hunt you, spare the civilians. Fuel from a sponsor visit brings the weapons truck. Every sector you clear for the first time pays POL.',
|
||||
art: RA_URL() + '/og-roadagent.jpg', play: '/api/my/roadagent', pays: 'POL for first sector clears and the daily patrol', progress: raProgress },
|
||||
{ slug: 'driprunner', name: 'Drip Runner', tag: 'Arcade runner', blurb: 'Hop the network, dodge the bots, clear chapters. Each first clear drips POL into your game balance, and a refuel on a member\u2019s page keeps your run alive.',
|
||||
art: DR_URL() + '/og-driprunner.jpg?v=20261002', artPos: 'left', play: '/api/my/driprunner', pays: 'POL to your wallet at 0.10', progress: drProgress },
|
||||
{ slug: 'gemkingdom', name: 'Gem Kingdom', tag: 'Fantasy match-3', blurb: 'Match gems to battle monsters with three heroes, earn stars and rebuild your village. Crowns for instant upgrades come from your ad credits.',
|
||||
@@ -1502,6 +1530,7 @@ const withPerks = list => { const st = starter.cfg(); return list.map(g => start
|
||||
// -- cross-promo strip (2026-10-03): one short line per game and where a signed-out player lands (the game's own page)
|
||||
const STRIP = () => ({
|
||||
spookydoors: { line: 'Halloween only. Run the graveyard, knock on doors, climb the candy ladder to POL.', open: SD_URL() + '/play', host: SD_URL().replace(/^https?:\/\//, '') },
|
||||
roadagent: { line: 'Night highway. Shoot the hostiles, clear sectors, get paid in POL.', open: RA_URL() + '/', host: RA_URL().replace(/^https?:\/\//, '') },
|
||||
driprunner: { line: 'Hop, dodge the bots, clear chapters. Every first clear drips POL.', open: DR_URL() + '/play', host: DR_URL().replace(/^https?:\/\//, '') },
|
||||
gemkingdom: { line: 'Match gems, beat the bosses, rebuild your kingdom. First clears pay POL.', open: GK_URL() + '/play', host: GK_URL().replace(/^https?:\/\//, '') },
|
||||
polhunter: { line: 'Find hidden codes on sites across the network. Every find drips POL.', open: 'https://polhunter.com/', host: 'polhunter.com' },
|
||||
@@ -1537,6 +1566,14 @@ async function drProgress(memberId) {
|
||||
return { line: 'Chapter ' + j.chapter + ' \u00b7 ' + Number(j.unpaid).toFixed(3) + ' POL in your game balance' + (j.paidTotal ? ' \u00b7 ' + Number(j.paidTotal).toFixed(3) + ' POL paid out' : '') };
|
||||
}
|
||||
|
||||
// the player's own line on the Road Agent card (signed, like the others)
|
||||
async function raProgress(memberId) {
|
||||
if (RA_SECRET().length < 32) return null;
|
||||
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', RA_SECRET()).update('player:' + memberId + ':' + ts).digest('hex');
|
||||
const r = await fetch(RA_URL() + '/api/partner/player?m=' + Number(memberId) + '&ts=' + ts + '&sig=' + sig, { signal: AbortSignal.timeout(2500) });
|
||||
if (!r.ok) return null; const j = await r.json(); if (!j || !j.played) return { line: 'Not played yet' };
|
||||
return { line: (Number(j.bestDist || 0) / 1000).toFixed(2) + ' km best \u00b7 ' + Number(j.sectors || 0) + ' sector' + (Number(j.sectors) === 1 ? '' : 's') + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') };
|
||||
}
|
||||
// the player's own line on the Spooky Doors card, read from the game with a signed request (same scheme as Drip Runner)
|
||||
async function sdProgress(memberId) {
|
||||
if (SD_SECRET().length < 32) return null;
|
||||
@@ -3080,6 +3117,17 @@ const server = http.createServer(async (req, res) => {
|
||||
sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000);
|
||||
res.writeHead(302, { Location: SD_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
|
||||
}
|
||||
// -- Road Agent hand-off (2026-10-07): sign the member across; the game verifies with RA_SSO_SECRET
|
||||
if (p === '/api/my/roadagent' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
const raRef = String(u.searchParams.get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
|
||||
if (!s || !s.email) { res.writeHead(302, { Location: '/my' + (raRef ? '?ref=' + encodeURIComponent(raRef) : ''), 'Set-Cookie': gkCookie('iap.return', 'roadagent', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
if (RA_SECRET().length < 32) return json(res, 503, { error: 'Road Agent is not connected yet.' });
|
||||
const acct = await accounts.byEmail(s.email);
|
||||
const tok = gMint(DOOR_GAMES().roadagent, { kind: 'sso', memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || s.address || null,
|
||||
sponsorRef: (acct && acct.sponsorRef) || null, joinedRef: (acct && acct.joinedRef) || null, joinedAt: (acct && acct.created) || null }, 5 * 60000);
|
||||
res.writeHead(302, { Location: RA_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
|
||||
}
|
||||
// -- the Spooky Doors costume shop checkout: the Crown shop flow with a Halloween coat (confirm, spend, signed receipt back)
|
||||
if (p === '/sd/shop' && req.method === 'GET') {
|
||||
const t = u.searchParams.get('t') || ''; const r = sdOpen(t, 'That order has expired. Go back to Spooky Doors and open the costume shop again.');
|
||||
@@ -3250,8 +3298,8 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
// -- Spooky Doors door: a real verified visit of kind 'door' (own daily cap, advertiser charged as usual); the player gets candy, not credits
|
||||
if (p === '/api/door/open' && req.method === 'GET') {
|
||||
const r = sdOpen(u.searchParams.get('t'), 'That door link has expired. Go back to Spooky Doors and knock again.'); if (r.error) return json(res, 400, { error: r.error });
|
||||
const c = r.claims; if (c.kind !== 'door' || !c.nonce || !c.email || !sdIsGameUrl(c.ret)) return json(res, 400, { error: 'That is not a door link.' });
|
||||
const r = doorOpen(u.searchParams.get('t')); if (r.error) return json(res, 400, { error: r.error });
|
||||
const c = r.claims; if (c.kind !== 'door' || !c.nonce || !c.email || !gameUrlOk(r.game, c.ret)) return json(res, 400, { error: 'That is not a door link.' });
|
||||
for (const [n, v] of doorTokens) if (v.ts + 30 * 60000 < Date.now()) doorTokens.delete(n);
|
||||
let t = doorTokens.get(c.nonce);
|
||||
if (t && t.done) return json(res, 200, { done: true, ret: t.doneRet || t.ret });
|
||||
@@ -3262,21 +3310,21 @@ const server = http.createServer(async (req, res) => {
|
||||
// door packs + Golden Doors first (golden, then doors; once per player per Central day), then the existing chain
|
||||
const pack = await ads.serveDoorPack(email, viewerGeo(req));
|
||||
const ad = pack || await ads.serveVisit(email, viewerGeo(req), { kind: 'door' }); // doors may repeat a campaign after doorRepeatDays
|
||||
if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false,
|
||||
if (ad) t = { kind: 'visit', game: r.game, email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false,
|
||||
credits: pack ? pack.credits : (ads.rates().visitCostPerVisit || 3), golden: !!(pack && pack.golden), bonus: (pack && pack.golden) ? sdGoldenBonus() : 0 };
|
||||
else { // every visit pack already visited: a member video ad instead, one door per video per person
|
||||
const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req)));
|
||||
if (v) t = { kind: 'video', email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
|
||||
if (v) t = { kind: 'video', game: r.game, email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false };
|
||||
else { // nothing left on the street: a house ad (one of Marty's programs, a smaller treat); none=1 only when the list is empty
|
||||
const h = await doorHousePick(email, c.username);
|
||||
if (!h) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') });
|
||||
t = { kind: 'house', email, memberId: Number(c.memberId) || 0, id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
|
||||
t = { kind: 'house', game: r.game, email, memberId: Number(c.memberId) || 0, id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false };
|
||||
}
|
||||
}
|
||||
t.host = t.kind === 'house' ? null : await sdHost(t.id);
|
||||
doorTokens.set(c.nonce, t);
|
||||
}
|
||||
const doors = { used: status.count, cap: status.cap };
|
||||
const doors = { used: status.count, cap: status.cap, game: t.game || 'spookydoors', gameName: DOOR_GAMES()[t.game || 'spookydoors'].name };
|
||||
if (t.kind === 'video') return json(res, 200, { mode: 'video', title: t.title, host: t.host || null, doors, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) });
|
||||
if (t.kind === 'house') return json(res, 200, { mode: 'visit', house: true, program: t.program, title: t.title, host: null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) });
|
||||
return json(res, 200, Object.assign({ mode: 'visit', title: t.title, host: t.host || null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000), credits: t.credits || (ads.rates().visitCostPerVisit || 3) }, t.golden ? { golden: true, bonus: t.bonus } : {}));
|
||||
@@ -3317,8 +3365,9 @@ const server = http.createServer(async (req, res) => {
|
||||
const host = t.host || null;
|
||||
const house = t.kind === 'house' ? { house: true, program: t.program } : {}; // a house ad: credits 0, host null, campaignId 0
|
||||
const gold = (t.kind === 'visit' && t.golden) ? { golden: true, bonus: t.bonus } : {}; // a Golden Door: the game adds `bonus` candy
|
||||
const posted = await sdCallback(Object.assign({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold));
|
||||
const receipt = sdMint(Object.assign({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold), 24 * 3600000);
|
||||
const gk = t.game || 'spookydoors';
|
||||
const posted = await gameCallback(gk, Object.assign({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold));
|
||||
const receipt = gMint(DOOR_GAMES()[gk], Object.assign({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house, gold), 24 * 3600000);
|
||||
t.doneRet = sdJoin(t.ret, 'ok=1&r=' + encodeURIComponent(receipt));
|
||||
doorTokens.set(nonce, t);
|
||||
return json(res, 200, Object.assign({ ok: true, posted, host, credits, ret: t.doneRet }, house, gold));
|
||||
|
||||
Reference in New Issue
Block a user