# 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('
' + gkEsc(r.error) + '
Back to Gem Kingdom'); const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '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.
Back to Gem Kingdom'); 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 = 'Gem Kingdom · Crown Shop
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.
'); } const need = c.credits - usable; return gkPage(res, 200, 'More credits needed', head + '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)' : '') + '.
' + 'Buy a credit packagePick a smaller pack' + 'A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.
'); } 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', '' + gkEsc(r.error) + '
'); 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', '' + gkEsc(out.error) + '
'); } 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')