Files
instantadpay/public/assets/game-signin.js
T

135 lines
13 KiB
JavaScript

/* 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; } }
// the one-tap link carries the inviter's ref too, so a new player who taps it still gets their sponsor (2026-10-05)
function oneTapUrl(opt) { var u = String(opt.oneTap || ''), r = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); if (!r || /[?&]ref=/.test(u)) return u; return u + (u.indexOf('?') < 0 ? '?' : '&') + 'ref=' + encodeURIComponent(r); }
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[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), src = String(opt.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
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(oneTapUrl(opt)) + '">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, src: src, fts: fts, fage: Date.now() - 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, src: src, 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 };
})();