Gem Kingdom: sign-in hand-off (/api/my/gemkingdom), Games card (admin preview until gamesLive), Crown shop checkout (/gk/shop: confirm, short -> top-up detour with dashboard banner back, confirm spends credits via ads.gamePurchase, signed receipt redirect + server callback); game purchases skip refill notices and the campaign list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
# Gem Kingdom on InstantAdPay (2026-10-01): sign-in hand-off, Games card, and the Crown shop checkout with its return trip.
|
||||
P = 'D:/Projects/HighRisk/onchain-ad-membership/site/server.js'
|
||||
J = 'D:/Projects/HighRisk/onchain-ad-membership/site/public/assets/my.js'
|
||||
H = 'D:/Projects/HighRisk/onchain-ad-membership/site/public/my.html'
|
||||
def patch(path, edits):
|
||||
s = open(path, encoding='utf-8').read()
|
||||
for a, b in edits:
|
||||
n = s.count(a)
|
||||
if n != 1: raise SystemExit('%s: anchor count %d: %s' % (path, n, a[:100]))
|
||||
s = s.replace(a, b)
|
||||
open(path, 'w', encoding='utf-8').write(s)
|
||||
|
||||
HELPERS = r"""
|
||||
// -- Gem Kingdom (2026-10-01): sign-in hand-off + the Crown shop checkout. Same token shape as Drip Runner, its own
|
||||
// secret GK_SSO_SECRET (also set on the game). The game mints a 'gk-buy' order; this site shows the member what it
|
||||
// costs, spends the ad credits through ads.gamePurchase (credit log + on-chain burn like any flat buy), then signs a
|
||||
// 'gk-receipt' back: as a redirect to the game AND as a server-to-server callback, so Crowns land even if they never return.
|
||||
const GK_SECRET = () => String(process.env.GK_SSO_SECRET || '').trim();
|
||||
const GK_URL = () => String(process.env.GK_URL || 'https://gemkingdom.app').replace(/\/+$/, '');
|
||||
const gkSign = p => drB64u(crypto.createHmac('sha256', GK_SECRET()).update(p).digest());
|
||||
function gkMint(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) + '.' + gkSign(payload); }
|
||||
function gkOpen(token) {
|
||||
if (GK_SECRET().length < 32) return { error: 'Gem Kingdom is not connected yet.' };
|
||||
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.' }; }
|
||||
const want = gkSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
|
||||
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
if (!c.exp || Date.now() > c.exp) return { error: 'That order has expired. Go back to Gem Kingdom and open the shop again.' };
|
||||
return { ok: true, claims: c };
|
||||
}
|
||||
const gkOrders = persistedMap('gkorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts }
|
||||
const gkEsc = s => String(s == null ? '' : s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch]));
|
||||
function gkPage(res, code, title, inner) {
|
||||
res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
|
||||
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + gkEsc(title) + ' | InstantAdPay</title>'
|
||||
+ '<style>body{margin:0;background:radial-gradient(ellipse 80% 50% at 50% 0%,#3B1E6E,#1B1026 70%);color:#3B1A0A;font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px 16px;box-sizing:border-box}'
|
||||
+ '.card{width:100%;max-width:440px;background:linear-gradient(180deg,#F1E2BF,#E3CC98);border-radius:12px;box-shadow:0 0 0 3px #6B4220,0 0 0 8px #3A2214,0 24px 60px rgba(0,0,0,.6);padding:26px 22px;text-align:center}'
|
||||
+ 'h1{font:700 26px/1.2 Georgia,serif;margin:0 0 6px}.sub{color:#5A3416;font-weight:700;margin:0 0 16px}.big{font:700 40px/1 Georgia,serif;color:#9A5A00;margin:8px 0}'
|
||||
+ '.row{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid rgba(90,52,22,.25);font-weight:700}.row span:first-child{color:#6A4422}'
|
||||
+ '.btn{display:block;width:100%;box-sizing:border-box;margin-top:16px;padding:14px;border:0;border-radius:12px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font:700 18px Georgia,serif;text-decoration:none;cursor:pointer;box-shadow:0 4px 0 #6A0E1C}'
|
||||
+ '.btn.blue{background:linear-gradient(180deg,#3B6FE8,#1D3FA8);box-shadow:0 4px 0 #10205A}.alt{display:inline-block;margin-top:14px;color:#5A3416;font-weight:700}.warn{color:#8A2A12;font-weight:800}.fine{font-size:13px;color:#6A4422;margin-top:14px}</style></head>'
|
||||
+ '<body><main class="card">' + inner + '</main></body></html>');
|
||||
}
|
||||
function gkFormBody(req) { return new Promise((ok, no) => { let d = ''; req.on('data', ch => { d += ch; if (d.length > 20000) req.destroy(); }); req.on('end', () => ok(new URLSearchParams(d))); req.on('error', no); }); }
|
||||
const gkCookie = (k, v, maxAge) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + maxAge + (IS_PROD ? '; Secure' : '');
|
||||
async function gkCallback(cbUrl, receipt) {
|
||||
if (!String(cbUrl || '').startsWith(GK_URL() + '/')) return false;
|
||||
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('gemkingdom callback', e.message); return false; }
|
||||
}
|
||||
"""
|
||||
|
||||
ROUTES = r""" // -- Gem Kingdom hand-off (2026-10-01): sign the member across; the game verifies with GK_SSO_SECRET
|
||||
if (p === '/api/my/gemkingdom' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Set-Cookie': gkCookie('iap.return', 'gemkingdom', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
if (GK_SECRET().length < 32) return json(res, 503, { error: 'Gem Kingdom is not connected yet.' });
|
||||
const acct = await accounts.byEmail(s.email);
|
||||
const tok = gkMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
|
||||
res.writeHead(302, { Location: GK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
|
||||
}
|
||||
// -- the Crown shop checkout: confirm, spend the credits, sign a receipt back to the game
|
||||
if (p === '/gk/shop' && req.method === 'GET') {
|
||||
const t = u.searchParams.get('t') || ''; const r = gkOpen(t);
|
||||
if (r.error) return gkPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="sub">' + gkEsc(r.error) + '</p><a class="btn blue" href="' + GK_URL() + '/play?open=shop">Back to Gem Kingdom</a>');
|
||||
const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '<h1>That is not a Crown order</h1>');
|
||||
const done = gkOrders.get(c.order);
|
||||
if (done && done.status === 'paid') { const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: c.email, crowns: c.crowns, credits: c.credits, ref: done.campaignId }, 24 * 3600000); res.writeHead(302, { Location: c.ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.gkshop', t, 7200), gkCookie('iap.return', 'gkshop', 1800)] }); return res.end(); }
|
||||
if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '<h1>Different account</h1><p class="sub">This order was started by the Gem Kingdom player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.</p><a class="btn blue" href="' + GK_URL() + '/play">Back to Gem Kingdom</a>');
|
||||
const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email);
|
||||
const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 };
|
||||
const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail);
|
||||
const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0);
|
||||
const head = '<p class="sub">Gem Kingdom · Crown Shop</p><h1>' + gkEsc(c.label || 'Crowns') + '</h1><div class="big">' + Number(c.crowns) + ' Crowns</div>'
|
||||
+ '<div class="row"><span>Price</span><span>' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')</span></div>'
|
||||
+ '<div class="row"><span>Your available credits</span><span>' + Number(bal.available || 0).toLocaleString('en-US') + '</span></div>';
|
||||
if (can) {
|
||||
const csrf = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase());
|
||||
return gkPage(res, 200, 'Confirm your Crowns', head + '<form method="post" action="/gk/shop/confirm"><input type="hidden" name="t" value="' + gkEsc(t) + '"><input type="hidden" name="csrf" value="' + csrf + '"><button class="btn" type="submit">Spend ' + Number(c.credits).toLocaleString('en-US') + ' credits</button></form>'
|
||||
+ '<a class="alt" href="' + GK_URL() + '/play?open=shop">Cancel and go back</a><p class="fine">Crowns are game items. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.</p>');
|
||||
}
|
||||
const need = c.credits - usable;
|
||||
return gkPage(res, 200, 'More credits needed', head + '<p class="warn">You need ' + need.toLocaleString('en-US') + ' more credits for this pack' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.</p>'
|
||||
+ '<a class="btn" href="/gk/shop/topup?t=' + encodeURIComponent(t) + '">Buy a credit package</a><a class="btn blue" href="' + GK_URL() + '/play?open=shop">Pick a smaller pack</a>'
|
||||
+ '<p class="fine">A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.</p>');
|
||||
}
|
||||
if (p === '/gk/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back
|
||||
const t = u.searchParams.get('t') || ''; if (gkOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); }
|
||||
res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', t, 7200) }); return res.end();
|
||||
}
|
||||
if (p === '/gk/shop/resume' && req.method === 'GET') {
|
||||
const t = parseCookies(req)['iap.gkshop']; res.writeHead(302, { Location: t ? '/gk/shop?t=' + encodeURIComponent(t) : GK_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
|
||||
}
|
||||
if (p === '/gk/shop/confirm' && req.method === 'POST') {
|
||||
const f = await gkFormBody(req); const t = f.get('t') || ''; const r = gkOpen(t);
|
||||
if (r.error) return gkPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="sub">' + gkEsc(r.error) + '</p>');
|
||||
const c = r.claims; const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '<h1>Please sign in again</h1><a class="btn blue" href="/gk/shop?t=' + encodeURIComponent(t) + '">Continue</a>');
|
||||
const want = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || '');
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Order problem', '<h1>That form expired</h1><a class="btn blue" href="/gk/shop?t=' + encodeURIComponent(t) + '">Try again</a>');
|
||||
const prev = gkOrders.get(c.order);
|
||||
if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); }
|
||||
gkOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() });
|
||||
const { ids } = await myMemberIds(s);
|
||||
const out = await ads.gamePurchase(s.email, ids, c.credits, 'Gem Kingdom: ' + c.crowns + ' Crowns', GK_URL());
|
||||
if (out.error) { gkOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } return gkPage(res, 500, 'Order problem', '<h1>Something went wrong</h1><p class="sub">' + gkEsc(out.error) + '</p>'); }
|
||||
gkOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, ts: Date.now() });
|
||||
console.log('gemkingdom crowns', s.email, c.crowns, 'for', c.credits, 'credits, campaign', out.campaignId);
|
||||
const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: String(c.email).toLowerCase(), crowns: Number(c.crowns), credits: Number(c.credits), ref: out.campaignId }, 24 * 3600000);
|
||||
gkCallback(c.cb, rc); // the server copy; the redirect below is the fast path
|
||||
const ret = String(c.ret || '').startsWith(GK_URL() + '/') ? c.ret : GK_URL() + '/api/iap/receipt';
|
||||
res.writeHead(302, { Location: ret + '?t=' + rc, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', '', 0) }); return res.end();
|
||||
}
|
||||
"""
|
||||
|
||||
patch(P, [
|
||||
("// -- the games registry (2026-10-01).", HELPERS + "\n// -- the games registry (2026-10-01)."),
|
||||
(" { slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt',",
|
||||
" { 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.',\n"
|
||||
" art: GK_URL() + '/fantasy/bg.jpg', play: '/api/my/gemkingdom', cta: 'Play', pays: 'Game rewards; Crowns from ad credits' },\n"
|
||||
" { slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt',"),
|
||||
(" // -- PassiveDrip card on the Earn tab", ROUTES + " // -- PassiveDrip card on the Earn tab"),
|
||||
("returnTo: ['polhunter', 'driprunner', 'passivedrip'].includes(", "returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop'].includes("),
|
||||
("next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip' })[parseCookies(req)['iap.return']] || null",
|
||||
"next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume' })[parseCookies(req)['iap.return']] || null"),
|
||||
])
|
||||
patch(J, [
|
||||
(" if (me.returnTo === 'passivedrip' && !render.toGame) {",
|
||||
" if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01)\n"
|
||||
" if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }\n"
|
||||
" if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \\u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); }\n"
|
||||
" if (me.returnTo === 'passivedrip' && !render.toGame) {"),
|
||||
])
|
||||
print('patched')
|
||||
Reference in New Issue
Block a user