In-game sign-in for the games: /api/game/auth/{start,verify,username} (CORS for the game origins, same code guard and one-account checks), /api/game/enter for signed-in nudges, shared kit /assets/game-signin.js
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -30,7 +30,8 @@ function norm(e) { return String(e || '').trim().toLowerCase(); }
|
||||
function ipOf(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim().replace(/^::ffff:/, '').slice(0, 45); }
|
||||
function uaOf(req) { return String(req.headers['user-agent'] || '').slice(0, 200); }
|
||||
function cookies(req) { const out = {}; String(req.headers.cookie || '').split(';').forEach(p => { const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); }); return out; }
|
||||
function deviceOf(req) { const d = cookies(req)['iap.dev'] || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }
|
||||
// in-game sign-in (2026-10-03): a cross-site request carries no iap.dev cookie, so the game sends its own browser id
|
||||
function deviceOf(req) { const d = cookies(req)['iap.dev'] || (req && req.gameDev) || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }
|
||||
function newDeviceId() { return crypto.randomBytes(16).toString('hex'); }
|
||||
function deviceCookie(id, isProd) { return 'iap.dev=' + id + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (400 * 86400) + (isProd ? '; Secure' : ''); }
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
/* InstantAdPay in-game sign-in kit (2026-10-03). Served by instantadpay.com, loaded by each game's own /signin page,
|
||||
so a player signs in (or opens a free InstantAdPay account) without leaving the game. Talks to /api/game/auth/*
|
||||
from the player's browser; the game only ever receives its normal hand-off token, which it opens at /auth.
|
||||
Host page sets theme through CSS variables on .iapsi (--si-*). Usage:
|
||||
IAPSignin.mount(el, { game: 'driprunner', ref: 'skycash', oneTap: 'https://instantadpay.com/api/my/driprunner' });
|
||||
IAPSignin.enter('wallet'); // nudge: opens InstantAdPay in a new tab, already signed in */
|
||||
(function () {
|
||||
var IAP = 'https://instantadpay.com';
|
||||
try { var me = document.currentScript && document.currentScript.src; if (me) IAP = new URL(me).origin; } catch (e) {}
|
||||
var PASS_KEY = 'iap.gamepass', DEV_KEY = 'iap.gdev';
|
||||
function ls(k, v) { try { if (v === undefined) return localStorage.getItem(k); if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch (e) { return null; } }
|
||||
function devId() { var d = ls(DEV_KEY); if (!/^[a-f0-9]{32}$/.test(d || '')) { d = ''; var a = new Uint8Array(16); (window.crypto || window.msCrypto).getRandomValues(a); for (var i = 0; i < 16; i++) d += ('0' + a[i].toString(16)).slice(-2); ls(DEV_KEY, d); } return d; }
|
||||
function getPass() { try { var p = JSON.parse(ls(PASS_KEY) || 'null'); return p && p.p && p.exp > Date.now() ? p : null; } catch (e) { return null; } }
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function post(path, body) {
|
||||
return fetch(IAP + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), credentials: 'omit' })
|
||||
.then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { j._status = r.status; return j; }); })
|
||||
.catch(function () { return { _status: 0, error: 'Could not reach InstantAdPay. Check your connection and try again.' }; });
|
||||
}
|
||||
var CSS = '.iapsi{--a:var(--si-accent,#7c5cff);--ai:var(--si-accent-ink,#fff);--ink:var(--si-ink,#f2efff);--mu:var(--si-muted,#b7b0d6);--fl:var(--si-field,rgba(255,255,255,.06));--ln:var(--si-line,rgba(255,255,255,.18));color:var(--ink);font-family:var(--si-font,system-ui,sans-serif);display:grid;gap:14px}'
|
||||
+ '.iapsi h2{margin:0;font-size:22px;line-height:1.2}.iapsi p{margin:0;color:var(--mu);font-size:14.5px;line-height:1.5}.iapsi b{color:var(--ink)}'
|
||||
+ '.iapsi label.f{display:grid;gap:6px;font-size:13px;color:var(--mu)}.iapsi input.t{font:inherit;font-size:17px;padding:12px 14px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);color:var(--ink);width:100%;box-sizing:border-box}'
|
||||
+ '.iapsi input.t:focus{outline:2px solid var(--a);outline-offset:1px}.iapsi input.code{letter-spacing:.4em;text-align:center;font-size:22px}'
|
||||
+ '.iapsi .go{font:inherit;font-weight:700;font-size:16px;padding:13px 16px;border:0;border-radius:12px;background:var(--a);color:var(--ai);cursor:pointer;width:100%}.iapsi .go[disabled]{opacity:.55;cursor:default}'
|
||||
+ '.iapsi .lk{background:none;border:0;padding:0;font:inherit;font-size:13.5px;color:var(--mu);text-decoration:underline;cursor:pointer}.iapsi .lk[disabled]{opacity:.5;cursor:default;text-decoration:none}'
|
||||
+ '.iapsi form{display:grid;gap:12px;margin:0}.iapsi .row{display:flex;gap:14px;flex-wrap:wrap;justify-content:space-between}.iapsi label.ck{display:flex!important;gap:10px;align-items:flex-start;font-size:13px;color:var(--mu);margin:0}.iapsi .ck input{margin:3px 0 0;width:auto!important;flex:0 0 auto;height:auto;padding:0}.iapsi .ck span{flex:1}.iapsi .err:empty{display:none}'
|
||||
+ '.iapsi .err{color:var(--si-bad,#ff8a8a);font-size:14px;min-height:1px}.iapsi .fine{font-size:12px;color:var(--mu)}.iapsi .fine a{color:var(--mu)}'
|
||||
+ '.iapsi .hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0}.iapsi .chal{display:flex;gap:8px;flex-wrap:wrap}.iapsi .chal button{font-size:26px;width:52px;height:52px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);cursor:pointer}';
|
||||
function styleOnce() { if (document.getElementById('iapsiCss')) return; var s = document.createElement('style'); s.id = 'iapsiCss'; s.textContent = CSS; document.head.appendChild(s); }
|
||||
|
||||
function mount(el, opt) {
|
||||
styleOnce(); opt = opt || {};
|
||||
var game = opt.game, ref = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 40);
|
||||
var fts = Date.now(), email = '', newsletter = true, resendAt = 0, timer = null;
|
||||
var onToken = opt.onToken || function (t) { location.href = '/auth?t=' + encodeURIComponent(t); };
|
||||
el.classList.add('iapsi');
|
||||
function err(m) { var e = el.querySelector('.err'); if (e) e.textContent = m || ''; }
|
||||
function busy(on) { var b = el.querySelector('.go'); if (b) { b.disabled = !!on; if (on) b.dataset.l = b.textContent, b.textContent = 'One moment…'; else if (b.dataset.l) b.textContent = b.dataset.l; } }
|
||||
function done(r) {
|
||||
if (r.pass) ls(PASS_KEY, JSON.stringify({ p: r.pass, exp: Date.now() + 29 * 86400000, email: email }));
|
||||
if (r.needUsername) return stepName(r);
|
||||
if (r.token) return onToken(r.token);
|
||||
err('Something went wrong. Try again.');
|
||||
}
|
||||
function stepEmail(msg) {
|
||||
el.innerHTML = '<h2>' + esc(opt.title || 'Sign in to play') + '</h2>'
|
||||
+ '<p>Use your email. We send you a 6-digit code, no password. New here? This also opens your free <b>InstantAdPay</b> account, the home of every game in the network.</p>'
|
||||
+ '<form novalidate><label class="f">Email<input class="t" type="email" name="email" autocomplete="email" inputmode="email" required value="' + esc(email) + '"></label>'
|
||||
+ '<input class="hp" type="text" name="hp_field_x9" tabindex="-1" autocomplete="off" aria-hidden="true">'
|
||||
+ '<label class="ck"><input type="checkbox" name="nl"' + (newsletter ? ' checked' : '') + '><span>Keep me posted with the InstantAdPay newsletter (tips and updates). You can unsubscribe anytime.</span></label>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="submit">Send my code</button></form>'
|
||||
+ (opt.oneTap ? '<div class="row"><a class="lk" href="' + esc(opt.oneTap) + '">Already signed in to InstantAdPay here? One tap</a></div>' : '')
|
||||
+ '<p class="fine">By continuing you agree to the InstantAdPay <a href="' + IAP + '/terms" target="_blank" rel="noopener">Terms</a> and <a href="' + IAP + '/privacy" target="_blank" rel="noopener">Privacy</a> policy.</p>';
|
||||
var f = el.querySelector('form'); if (msg) err(msg);
|
||||
f.addEventListener('submit', function (ev) { ev.preventDefault(); send(null); });
|
||||
setTimeout(function () { var i = f.email; if (i && !email) try { i.focus(); } catch (e) {} }, 50);
|
||||
}
|
||||
function send(pick) {
|
||||
var f = el.querySelector('form');
|
||||
if (f && f.email) { email = String(f.email.value || '').trim(); newsletter = !!(f.nl && f.nl.checked); }
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return err('Enter the email you use (or want to use) for InstantAdPay.');
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/start', { game: game, email: email, ref: ref, fts: fts, hp_field_x9: (f && f.hp_field_x9 && f.hp_field_x9.value) || '', pick: pick || '', dev: devId() }).then(function (r) {
|
||||
busy(false);
|
||||
if (r.challenge) return stepChallenge(r.challenge, r.error);
|
||||
if (r.ok) { resendAt = Date.now() + 60000; return stepCode(r.devCode); }
|
||||
if (/already sent/i.test(r.error || '')) { resendAt = Date.now() + 60000; return stepCode(null, r.error); }
|
||||
err(r.error || 'Could not send the code. Try again.');
|
||||
});
|
||||
}
|
||||
function stepChallenge(ch, msg) {
|
||||
el.innerHTML = '<h2>Quick check</h2><p>' + esc(msg || 'Before we send your code:') + ' Tap the <b>' + esc(ch.prompt) + '</b>.</p><div class="chal">'
|
||||
+ ch.options.map(function (o) { return '<button type="button" data-o="' + esc(o) + '">' + esc(o) + '</button>'; }).join('') + '</div><div class="err" role="alert"></div>'
|
||||
+ '<button class="lk" type="button" data-back>Use a different email</button>';
|
||||
el.querySelectorAll('[data-o]').forEach(function (b) { b.addEventListener('click', function () { send(b.getAttribute('data-o')); }); });
|
||||
el.querySelector('[data-back]').addEventListener('click', function () { stepEmail(); });
|
||||
}
|
||||
function stepCode(devCode, msg) {
|
||||
el.innerHTML = '<h2>Check your email</h2><p>We sent a 6-digit code to <b>' + esc(email) + '</b>. It can take a minute. Not there? Check spam or promotions.</p>'
|
||||
+ '<form novalidate><label class="f">Code<input class="t code" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]*" value="' + esc(devCode || '') + '"></label>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="submit">Sign in</button></form>'
|
||||
+ '<div class="row"><button class="lk" type="button" data-again>Send a new code</button><button class="lk" type="button" data-back>Use a different email</button></div>';
|
||||
var f = el.querySelector('form'), again = el.querySelector('[data-again]'); if (msg) err(msg);
|
||||
clearInterval(timer);
|
||||
function tick() { var s = Math.ceil((resendAt - Date.now()) / 1000); again.disabled = s > 0; again.textContent = s > 0 ? 'Send a new code (' + s + 's)' : 'Send a new code'; if (s <= 0) clearInterval(timer); }
|
||||
tick(); timer = setInterval(tick, 1000);
|
||||
again.addEventListener('click', function () { clearInterval(timer); send(null); });
|
||||
el.querySelector('[data-back]').addEventListener('click', function () { clearInterval(timer); stepEmail(); });
|
||||
f.code.addEventListener('input', function () { f.code.value = f.code.value.replace(/\D/g, '').slice(0, 6); if (f.code.value.length === 6) f.requestSubmit ? f.requestSubmit() : verify(); });
|
||||
f.addEventListener('submit', function (ev) { ev.preventDefault(); verify(); });
|
||||
setTimeout(function () { try { f.code.focus(); } catch (e) {} }, 50);
|
||||
}
|
||||
function verify() {
|
||||
var f = el.querySelector('form'); var code = String((f && f.code && f.code.value) || '').trim();
|
||||
if (!/^\d{6}$/.test(code)) return err('Enter the 6 digits from the email.');
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/verify', { game: game, email: email, code: code, ref: ref, newsletter: newsletter, dev: devId() }).then(function (r) {
|
||||
busy(false);
|
||||
if (r.ok) { clearInterval(timer); return done(r); }
|
||||
if (/expired|too many/i.test(r.error || '')) { clearInterval(timer); return stepEmail(r.error); }
|
||||
err(r.error || 'That did not work. Try again.');
|
||||
});
|
||||
}
|
||||
function stepName(r) {
|
||||
el.innerHTML = '<h2>Pick your username</h2><p>This is your name in every game, on the leaderboards and in your invite link. Choose carefully: it cannot be changed later.</p>'
|
||||
+ '<form novalidate><label class="f">Username<input class="t" name="u" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="20" placeholder="3 to 20 letters, numbers or _"></label>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="submit">Save and play</button></form>';
|
||||
var f = el.querySelector('form');
|
||||
f.u.addEventListener('input', function () { f.u.value = f.u.value.replace(/[^A-Za-z0-9_]/g, '').slice(0, 20); });
|
||||
f.addEventListener('submit', function (ev) {
|
||||
ev.preventDefault(); var name = f.u.value.trim();
|
||||
if (!/^[A-Za-z0-9_]{3,20}$/.test(name)) return err('Usernames are 3 to 20 letters, numbers, or underscores.');
|
||||
if (/^\d+$/.test(name)) return err('Usernames need at least one letter.');
|
||||
var pass = getPass(); if (!pass) return stepEmail('Your sign-in expired. Start again with your email.');
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/username', { game: game, pass: pass.p, username: name }).then(function (x) { busy(false); if (x.ok) return done(x); err(x.error || 'That name did not work. Try another.'); });
|
||||
});
|
||||
setTimeout(function () { try { f.u.focus(); } catch (e) {} }, 50);
|
||||
}
|
||||
stepEmail();
|
||||
}
|
||||
|
||||
// nudge: open InstantAdPay in a new tab already signed in (the pass posts in a form, never in a URL)
|
||||
function enter(to) {
|
||||
var pass = getPass();
|
||||
if (!pass) { window.open(IAP + '/my' + (to ? '#' + to : ''), '_blank', 'noopener'); return; }
|
||||
var f = document.createElement('form'); f.method = 'POST'; f.action = IAP + '/api/game/enter'; f.target = '_blank'; f.style.display = 'none';
|
||||
[['p', pass.p], ['to', to || 'overview']].forEach(function (kv) { var i = document.createElement('input'); i.type = 'hidden'; i.name = kv[0]; i.value = kv[1]; f.appendChild(i); });
|
||||
document.body.appendChild(f); f.submit(); setTimeout(function () { f.remove(); }, 1000);
|
||||
}
|
||||
window.IAPSignin = { mount: mount, enter: enter, hasPass: function () { return !!getPass(); }, forget: function () { ls(PASS_KEY, null); }, origin: IAP };
|
||||
})();
|
||||
@@ -1411,6 +1411,56 @@ async function sdProgress(memberId) {
|
||||
return { line: Number(j.candy || 0).toLocaleString('en-US') + ' candy \u00b7 ' + Number(j.doorsToday || 0) + ' of ' + cap + ' doors today' + (Number(j.polEarned) ? ' \u00b7 ' + Number(j.polEarned).toFixed(2) + ' POL earned' : '') };
|
||||
}
|
||||
|
||||
// -- in-game sign-in (Marty, 2026-10-03: "an integrated sign-on that never leaves the game"). The game's own /signin
|
||||
// page calls these endpoints straight from the player's browser (CORS, no cookies), so the sign-up guard and the
|
||||
// one-account-per-person checks see the player's real connection. Same email code, same guard and the same account
|
||||
// as the dashboard; the answer is the game's hand-off token instead of a session cookie, plus a GAME PASS (signed
|
||||
// here, kept by the game in localStorage, 30 days) that lets the game's "open InstantAdPay" nudges arrive signed in
|
||||
// (POST /api/game/enter). The IAP device cookie cannot ride a cross-site request, so the game sends its own
|
||||
// browser id (req.gameDev) for the device checks.
|
||||
const GAME_AUTH = {
|
||||
driprunner: { name: 'Drip Runner', origins: () => [DR_URL()], host: () => DR_URL().replace(/^https?:\/\//, ''),
|
||||
mint: (a, memberId) => drMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), wallet: a.address || null, username: a.username || null,
|
||||
sponsorRef: a.sponsorRef || null, joinedRef: a.joinedRef || null, joinedAt: a.created || null }) },
|
||||
gemkingdom: { name: 'Gem Kingdom', origins: () => [GK_URL(), 'https://gemkingdom.saasy.top'], host: () => GK_URL().replace(/^https?:\/\//, ''),
|
||||
mint: (a, memberId) => gkMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
|
||||
};
|
||||
const devOrigin = o => !IS_PROD && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(o);
|
||||
function gameOf(req, slug) {
|
||||
const g = Object.prototype.hasOwnProperty.call(GAME_AUTH, String(slug || '')) ? GAME_AUTH[slug] : null; if (!g) return null;
|
||||
const o = String(req.headers.origin || '');
|
||||
return g.origins().includes(o) || devOrigin(o) ? g : null;
|
||||
}
|
||||
function gameCors(req) {
|
||||
const o = String(req.headers.origin || '');
|
||||
const ok = Object.values(GAME_AUTH).some(g => g.origins().includes(o)) || devOrigin(o);
|
||||
return ok ? { 'Access-Control-Allow-Origin': o, Vary: 'Origin', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'content-type', 'Access-Control-Max-Age': '600' } : { Vary: 'Origin' };
|
||||
}
|
||||
let gamePassKey = '';
|
||||
function gamePassSecret() {
|
||||
if (gamePassKey) return gamePassKey;
|
||||
const f = path.join(DATA_DIR, 'game-pass.secret');
|
||||
try { gamePassKey = fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
|
||||
if (gamePassKey.length < 32) { gamePassKey = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, gamePassKey, { mode: 0o600 }); } catch (e) { console.error('game pass secret', e.message); } }
|
||||
return gamePassKey;
|
||||
}
|
||||
const gamePassSign = p => drB64u(crypto.createHmac('sha256', gamePassSecret()).update(p).digest());
|
||||
function gamePassMint(email, game) { const p = JSON.stringify({ e: String(email).toLowerCase(), g: game, iat: Date.now(), exp: Date.now() + 30 * 86400000 }); return drB64u(p) + '.' + gamePassSign(p); }
|
||||
function gamePassOpen(tok) {
|
||||
const [p, sig] = String(tok || '').split('.'); if (!p || !sig) return null;
|
||||
let payload; try { payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return null; }
|
||||
const want = gamePassSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return null;
|
||||
let c; try { c = JSON.parse(payload); } catch (e) { return null; }
|
||||
return c && c.e && c.exp > Date.now() ? c : null;
|
||||
}
|
||||
const gameDevOf = b => { const d = String((b && b.dev) || ''); return /^[a-f0-9]{32}$/.test(d) ? d : ''; };
|
||||
async function gameAnswer(g, slug, acct) { // the game token (only once a username exists) + a fresh pass
|
||||
let memberId = acct.memberId || 0;
|
||||
if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
|
||||
const needUsername = !acct.username;
|
||||
return { ok: true, needUsername, username: acct.username || null, token: needUsername ? null : g.mint(acct, memberId), pass: gamePassMint(acct.email, slug) };
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
@@ -1784,6 +1834,94 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
|
||||
}
|
||||
|
||||
// -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies.
|
||||
if (p.startsWith('/api/game/auth/') && req.method === 'OPTIONS') { res.writeHead(204, gameCors(req)); return res.end(); }
|
||||
if (p === '/api/game/auth/start' && req.method === 'POST') {
|
||||
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
|
||||
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
|
||||
req.gameDev = gameDevOf(b);
|
||||
const e = String(b.email || '').trim().toLowerCase();
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }, cors);
|
||||
if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }, cors);
|
||||
const prev = emailCodes.get(e);
|
||||
if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, cors);
|
||||
const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited
|
||||
if (guard) return json(res, guard.status, guard.body, cors);
|
||||
const code = String(Math.floor(100000 + Math.random() * 900000));
|
||||
emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
|
||||
const ref = pageTok(b.ref);
|
||||
if (!(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: ref || '', via: String(b.game), joinedRef: g.host() });
|
||||
console.log('game-signin code', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'ref ' + ref : '');
|
||||
if (mailer.hasKey()) {
|
||||
try { await mailer.sendCode(e, code); } catch (err) { console.error('sendCode failed', err.message); return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, cors); }
|
||||
return json(res, 200, { ok: true, sent: true }, cors);
|
||||
}
|
||||
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, cors);
|
||||
return json(res, 503, { error: 'Email sign-in is not configured yet.' }, cors);
|
||||
}
|
||||
if (p === '/api/game/auth/verify' && req.method === 'POST') {
|
||||
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
|
||||
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
|
||||
req.gameDev = gameDevOf(b);
|
||||
const e = String(b.email || '').trim().toLowerCase();
|
||||
const rec = emailCodes.get(e);
|
||||
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }, cors);
|
||||
rec.tries += 1;
|
||||
if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }, cors); }
|
||||
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }, cors);
|
||||
emailCodes.delete(e);
|
||||
if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support.' }, cors);
|
||||
const pend = pendingSponsor.get(e);
|
||||
const ref = pageTok(b.ref) || (pend && pend.ref) || '';
|
||||
const via = String(b.game); const joinedRef = (pend && pend.joinedRef) || g.host();
|
||||
let fraudFlags = [];
|
||||
const existing = await accounts.byEmail(e);
|
||||
if (!existing) { // one account per person, exactly as on the dashboard
|
||||
let spAcct = null; if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} }
|
||||
const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e);
|
||||
fraudFlags = fc.flags;
|
||||
if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy);
|
||||
if (fc.block) { console.log('signup blocked (game)', b.game, fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }, cors); }
|
||||
}
|
||||
const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged
|
||||
if (r.error) return json(res, 400, r, cors);
|
||||
if (r.created) {
|
||||
pendingSponsor.del(e);
|
||||
fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false);
|
||||
if (b.newsletter) { drip.enqueue(e, ref, via).catch(() => {}); sendy.subscribe(e, '').catch(() => {}); }
|
||||
sendWelcome(e, ref).catch(() => {});
|
||||
console.log('game-signin new account', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'sponsor ' + ref : 'no sponsor');
|
||||
} else fraud.recordSeen(e, req).catch(() => {});
|
||||
const acct = r.account || await accounts.byEmail(e);
|
||||
return json(res, 200, Object.assign(await gameAnswer(g, b.game, acct), { created: !!r.created }), cors);
|
||||
}
|
||||
if (p === '/api/game/auth/username' && req.method === 'POST') {
|
||||
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
|
||||
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
|
||||
const pass = gamePassOpen(b.pass); if (!pass) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors);
|
||||
const before = await accounts.byEmail(pass.e); if (!before) return json(res, 404, { error: 'Account not found.' }, cors);
|
||||
if (!before.username) {
|
||||
const r = await accounts.setUsername(pass.e, b.username);
|
||||
if (r.error) return json(res, 400, r, cors);
|
||||
const acct = await accounts.byEmail(pass.e); // first username: the sponsor hears now, as from the dashboard
|
||||
notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {});
|
||||
if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() });
|
||||
}
|
||||
return json(res, 200, await gameAnswer(g, b.game, await accounts.byEmail(pass.e)), cors);
|
||||
}
|
||||
// the game's nudges ("Add your wallet", "Level up") post the pass here in a new tab: signed in on arrival
|
||||
if (p === '/api/game/enter' && req.method === 'POST') {
|
||||
let f; try { f = new URLSearchParams((await readRaw(req, 4096)).toString('utf8')); } catch (e) { f = new URLSearchParams(); }
|
||||
const pass = gamePassOpen(f.get('p'));
|
||||
const to = ['overview', 'wallet', 'buy', 'earn', 'promo', 'games', 'profile', 'campaigns'].includes(f.get('to')) ? f.get('to') : 'overview';
|
||||
if (!pass || fraud.isSuspended(pass.e)) { res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
const acct = await accounts.byEmail(pass.e); if (!acct) { res.writeHead(303, { Location: '/my', 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
let memberId = acct.memberId || 0;
|
||||
if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
|
||||
const token = await auth.mintSession({ email: acct.email, address: acct.address, memberId });
|
||||
res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store', 'Set-Cookie': auth.sessionCookie(token) }); return res.end();
|
||||
}
|
||||
|
||||
// -- wallet auth: link-to-account when an email session exists, or
|
||||
// wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session
|
||||
// is walked to the email card, which adopts the wallet on verify)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# In-game sign-in (Marty, 2026-10-03: "an integrated signon process for IAP that never leaves the game").
|
||||
# Adds /api/game/auth/{start,verify,username} (CORS for the game origins) + /api/game/enter, and lets the
|
||||
# fraud layer read a game-side browser id when the IAP device cookie cannot ride a cross-site request.
|
||||
ROOT = 'D:/Projects/HighRisk/onchain-ad-membership/site/'
|
||||
def edit(path, pairs):
|
||||
b = open(ROOT + path, 'rb').read(); crlf = b.count(b'\r\n') > b.count(b'\n') // 2
|
||||
s = b.decode('utf-8').replace('\r\n', '\n')
|
||||
for a, r in pairs:
|
||||
if s.count(a) != 1: raise SystemExit('%s anchor %d: %s' % (path, s.count(a), a[:70]))
|
||||
s = s.replace(a, r)
|
||||
if crlf: s = s.replace('\n', '\r\n')
|
||||
open(ROOT + path, 'wb').write(s.encode('utf-8')); print('patched', path)
|
||||
|
||||
HELPERS = r"""
|
||||
// -- in-game sign-in (Marty, 2026-10-03: "an integrated sign-on that never leaves the game"). The game's own /signin
|
||||
// page calls these endpoints straight from the player's browser (CORS, no cookies), so the sign-up guard and the
|
||||
// one-account-per-person checks see the player's real connection. Same email code, same guard and the same account
|
||||
// as the dashboard; the answer is the game's hand-off token instead of a session cookie, plus a GAME PASS (signed
|
||||
// here, kept by the game in localStorage, 30 days) that lets the game's "open InstantAdPay" nudges arrive signed in
|
||||
// (POST /api/game/enter). The IAP device cookie cannot ride a cross-site request, so the game sends its own
|
||||
// browser id (req.gameDev) for the device checks.
|
||||
const GAME_AUTH = {
|
||||
driprunner: { name: 'Drip Runner', origins: () => [DR_URL()], host: () => DR_URL().replace(/^https?:\/\//, ''),
|
||||
mint: (a, memberId) => drMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), wallet: a.address || null, username: a.username || null,
|
||||
sponsorRef: a.sponsorRef || null, joinedRef: a.joinedRef || null, joinedAt: a.created || null }) },
|
||||
gemkingdom: { name: 'Gem Kingdom', origins: () => [GK_URL(), 'https://gemkingdom.saasy.top'], host: () => GK_URL().replace(/^https?:\/\//, ''),
|
||||
mint: (a, memberId) => gkMint({ memberId: Number(memberId) || 0, email: String(a.email).toLowerCase(), username: a.username || null, wallet: a.address || null }) },
|
||||
};
|
||||
const devOrigin = o => !IS_PROD && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(o);
|
||||
function gameOf(req, slug) {
|
||||
const g = Object.prototype.hasOwnProperty.call(GAME_AUTH, String(slug || '')) ? GAME_AUTH[slug] : null; if (!g) return null;
|
||||
const o = String(req.headers.origin || '');
|
||||
return g.origins().includes(o) || devOrigin(o) ? g : null;
|
||||
}
|
||||
function gameCors(req) {
|
||||
const o = String(req.headers.origin || '');
|
||||
const ok = Object.values(GAME_AUTH).some(g => g.origins().includes(o)) || devOrigin(o);
|
||||
return ok ? { 'Access-Control-Allow-Origin': o, Vary: 'Origin', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'content-type', 'Access-Control-Max-Age': '600' } : { Vary: 'Origin' };
|
||||
}
|
||||
let gamePassKey = '';
|
||||
function gamePassSecret() {
|
||||
if (gamePassKey) return gamePassKey;
|
||||
const f = path.join(DATA_DIR, 'game-pass.secret');
|
||||
try { gamePassKey = fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
|
||||
if (gamePassKey.length < 32) { gamePassKey = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, gamePassKey, { mode: 0o600 }); } catch (e) { console.error('game pass secret', e.message); } }
|
||||
return gamePassKey;
|
||||
}
|
||||
const gamePassSign = p => drB64u(crypto.createHmac('sha256', gamePassSecret()).update(p).digest());
|
||||
function gamePassMint(email, game) { const p = JSON.stringify({ e: String(email).toLowerCase(), g: game, iat: Date.now(), exp: Date.now() + 30 * 86400000 }); return drB64u(p) + '.' + gamePassSign(p); }
|
||||
function gamePassOpen(tok) {
|
||||
const [p, sig] = String(tok || '').split('.'); if (!p || !sig) return null;
|
||||
let payload; try { payload = Buffer.from(p.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return null; }
|
||||
const want = gamePassSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return null;
|
||||
let c; try { c = JSON.parse(payload); } catch (e) { return null; }
|
||||
return c && c.e && c.exp > Date.now() ? c : null;
|
||||
}
|
||||
const gameDevOf = b => { const d = String((b && b.dev) || ''); return /^[a-f0-9]{32}$/.test(d) ? d : ''; };
|
||||
async function gameAnswer(g, slug, acct) { // the game token (only once a username exists) + a fresh pass
|
||||
let memberId = acct.memberId || 0;
|
||||
if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
|
||||
const needUsername = !acct.username;
|
||||
return { ok: true, needUsername, username: acct.username || null, token: needUsername ? null : g.mint(acct, memberId), pass: gamePassMint(acct.email, slug) };
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
ROUTES = r"""
|
||||
// -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies.
|
||||
if (p.startsWith('/api/game/auth/') && req.method === 'OPTIONS') { res.writeHead(204, gameCors(req)); return res.end(); }
|
||||
if (p === '/api/game/auth/start' && req.method === 'POST') {
|
||||
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
|
||||
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
|
||||
req.gameDev = gameDevOf(b);
|
||||
const e = String(b.email || '').trim().toLowerCase();
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }, cors);
|
||||
if (fraud.isBlocked(e)) return json(res, 403, { error: 'This address cannot open an account.' }, cors);
|
||||
const prev = emailCodes.get(e);
|
||||
if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }, cors);
|
||||
const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited
|
||||
if (guard) return json(res, guard.status, guard.body, cors);
|
||||
const code = String(Math.floor(100000 + Math.random() * 900000));
|
||||
emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 });
|
||||
const ref = pageTok(b.ref);
|
||||
if (!(await accounts.byEmail(e))) pendingSponsor.set(e, { ref: ref || '', via: String(b.game), joinedRef: g.host() });
|
||||
console.log('game-signin code', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'ref ' + ref : '');
|
||||
if (mailer.hasKey()) {
|
||||
try { await mailer.sendCode(e, code); } catch (err) { console.error('sendCode failed', err.message); return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }, cors); }
|
||||
return json(res, 200, { ok: true, sent: true }, cors);
|
||||
}
|
||||
if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }, cors);
|
||||
return json(res, 503, { error: 'Email sign-in is not configured yet.' }, cors);
|
||||
}
|
||||
if (p === '/api/game/auth/verify' && req.method === 'POST') {
|
||||
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
|
||||
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
|
||||
req.gameDev = gameDevOf(b);
|
||||
const e = String(b.email || '').trim().toLowerCase();
|
||||
const rec = emailCodes.get(e);
|
||||
if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }, cors);
|
||||
rec.tries += 1;
|
||||
if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }, cors); }
|
||||
if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }, cors);
|
||||
emailCodes.delete(e);
|
||||
if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support.' }, cors);
|
||||
const pend = pendingSponsor.get(e);
|
||||
const ref = pageTok(b.ref) || (pend && pend.ref) || '';
|
||||
const via = String(b.game); const joinedRef = (pend && pend.joinedRef) || g.host();
|
||||
let fraudFlags = [];
|
||||
const existing = await accounts.byEmail(e);
|
||||
if (!existing) { // one account per person, exactly as on the dashboard
|
||||
let spAcct = null; if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} }
|
||||
const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e);
|
||||
fraudFlags = fc.flags;
|
||||
if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy);
|
||||
if (fc.block) { console.log('signup blocked (game)', b.game, fc.flags.join(','), clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); fraudAlert(e, fc, spAcct, true); return json(res, 403, { error: fc.block }, cors); }
|
||||
}
|
||||
const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged
|
||||
if (r.error) return json(res, 400, r, cors);
|
||||
if (r.created) {
|
||||
pendingSponsor.del(e);
|
||||
fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false);
|
||||
if (b.newsletter) { drip.enqueue(e, ref, via).catch(() => {}); sendy.subscribe(e, '').catch(() => {}); }
|
||||
sendWelcome(e, ref).catch(() => {});
|
||||
console.log('game-signin new account', b.game, e.replace(/^(.).*(@.*)$/, '$1***$2'), ref ? 'sponsor ' + ref : 'no sponsor');
|
||||
} else fraud.recordSeen(e, req).catch(() => {});
|
||||
const acct = r.account || await accounts.byEmail(e);
|
||||
return json(res, 200, Object.assign(await gameAnswer(g, b.game, acct), { created: !!r.created }), cors);
|
||||
}
|
||||
if (p === '/api/game/auth/username' && req.method === 'POST') {
|
||||
const cors = gameCors(req); const b = await readBody(req); const g = gameOf(req, b.game);
|
||||
if (!g) return json(res, 403, { error: 'This game is not connected to InstantAdPay.' }, cors);
|
||||
const pass = gamePassOpen(b.pass); if (!pass) return json(res, 401, { error: 'Your sign-in expired. Start again with your email.' }, cors);
|
||||
const before = await accounts.byEmail(pass.e); if (!before) return json(res, 404, { error: 'Account not found.' }, cors);
|
||||
if (!before.username) {
|
||||
const r = await accounts.setUsername(pass.e, b.username);
|
||||
if (r.error) return json(res, 400, r, cors);
|
||||
const acct = await accounts.byEmail(pass.e); // first username: the sponsor hears now, as from the dashboard
|
||||
notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {});
|
||||
if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() });
|
||||
}
|
||||
return json(res, 200, await gameAnswer(g, b.game, await accounts.byEmail(pass.e)), cors);
|
||||
}
|
||||
// the game's nudges ("Add your wallet", "Level up") post the pass here in a new tab: signed in on arrival
|
||||
if (p === '/api/game/enter' && req.method === 'POST') {
|
||||
let f; try { f = new URLSearchParams((await readRaw(req, 4096)).toString('utf8')); } catch (e) { f = new URLSearchParams(); }
|
||||
const pass = gamePassOpen(f.get('p'));
|
||||
const to = ['overview', 'wallet', 'buy', 'earn', 'promo', 'games', 'profile', 'campaigns'].includes(f.get('to')) ? f.get('to') : 'overview';
|
||||
if (!pass || fraud.isSuspended(pass.e)) { res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
const acct = await accounts.byEmail(pass.e); if (!acct) { res.writeHead(303, { Location: '/my', 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
let memberId = acct.memberId || 0;
|
||||
if (!memberId && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} }
|
||||
const token = await auth.mintSession({ email: acct.email, address: acct.address, memberId });
|
||||
res.writeHead(303, { Location: '/my#' + to, 'Cache-Control': 'no-store', 'Set-Cookie': auth.sessionCookie(token) }); return res.end();
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
edit('server.js', [
|
||||
("const server = http.createServer(async (req, res) => {", HELPERS.lstrip('\n') + "const server = http.createServer(async (req, res) => {"),
|
||||
(" // -- wallet auth: link-to-account when an email session exists, or\n", ROUTES.lstrip('\n') + " // -- wallet auth: link-to-account when an email session exists, or\n"),
|
||||
])
|
||||
edit('fraud.js', [
|
||||
("function deviceOf(req) { const d = cookies(req)['iap.dev'] || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }",
|
||||
"// in-game sign-in (2026-10-03): a cross-site request carries no iap.dev cookie, so the game sends its own browser id\nfunction deviceOf(req) { const d = cookies(req)['iap.dev'] || (req && req.gameDev) || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }"),
|
||||
])
|
||||
print('ok')
|
||||
Reference in New Issue
Block a user