NOXBALL-SERVER / server.js
NOXBALL's picture
Update server.js
5507d8e verified
Raw History Blame Contribute Delete
30.1 kB
/* =====================================================================
NOXBALL SERVER v3 (Hugging Face Space - Docker)
- Hesap / kupa / görev / envanter verisi RAM'de (Map) tutulur: okuma-yazma anlık.
- KALICILIK (güncelleme / yeniden başlatma / yeniden build verinin silinmesin diye):
1) Yerel disk yedeği : DATA_DIR/db.json (Persistent Storage varsa /data)
2) Bulut yedeği : özel (private) bir Hugging Face DATASET deposuna db.json commit'lenir
-> Space'in diski silinse bile açılışta buradan geri yüklenir. (ÜCRETSİZ yöntem)
- Eşleşme (WebSocket) + WebRTC sinyalleşme + REST API + /admin paneli.
Ortam değişkenleri (Space > Settings > Variables and secrets):
ADMIN_KEY (SECRET) admin paneli şifresi. ZORUNLU, uzun ve rastgele olsun.
HF_TOKEN (SECRET) huggingface.co/settings/tokens -> "Write" yetkili token
HF_DATASET (Variable) örn: kullaniciadin/noxball-db (PRIVATE dataset olmalı)
DATA_DIR (opsiyonel) varsayılan /data, yoksa ./data
===================================================================== */
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { WebSocketServer } = require('ws');
const PORT = +process.env.PORT || 7860;
const ADMIN_KEY = process.env.ADMIN_KEY || '';
const HF_TOKEN = process.env.HF_TOKEN || '';
const HF_DATASET = (process.env.HF_DATASET || '').trim();
const BASLANGIC = { altin: 275, elmas: 50 };
const NICK_UCRET = 100;
const KUPA_KAZAN = 20, KUPA_KAYIP = 5, KAZAN_ALTIN = 25;
const MIN_MAC_MS = 15000;
const BULUT_ARALIK = 60000; // bulut yedeği en sık dakikada bir (HF commit limiti için)
/* ---------------- Yerel disk ---------------- */
function veriKlasoru() {
const adaylar = [process.env.DATA_DIR, '/data', path.join(__dirname, 'data')].filter(Boolean);
for (const d of adaylar) {
try { fs.mkdirSync(d, { recursive: true }); fs.accessSync(d, fs.constants.W_OK); return d; } catch (_) {}
}
return null;
}
const DATA_DIR = veriKlasoru();
const DB_DOSYA = DATA_DIR ? path.join(DATA_DIR, 'db.json') : null;
const BAK_DOSYA = DATA_DIR ? path.join(DATA_DIR, 'db.bak.json') : null;
/* ---------------- RAM veritabanı ---------------- */
const users = new Map(); // anahtar: küçük harf kullanıcı adı
const nickIndex = new Map(); // küçük harf görünen ad -> kullanıcı anahtarı
const tokens = new Map(); // sha256(token) -> { key, son } (düz token diske/buluta YAZILMAZ)
let kirli = false, bulutKirli = false, yazimTimer = null, siraCache = { t: 0, liste: [] };
let hazir = false; // veri yüklenmeden API açılmaz (boş veritabanının yedeğin üstüne yazılmasını engeller)
let sonBakYedek = 0;
const tokHash = t => crypto.createHash('sha256').update(String(t || '')).digest('hex');
/* Eski kayıtlarda olmayan alanlar tamamlanır: güncellemeler eski hesabı bozmaz */
function gocEt(u) {
if (typeof u.nr !== 'string') u.nr = '';
if (u.nd === undefined) u.nd = false;
if (u.ban === undefined) u.ban = null;
if (u.gorev === undefined) u.gorev = null;
if (u.envanter === undefined) u.envanter = null;
if (!Number.isFinite(u.altin)) u.altin = BASLANGIC.altin;
if (!Number.isFinite(u.elmas)) u.elmas = BASLANGIC.elmas;
for (const k of ['kupa', 'mac', 'gal', 'mag', 'gol']) if (!Number.isFinite(u[k])) u[k] = 0;
if (!u.olusturma) u.olusturma = Date.now();
if (!u.sonGiris) u.sonGiris = u.olusturma;
return u;
}
function dbNesnesi() {
return { surum: 3, kaydedildi: Date.now(), users: [...users.values()], tokens: [...tokens.entries()] };
}
function dbYukle(j) {
users.clear(); nickIndex.clear(); tokens.clear();
for (const u0 of j.users || []) { const u = gocEt(u0); users.set(u.key, u); nickIndex.set(u.ad.toLowerCase(), u.key); }
for (const [t, v] of j.tokens || []) {
const h = String(t).length === 64 ? t : tokHash(t); // eski (düz) tokenları hash'e çevir
if (v && users.has(v.key)) tokens.set(h, v);
}
}
function yerelOku() {
if (!DB_DOSYA) return null;
for (const f of [DB_DOSYA, BAK_DOSYA]) {
try { return JSON.parse(fs.readFileSync(f, 'utf8')); }
catch (e) { if (e.code !== 'ENOENT') console.error('[DB] Yerel okuma hatası (' + f + '):', e.message); }
}
return null;
}
function diskeYaz() {
if (!DB_DOSYA) return;
const tmp = DB_DOSYA + '.tmp';
try {
const n = Date.now();
if (n - sonBakYedek > 600000 && fs.existsSync(DB_DOSYA)) { try { fs.copyFileSync(DB_DOSYA, BAK_DOSYA); sonBakYedek = n; } catch (_) {} }
fs.writeFileSync(tmp, JSON.stringify(dbNesnesi()));
fs.renameSync(tmp, DB_DOSYA); // yarım yazılmış dosya olmasın
kirli = false;
} catch (e) { console.error('[DB] Yazma hatası:', e.message); }
}
/* ---------------- Bulut yedeği (Hugging Face Dataset) ---------------- */
const bulut = { aktif: !!(HF_TOKEN && HF_DATASET), yuklendi: false, son: 0, hata: '', yazimda: false, sonIcerik: '', baslangicUye: 0 };
const HF_DOSYA = 'db.json';
async function bulutOku() {
const r = await fetch('https://huggingface.co/datasets/' + HF_DATASET + '/resolve/main/' + HF_DOSYA + '?t=' + Date.now(),
{ headers: { Authorization: 'Bearer ' + HF_TOKEN }, signal: AbortSignal.timeout(25000) });
if (r.status === 404) return null; // dosya henüz yok (ilk kurulum)
if (!r.ok) throw new Error('HTTP ' + r.status);
return await r.json();
}
async function bulutYaz(ozet) {
if (!bulut.aktif || !bulut.yuklendi || bulut.yazimda) return false;
if (users.size === 0 && bulut.baslangicUye > 0) { console.warn('[BULUT] Boş veritabanı yedeğin üstüne yazılmadı.'); return false; }
const nesne = dbNesnesi();
const karsilastir = JSON.stringify({ u: nesne.users, t: nesne.tokens });
if (karsilastir === bulut.sonIcerik) { bulutKirli = false; return true; }
bulut.yazimda = true;
try {
const icerik = Buffer.from(JSON.stringify(nesne)).toString('base64');
const govde = JSON.stringify({ key: 'header', value: { summary: ozet || ('yedek ' + new Date().toISOString()) } }) + '\n' +
JSON.stringify({ key: 'file', value: { content: icerik, path: HF_DOSYA, encoding: 'base64' } }) + '\n';
const r = await fetch('https://huggingface.co/api/datasets/' + HF_DATASET + '/commit/main', {
method: 'POST', headers: { Authorization: 'Bearer ' + HF_TOKEN, 'Content-Type': 'application/x-ndjson' },
body: govde, signal: AbortSignal.timeout(40000)
});
if (!r.ok) throw new Error('HTTP ' + r.status + ' ' + (await r.text()).slice(0, 160));
bulut.sonIcerik = karsilastir; bulut.son = Date.now(); bulut.hata = ''; bulutKirli = false;
return true;
} catch (e) { bulut.hata = String(e.message || e).slice(0, 200); console.error('[BULUT] Yazma hatası:', bulut.hata); return false; }
finally { bulut.yazimda = false; }
}
setInterval(() => { if (bulutKirli) bulutYaz(); }, BULUT_ARALIK);
function degisti() {
kirli = true; bulutKirli = true; siraCache.t = 0;
if (yazimTimer) return;
yazimTimer = setTimeout(() => { yazimTimer = null; if (kirli) diskeYaz(); }, 2000);
}
setInterval(() => { if (kirli) diskeYaz(); }, 30000);
let kapaniyor = false;
async function kapat() {
if (kapaniyor) return; kapaniyor = true;
try {
if (hazir) {
diskeYaz();
if (bulut.aktif) await Promise.race([bulutYaz('kapanış yedeği'), new Promise(r => setTimeout(r, 7000))]);
}
} finally { process.exit(0); }
}
['SIGTERM', 'SIGINT'].forEach(s => process.on(s, kapat));
/* Açılış: yerel + bulut verisinden DAHA YENİ olan yüklenir. Bulut okunamazsa boş başlamaz, tekrar dener. */
async function baslangicYukle() {
const yerel = yerelOku();
if (!bulut.aktif) {
if (yerel) { dbYukle(yerel); console.log('[DB] Yerel yükleme:', users.size, 'hesap'); }
else console.log('[DB] Yeni veritabanı.' + (DB_DOSYA ? '' : ' (UYARI: diske yazılamıyor)'));
if (!DB_DOSYA) console.warn('[DB] UYARI: HF_TOKEN/HF_DATASET yok ve disk yok -> yeniden başlatmada veri SİLİNİR!');
else console.warn('[DB] UYARI: Bulut yedeği kapalı. Space Persistent Storage kullanmıyorsa güncellemede veri silinir. HF_TOKEN + HF_DATASET ekle.');
hazir = true; return;
}
for (let deneme = 1; ; deneme++) {
try {
const uzak = await bulutOku();
let secilen = null, kaynak = '';
if (uzak && yerel) { secilen = (uzak.kaydedildi || 0) >= (yerel.kaydedildi || 0) ? uzak : yerel; kaynak = secilen === uzak ? 'bulut' : 'yerel'; }
else if (uzak) { secilen = uzak; kaynak = 'bulut'; }
else if (yerel) { secilen = yerel; kaynak = 'yerel'; }
if (secilen) dbYukle(secilen);
bulut.baslangicUye = uzak && Array.isArray(uzak.users) ? uzak.users.length : 0;
bulut.yuklendi = true;
if (uzak) bulut.sonIcerik = JSON.stringify({ u: uzak.users || [], t: uzak.tokens || [] });
console.log('[DB] Yüklendi (' + (kaynak || 'yeni') + '):', users.size, 'hesap');
if (kaynak === 'yerel') { bulutKirli = true; } // yerel daha yeniyse buluta da yaz
hazir = true; return;
} catch (e) {
bulut.hata = 'Açılış okuma: ' + String(e.message || e).slice(0, 120);
console.error('[BULUT] Okuma başarısız (deneme ' + deneme + '):', e.message, '- tekrar denenecek (veri korunuyor, API kapalı).');
await new Promise(r => setTimeout(r, Math.min(30000, 3000 * deneme)));
}
}
}
/* ---------------- Yardımcılar ---------------- */
const simdi = () => Date.now();
function sifreHash(sifre, tuz) {
tuz = tuz || crypto.randomBytes(16).toString('hex');
return tuz + ':' + crypto.scryptSync(sifre, tuz, 32).toString('hex');
}
function sifreDogru(sifre, kayit) {
const [tuz, h] = String(kayit).split(':');
if (!tuz || !h) return false;
const a = Buffer.from(h, 'hex'), b = crypto.scryptSync(sifre, tuz, 32);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
const adGecerli = s => typeof s === 'string' && /^[A-Za-z0-9._-]{3,16}$/.test(s);
const renkGecerli = s => s === '' || s === 'gk' || /^#[0-9a-fA-F]{6}$/.test(s);
const kostumGecerli = s => typeof s === 'string' && /^[a-z0-9_]{1,24}$/.test(s) ? s : '';
function gunAnahtari() { return new Date(Date.now() + 3 * 3600e3).toISOString().slice(0, 10); } // Türkiye saati (UTC+3)
/* ---------------- Görevler (her gün yenilenir) ---------------- */
const GOREV_TANIM = [
{ id: 'mac3', ad: '3 maç oyna', hedef: 3, ikon: '⚽', odul: { altin: 60 }, alan: 'mac' },
{ id: 'galib1', ad: '1 maç kazan', hedef: 1, ikon: '🏆', odul: { altin: 80 }, alan: 'gal' },
{ id: 'gol5', ad: '5 gol at', hedef: 5, ikon: '🥅', odul: { altin: 50, elmas: 2 }, alan: 'gol' },
{ id: 'galib3', ad: '3 maç kazan', hedef: 3, ikon: '🔥', odul: { elmas: 5 }, alan: 'gal' },
{ id: 'mac8', ad: '8 maç oyna', hedef: 8, ikon: '💪', odul: { altin: 150, elmas: 3 }, alan: 'mac' }
];
function gorevYenile(u) {
const g = gunAnahtari();
if (!u.gorev || u.gorev.gun !== g) u.gorev = { gun: g, ilerleme: {}, alindi: {} };
}
function gorevIlerlet(u, alan, miktar) {
gorevYenile(u);
for (const t of GOREV_TANIM) if (t.alan === alan) u.gorev.ilerleme[t.id] = Math.min(t.hedef, (u.gorev.ilerleme[t.id] || 0) + miktar);
}
function gorevListesi(u) {
gorevYenile(u);
return GOREV_TANIM.map(t => ({ id: t.id, ad: t.ad, ikon: t.ikon, alan: t.alan, hedef: t.hedef, odul: t.odul,
ilerleme: u.gorev.ilerleme[t.id] || 0, alindi: !!u.gorev.alindi[t.id] }));
}
/* ---------------- Hesap işlemleri ---------------- */
function profil(u) {
return { ad: u.ad, nr: u.nr || '', kupa: u.kupa, mac: u.mac, gal: u.gal, mag: u.mag, gol: u.gol, nd: !!u.nd,
altin: u.altin, elmas: u.elmas, envanter: u.envanter || null, gorevler: gorevListesi(u) };
}
function kullaniciOlustur(ad, sifre) {
const u = { key: ad.toLowerCase(), ad: ad, pass: sifreHash(sifre), olusturma: simdi(), sonGiris: simdi(),
altin: BASLANGIC.altin, elmas: BASLANGIC.elmas, envanter: null,
kupa: 0, mac: 0, gal: 0, mag: 0, gol: 0, nd: false, nr: '', ban: null, gorev: null };
users.set(u.key, u); nickIndex.set(u.ad.toLowerCase(), u.key);
degisti();
return u;
}
function tokenVer(key) {
const t = crypto.randomBytes(24).toString('hex');
tokens.set(tokHash(t), { key, son: simdi() });
degisti();
return t;
}
function tokenKullanici(t) {
const h = tokHash(t), k = tokens.get(h);
if (!k) return null;
const u = users.get(k.key);
if (!u) { tokens.delete(h); return null; }
k.son = simdi();
return u;
}
function tokenlariSil(key) { for (const [t, v] of tokens) if (v.key === key) tokens.delete(t); }
function hesapSil(key) {
const u = users.get(key);
if (!u) return false;
users.delete(key); nickIndex.delete(u.ad.toLowerCase());
tokenlariSil(key);
oyuncuAt(key, 'silindi');
degisti();
return true;
}
/* Nick değiştir: giriş adı = nick, hesap yeni anahtara taşınır. Dönüş: null (başarılı) ya da hata kodu */
function nickDegistir(u, ad) {
if (!adGecerli(ad)) return 'karakter';
if (ad === u.ad) return 'ayni';
const sahip = nickIndex.get(ad.toLowerCase());
if (sahip && sahip !== u.key) return 'ad_alinmis';
const eskiKey = u.key, yeniKey = ad.toLowerCase();
users.delete(eskiKey); nickIndex.delete(eskiKey);
u.ad = ad; u.key = yeniKey;
users.set(yeniKey, u); nickIndex.set(yeniKey, yeniKey);
for (const v of tokens.values()) if (v.key === eskiKey) v.key = yeniKey;
const ws = baglilar.get(eskiKey); if (ws) { baglilar.delete(eskiKey); ws.key = yeniKey; baglilar.set(yeniKey, ws); }
for (const m of maclar.values()) { if (m.a === eskiKey) m.a = yeniKey; if (m.b === eskiKey) m.b = yeniKey; if (m.rapor.delete(eskiKey)) m.rapor.add(yeniKey); }
degisti();
return null;
}
/* ---------------- Brute-force koruması ---------------- */
const denemeler = new Map();
function denemeKontrol(ip) {
const d = denemeler.get(ip), n = simdi();
if (d && d.kilit > n) return false;
return true;
}
function denemeKaydet(ip, basari) {
const n = simdi();
if (basari) { denemeler.delete(ip); return; }
const d = denemeler.get(ip) || { say: 0, kilit: 0 };
d.say++; if (d.say >= 8) { d.kilit = n + 60000; d.say = 0; }
denemeler.set(ip, d);
}
setInterval(() => { const n = simdi(); for (const [k, v] of denemeler) if (v.kilit < n && !v.say) denemeler.delete(k); }, 300000);
/* ---------------- Sıralama (RAM, 2 sn önbellek) ---------------- */
function siralama() {
const n = simdi();
if (n - siraCache.t < 2000) return siraCache.liste;
siraCache.liste = [...users.values()].filter(u => !u.ban).sort((a, b) => b.kupa - a.kupa || a.olusturma - b.olusturma);
siraCache.t = n;
return siraCache.liste;
}
/* ---------------- Eşleşme ---------------- */
const baglilar = new Map(); // kullanıcı key -> ws
let bekleyen = null; // { ws, key, ad, nr, ks, iz, sv, ge }
const maclar = new Map(); // matchId -> { a, b, t, rapor: Set }
let macSayac = 0;
function gonder(ws, o) { if (ws && ws.readyState === 1) { try { ws.send(JSON.stringify(o)); } catch (_) {} } }
function oyuncuAt(key, neden) {
const ws = baglilar.get(key);
if (ws) { gonder(ws, { t: 'kick', neden }); try { ws.close(); } catch (_) {} }
}
function sidIdsiz(ws) { if (bekleyen && bekleyen.ws === ws) bekleyen = null; }
function esle(a, b) {
const aHost = Math.random() < 0.5, aMavi = Math.random() < 0.5;
const id = String(++macSayac) + '-' + crypto.randomBytes(4).toString('hex');
maclar.set(id, { a: a.key, b: b.key, t: simdi(), rapor: new Set() });
a.ws.rakip = b.ws; b.ws.rakip = a.ws; a.ws.macId = b.ws.macId = id;
const paket = (x, y, host, mavi) => ({ t: 'm', id, host, renk: mavi ? 'mavi' : 'kirmizi',
rk: { ad: y.ad, nr: y.nr, ks: y.ks, iz: y.iz, sv: y.sv, ge: y.ge } });
gonder(a.ws, paket(a, b, aHost, aMavi));
gonder(b.ws, paket(b, a, !aHost, !aMavi));
}
setInterval(() => { const n = simdi(); for (const [id, m] of maclar) if (n - m.t > 3600e3) maclar.delete(id); }, 600000);
/* ---------------- HTTP / REST ---------------- */
const CORS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'content-type,x-admin-key', 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS' };
function yanit(res, kod, obj) { res.writeHead(kod, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }, CORS)); res.end(JSON.stringify(obj)); }
function govdeOku(req, limit) {
limit = limit || 20000;
return new Promise(ok => {
let s = '';
req.on('data', c => { s += c; if (s.length > limit) { s = ''; req.destroy(); } });
req.on('end', () => { try { ok(JSON.parse(s || '{}')); } catch (_) { ok({}); } });
req.on('error', () => ok({}));
});
}
const ipAl = req => String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
function adminMi(req) {
const ip = 'adm:' + ipAl(req);
if (!denemeKontrol(ip)) return false;
const k = String(req.headers['x-admin-key'] || '');
let ok = false;
if (ADMIN_KEY && k.length === ADMIN_KEY.length) ok = crypto.timingSafeEqual(Buffer.from(k), Buffer.from(ADMIN_KEY));
denemeKaydet(ip, ok);
return ok;
}
function envGecerli(e) {
if (!e || typeof e !== 'object') return null;
try { const s = JSON.stringify(e); if (s.length > 20000) return null; return JSON.parse(s); } catch (_) { return null; }
}
const ROUTES = {
async 'POST /api/auth'(req, res, b) {
const ip = ipAl(req);
if (!denemeKontrol(ip)) return yanit(res, 429, { hata: 'cok_deneme' });
const ad = String(b.ad || '').trim(), sifre = String(b.sifre || '');
if (!adGecerli(ad)) return yanit(res, 400, { hata: 'ad_gecersiz' });
if (sifre.length < 6 || sifre.length > 64) return yanit(res, 400, { hata: 'sifre_kisa' });
let u = users.get(ad.toLowerCase());
if (!u) {
if (nickIndex.has(ad.toLowerCase())) return yanit(res, 409, { hata: 'ad_alinmis' });
u = kullaniciOlustur(ad, sifre);
} else if (!sifreDogru(sifre, u.pass)) { denemeKaydet(ip, false); return yanit(res, 401, { hata: 'sifre_yanlis' }); }
denemeKaydet(ip, true);
if (u.ban) return yanit(res, 403, { hata: 'banli', sebep: u.ban.sebep || '' });
u.sonGiris = simdi();
yanit(res, 200, { token: tokenVer(u.key), profil: profil(u) });
},
async 'POST /api/me'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u) return yanit(res, 401, { hata: 'oturum' });
if (u.ban) return yanit(res, 403, { hata: 'banli', sebep: u.ban.sebep || '' });
yanit(res, 200, { profil: profil(u) });
},
async 'POST /api/logout'(req, res, b) { if (tokens.delete(tokHash(b.token))) degisti(); yanit(res, 200, { ok: 1 }); },
async 'POST /api/hesap-sil'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u) return yanit(res, 401, { hata: 'oturum' });
hesapSil(u.key);
yanit(res, 200, { ok: 1 });
},
async 'POST /api/kaydet'(req, res, b) { // altın / elmas / envanter eşitleme
const u = tokenKullanici(b.token);
if (!u || u.ban) return yanit(res, 401, { hata: 'oturum' });
const a = Math.floor(+b.altin), e = Math.floor(+b.elmas);
if (Number.isFinite(a) && Number.isFinite(e) && a >= 0 && e >= 0 && a < 1e9 && e < 1e9) { u.altin = a; u.elmas = e; }
const env = envGecerli(b.envanter); if (env) u.envanter = env;
degisti();
yanit(res, 200, { ok: 1 });
},
async 'POST /api/mac'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u || u.ban) return yanit(res, 401, { hata: 'oturum' });
const n = simdi();
if (b.bot) {
if (n - (u.sonBot || 0) < 30000) return yanit(res, 429, { hata: 'cok_sik', profil: profil(u) });
u.sonBot = n;
} else {
const m = maclar.get(String(b.mid));
if (!m || (m.a !== u.key && m.b !== u.key) || m.rapor.has(u.key)) return yanit(res, 400, { hata: 'mac_gecersiz', profil: profil(u) });
if (n - m.t < MIN_MAC_MS) return yanit(res, 400, { hata: 'cok_kisa', profil: profil(u) });
m.rapor.add(u.key);
}
const kazandi = !!b.galibiyet, gol = Math.max(0, Math.min(3, b.gol | 0));
u.mac++; if (kazandi) { u.gal++; u.kupa += KUPA_KAZAN; u.altin += KAZAN_ALTIN; } else { u.mag++; u.kupa -= Math.min(KUPA_KAYIP, u.kupa); }
u.gol += gol;
gorevIlerlet(u, 'mac', 1); if (kazandi) gorevIlerlet(u, 'gal', 1); gorevIlerlet(u, 'gol', gol);
degisti();
yanit(res, 200, { profil: profil(u) });
},
async 'POST /api/gorevler'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u || u.ban) return yanit(res, 401, { hata: 'oturum' });
yanit(res, 200, { gorevler: gorevListesi(u) });
},
async 'POST /api/gorev-al'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u || u.ban) return yanit(res, 401, { hata: 'oturum' });
gorevYenile(u);
const t = GOREV_TANIM.find(x => x.id === b.id);
if (!t) return yanit(res, 400, { hata: 'gorev_yok' });
if (u.gorev.alindi[t.id]) return yanit(res, 400, { hata: 'alindi' });
if ((u.gorev.ilerleme[t.id] || 0) < t.hedef) return yanit(res, 400, { hata: 'tamam_degil' });
u.gorev.alindi[t.id] = 1;
u.altin += t.odul.altin || 0; u.elmas += t.odul.elmas || 0;
degisti();
yanit(res, 200, { odul: t.odul, profil: profil(u) });
},
async 'POST /api/nick'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u || u.ban) return yanit(res, 401, { hata: 'oturum' });
const ad = String(b.ad || '').trim();
if (u.nd && u.altin < NICK_UCRET && adGecerli(ad) && ad !== u.ad) return yanit(res, 400, { hata: 'altin' });
const eskiAltin = u.altin;
const hata = nickDegistir(u, ad);
if (hata) return yanit(res, hata === 'ad_alinmis' ? 409 : 400, { hata });
if (u.nd) u.altin = eskiAltin - NICK_UCRET;
u.nd = true;
degisti();
yanit(res, 200, { profil: profil(u) });
},
async 'POST /api/siralama'(req, res, b) {
const u = tokenKullanici(b.token);
if (!u || u.ban) return yanit(res, 401, { hata: 'oturum' });
const liste = siralama();
const ilk = liste.slice(0, 50).map((x, i) => ({ sira: i + 1, ad: x.ad, nr: x.nr || '', kupa: x.kupa, ben: x.key === u.key }));
let benim = null;
if (!ilk.some(x => x.ben)) benim = liste.indexOf(u) + 1;
yanit(res, 200, { liste: ilk, benim });
},
/* ---------- ADMIN (yetki kontrolü sunucu girişinde yapılır) ---------- */
async 'GET /admin/stats'(req, res) {
let banli = 0, bugun = 0; const g = simdi() - 86400e3;
for (const u of users.values()) { if (u.ban) banli++; if (u.sonGiris > g) bugun++; }
yanit(res, 200, { toplam: users.size, cevrimici: baglilar.size, banli, son24saat: bugun, bekleyen: bekleyen ? 1 : 0,
aktifMac: [...baglilar.values()].filter(w => w.rakip).length / 2, disk: !!DB_DOSYA, bellekMB: Math.round(process.memoryUsage().rss / 1048576),
bulut: { aktif: bulut.aktif, son: bulut.son, hata: bulut.hata, bekliyor: bulutKirli } });
},
async 'GET /admin/users'(req, res) {
const q = (new URL(req.url, 'http://x').searchParams.get('q') || '').toLowerCase();
const liste = [...users.values()].filter(u => !q || u.key.includes(q) || u.ad.toLowerCase().includes(q))
.sort((a, b) => b.kupa - a.kupa).slice(0, 200)
.map(u => ({ ad: u.ad, nr: u.nr || '', kupa: u.kupa, mac: u.mac, altin: u.altin, elmas: u.elmas, olusturma: u.olusturma, sonGiris: u.sonGiris, ban: u.ban, cevrimici: baglilar.has(u.key) }));
yanit(res, 200, { liste });
},
async 'GET /admin/yedek'(req, res) {
res.writeHead(200, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'Content-Disposition': 'attachment; filename="noxball-db-' + new Date().toISOString().slice(0, 10) + '.json"' }, CORS));
res.end(JSON.stringify(dbNesnesi()));
},
async 'POST /admin/yedek-al'(req, res) { // şimdi buluta yaz
if (!bulut.aktif) return yanit(res, 400, { hata: 'bulut_kapali' });
const ok = await bulutYaz('admin yedeği');
yanit(res, ok ? 200 : 500, { ok: ok ? 1 : 0, hata: bulut.hata });
},
async 'POST /admin/geri-yukle'(req, res, b) { // yedek dosyasından geri yükle (tüm veriyi değiştirir)
if (b.onay !== 'EVET' || !b.veri || !Array.isArray(b.veri.users)) return yanit(res, 400, { hata: 'gecersiz' });
dbYukle(b.veri); bulut.baslangicUye = users.size; degisti(); diskeYaz();
yanit(res, 200, { ok: 1, hesap: users.size });
},
async 'POST /admin/ban'(req, res, b) {
const u = users.get(String(b.ad || '').toLowerCase());
if (!u) return yanit(res, 404, { hata: 'yok' });
u.ban = { sebep: String(b.sebep || '').slice(0, 120), t: simdi() };
tokenlariSil(u.key);
oyuncuAt(u.key, 'banli'); degisti();
yanit(res, 200, { ok: 1 });
},
async 'POST /admin/unban'(req, res, b) {
const u = users.get(String(b.ad || '').toLowerCase());
if (!u) return yanit(res, 404, { hata: 'yok' });
u.ban = null; degisti();
yanit(res, 200, { ok: 1 });
},
async 'POST /admin/sil'(req, res, b) {
yanit(res, hesapSil(String(b.ad || '').toLowerCase()) ? 200 : 404, { ok: 1 });
},
async 'POST /admin/duzenle'(req, res, b) { // kupa / altın / elmas düzelt
const u = users.get(String(b.ad || '').toLowerCase());
if (!u) return yanit(res, 404, { hata: 'yok' });
for (const k of ['kupa', 'altin', 'elmas']) if (Number.isFinite(+b[k]) && +b[k] >= 0 && +b[k] < 1e9) u[k] = Math.floor(+b[k]);
degisti();
yanit(res, 200, { ok: 1 });
},
async 'POST /admin/nick'(req, res, b) { // admin: oyuncunun nickini değiştir (ücretsiz)
const u = users.get(String(b.ad || '').toLowerCase());
if (!u) return yanit(res, 404, { hata: 'yok' });
const hata = nickDegistir(u, String(b.yeni || '').trim());
if (hata) return yanit(res, hata === 'ad_alinmis' ? 409 : 400, { hata });
yanit(res, 200, { ok: 1, ad: u.ad });
},
async 'POST /admin/renk'(req, res, b) { // admin: nick rengi ('' = kaldır, '#rrggbb', 'gk' = gökkuşağı)
const u = users.get(String(b.ad || '').toLowerCase());
if (!u) return yanit(res, 404, { hata: 'yok' });
const r = String(b.renk || '');
if (!renkGecerli(r)) return yanit(res, 400, { hata: 'renk' });
u.nr = r; degisti();
yanit(res, 200, { ok: 1 });
},
/* Şifreler scrypt ile HASH'lenir; geri çevrilemez, düz metin saklanmaz (bilerek). Admin yeni şifre atayabilir. */
async 'POST /admin/sifre'(req, res, b) {
const u = users.get(String(b.ad || '').toLowerCase());
if (!u) return yanit(res, 404, { hata: 'yok' });
let yeni = String(b.sifre || '');
if (!yeni) yeni = crypto.randomBytes(6).toString('base64').replace(/[^A-Za-z0-9]/g, 'x').slice(0, 10);
if (yeni.length < 6 || yeni.length > 64) return yanit(res, 400, { hata: 'sifre_kisa' });
u.pass = sifreHash(yeni);
tokenlariSil(u.key); oyuncuAt(u.key, 'oturum'); degisti();
yanit(res, 200, { ok: 1, sifre: yeni });
}
};
const server = http.createServer(async (req, res) => {
if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
const yol = req.url.split('?')[0];
if (yol === '/health' || yol === '/') { res.writeHead(200, Object.assign({ 'Content-Type': 'text/plain' }, CORS)); return res.end('ok'); }
if (yol === '/admin' || yol === '/admin/') {
try { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(fs.readFileSync(path.join(__dirname, 'admin.html'))); }
catch (_) { res.writeHead(500); return res.end('admin.html yok'); }
}
const h = ROUTES[req.method + ' ' + yol];
if (!h) return yanit(res, 404, { hata: 'yok' });
if (yol.startsWith('/admin/') && !adminMi(req)) return yanit(res, 401, { hata: 'yetkisiz' });
if (!hazir) return yanit(res, 503, { hata: 'baslatiliyor' });
try {
const body = req.method === 'POST' ? await govdeOku(req, yol === '/admin/geri-yukle' ? 40e6 : 20000) : {};
await h(req, res, body);
} catch (e) { console.error(e); yanit(res, 500, { hata: 'sunucu' }); }
});
/* ---------------- WebSocket: eşleşme + sinyal ---------------- */
const wss = new WebSocketServer({ server, maxPayload: 16384 });
wss.on('connection', ws => {
ws.canli = true; ws.key = null; ws.rakip = null;
ws.on('pong', () => { ws.canli = true; });
ws.on('message', raw => {
ws.canli = true;
let m; try { m = JSON.parse(raw); } catch (_) { return; }
if (!m || typeof m !== 'object') return;
if (m.t === 'p') return;
if (!hazir) return;
if (m.t === 'q') {
const u = tokenKullanici(m.tok);
if (!u) return gonder(ws, { t: 'kick', neden: 'oturum' });
if (u.ban) return gonder(ws, { t: 'kick', neden: 'banli' });
if (ws.key) return;
const eski = baglilar.get(u.key);
if (eski && eski !== ws) { sidIdsiz(eski); try { eski.close(); } catch (_) {} }
ws.key = u.key; baglilar.set(u.key, ws);
const o = { ws, key: u.key, ad: u.ad, nr: u.nr || '', ks: kostumGecerli(m.ks),
iz: String(m.iz || '').slice(0, 40), sv: String(m.sv || '').slice(0, 40), ge: String(m.ge || '').slice(0, 40) };
if (bekleyen && bekleyen.ws.readyState === 1 && bekleyen.key !== o.key) { const b = bekleyen; bekleyen = null; esle(b, o); }
else bekleyen = o;
return;
}
if (m.t === 'sig') { if (ws.rakip) gonder(ws.rakip, { t: 'sig', d: m.d }); return; }
if (m.t === 'x') { ayril(ws); return; }
});
ws.on('close', () => ayril(ws));
ws.on('error', () => {});
});
function ayril(ws) {
sidIdsiz(ws);
if (ws.key && baglilar.get(ws.key) === ws) baglilar.delete(ws.key);
const r = ws.rakip; ws.rakip = null;
if (r && r.rakip === ws) { r.rakip = null; gonder(r, { t: 'l' }); }
}
setInterval(() => {
for (const ws of wss.clients) { if (!ws.canli) { try { ws.terminate(); } catch (_) {} continue; } ws.canli = false; try { ws.ping(); } catch (_) {} }
}, 30000);
server.listen(PORT, () => console.log('NOXBALL sunucu :' + PORT + (ADMIN_KEY ? '' : ' (UYARI: ADMIN_KEY ayarlı değil, admin kapalı)') +
(bulut.aktif ? ' [bulut yedeği: ' + HF_DATASET + ']' : ' [bulut yedeği KAPALI]')));
baslangicYukle().catch(e => console.error('[DB] Açılış hatası:', e));