// Sign-in by hand-off from InstantAdPay, the PolHunter pattern. There is no sign-up here and // no mailer: a member opens the game from their IAP dashboard (or the tester page sends them // through IAP), IAP signs a short-lived token with the shared secret, and this turns it into a // game session. The same signing scheme carries the refuel token to IAP and IAP's receipt back. // // Token: base64url(JSON payload) + '.' + base64url(HMAC-SHA256(secret, payload)). 'use strict'; const crypto = require('crypto'); const store = require('./store'); const SECRET = String(process.env.DR_SSO_SECRET || '').trim(); const SESSION_TTL = 30 * 86400000; const used = new Map(); // nonce -> exp (single-use guard for hand-off tokens) const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64'); const sign = payload => b64u(crypto.createHmac('sha256', SECRET).update(payload).digest()); const secure = () => process.env.NODE_ENV === 'production' ? '; Secure' : ''; function enabled() { return SECRET.length >= 32; } // the temporary id of a member with no on-chain id yet (no wallet): negative, derived from the email function emailId(email) { return -parseInt(crypto.createHash('sha256').update(String(email).toLowerCase()).digest('hex').slice(0, 11), 16); } // guests (a share link, no sign-in yet): their own negative range, far below any email id function guestFrom(req) { const m = /(?:^|;\s*)dr\.gid=([a-f0-9]{32})/.exec(req.headers.cookie || ''); if (!m) return null; const g = store.read('guests', {})[m[1]]; if (!g) return null; return { gid: m[1], memberId: g.memberId, guest: true, username: null, wallet: null, email: null, ref: g.ref || null }; } function startGuest(ref) { const gid = crypto.randomBytes(16).toString('hex'); const memberId = -(2 ** 45 + crypto.randomInt(2 ** 40)); store.update('guests', {}, g => { const cut = Date.now() - 30 * 86400000; for (const k of Object.keys(g)) if (g[k].since < cut) delete g[k]; g[gid] = { memberId, since: Date.now(), ref: ref || null }; return g; }); return { gid, memberId }; } function endGuest(gid) { store.update('guests', {}, g => { delete g[gid]; return g; }); } function guestCookie(gid) { return 'dr.gid=' + gid + '; Path=/; Max-Age=' + 30 * 86400 + '; HttpOnly; SameSite=Lax' + secure(); } function clearGuestCookie() { return 'dr.gid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax' + secure(); } function mint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 5 * 60000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return b64u(payload) + '.' + sign(payload); } // generic check: signature + expiry, no replay guard (the caller keeps its own nonce book) function open(token) { if (!enabled()) return { error: 'Sign-in from InstantAdPay is not configured on this server.' }; const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' }; let payload; try { payload = unb64u(p).toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; } const want = sign(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 link has expired. Open Drip Runner from your InstantAdPay dashboard again.' }; return { ok: true, claims: c }; } // the hand-off: single use function verify(token) { const r = open(token); if (r.error) return r; const c = r.claims; if (!c.email) return { error: 'That sign-in link is missing your account.' }; // a free member with no wallet has no on-chain id yet: key them on their email until they link one if (!(Number(c.memberId) > 0)) c.memberId = emailId(c.email); for (const [n, exp] of used) if (exp < Date.now()) used.delete(n); if (used.has(c.nonce)) return { error: 'That sign-in link was already used.' }; used.set(c.nonce, c.exp); return { ok: true, claims: c }; } function startSession(claims) { const id = crypto.randomBytes(24).toString('hex'); store.update('sessions', {}, s => { const now = Date.now(); for (const k of Object.keys(s)) if ((s[k].since || 0) + SESSION_TTL < now) delete s[k]; s[id] = { memberId: Number(claims.memberId), email: String(claims.email).toLowerCase(), wallet: claims.wallet ? String(claims.wallet).toLowerCase() : null, username: claims.username || null, since: now }; return s; }); return id; } function cookie(id) { return 'dr.sid=' + id + '; Path=/; Max-Age=' + Math.floor(SESSION_TTL / 1000) + '; HttpOnly; SameSite=Lax' + secure(); } function clearCookie() { return 'dr.sid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax' + secure(); } function fromRequest(req) { const m = /(?:^|;\s*)dr\.sid=([a-f0-9]{48})/.exec(req.headers.cookie || ''); if (!m) return null; const s = store.read('sessions', {})[m[1]]; if (!s || (s.since || 0) + SESSION_TTL < Date.now()) return null; return Object.assign({ sid: m[1] }, s); } function endSession(sid) { store.update('sessions', {}, s => { delete s[sid]; return s; }); } function refresh(sid, claims) { store.update('sessions', {}, s => { if (s[sid]) { s[sid].wallet = claims.wallet ? String(claims.wallet).toLowerCase() : null; s[sid].username = claims.username || s[sid].username; } return s; }); } module.exports = { enabled, mint, open, verify, startSession, cookie, clearCookie, fromRequest, endSession, refresh, emailId, guestFrom, startGuest, endGuest, guestCookie, clearGuestCookie };