30c95026f9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
167 lines
13 KiB
Python
167 lines
13 KiB
Python
# 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')
|