refactor!: remove firebase leftovers, admin page on the server (P1-8)
BREAKING CHANGE: admin/cleanup.js, admin/setcoins.js and docs/firebase are gone; the admin page now runs at /admin/.
This commit is contained in:
@@ -1,90 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/* Robot Clash - Firebase cleanup. DRY-RUN by default: it only lists what it WOULD delete.
|
||||
*
|
||||
* npm install firebase-admin (once, locally)
|
||||
* node admin/cleanup.js --key serviceAccount.json # preview, deletes nothing
|
||||
* node admin/cleanup.js --key serviceAccount.json --apply # actually delete
|
||||
*
|
||||
* Options: --db <rtdb-url> --stale-min <minutes, default 10>
|
||||
* The service-account key is a SECRET: never commit or upload it (add it to .gitignore).
|
||||
*
|
||||
* Deletes (only with --apply): anonymous guest accounts (no e-mail), stale lobby/ presence,
|
||||
* and orphan saves/ ranks/ users/ nodes whose uid no longer exists in Auth.
|
||||
*/
|
||||
'use strict';
|
||||
const admin = require('firebase-admin');
|
||||
const fs = require('fs');
|
||||
|
||||
function arg(name, def) {
|
||||
const i = process.argv.indexOf('--' + name);
|
||||
if (i < 0) return def;
|
||||
const next = process.argv[i + 1];
|
||||
return next && !next.startsWith('--') ? next : true;
|
||||
}
|
||||
const keyPath = arg('key', process.env.GOOGLE_APPLICATION_CREDENTIALS);
|
||||
const DB = arg('db', 'https://robot-clash-aa37b-default-rtdb.firebaseio.com');
|
||||
const APPLY = arg('apply', false) === true;
|
||||
const STALE_MIN = +arg('stale-min', 10);
|
||||
|
||||
if (!keyPath || keyPath === true) {
|
||||
console.error('Need --key <serviceAccount.json> (or set GOOGLE_APPLICATION_CREDENTIALS).');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(JSON.parse(fs.readFileSync(keyPath, 'utf8'))),
|
||||
databaseURL: DB,
|
||||
});
|
||||
const auth = admin.auth();
|
||||
const db = admin.database();
|
||||
|
||||
(async () => {
|
||||
console.log(APPLY ? '=== APPLY: deleting ===' : '=== DRY-RUN: nothing is deleted ===');
|
||||
|
||||
// 1) all auth users; flag anonymous (no e-mail and no linked provider)
|
||||
const uids = new Set();
|
||||
const anon = [];
|
||||
let pageToken;
|
||||
do {
|
||||
const res = await auth.listUsers(1000, pageToken);
|
||||
for (const u of res.users) {
|
||||
uids.add(u.uid);
|
||||
const registered = !!u.email || (u.providerData && u.providerData.length > 0);
|
||||
if (!registered) anon.push(u.uid);
|
||||
}
|
||||
pageToken = res.pageToken;
|
||||
} while (pageToken);
|
||||
console.log(`Auth users: ${uids.size} total, ${anon.length} anonymous/guest`);
|
||||
|
||||
// 2) stale lobby presence (no ts or older than the cutoff)
|
||||
const cutoff = Date.now() - STALE_MIN * 60000;
|
||||
const lobby = (await db.ref('lobby').get()).val() || {};
|
||||
const staleLobby = Object.entries(lobby).filter(([, v]) => !v || !v.ts || v.ts < cutoff).map(([k]) => k);
|
||||
console.log(`Lobby: ${Object.keys(lobby).length} entries, ${staleLobby.length} stale (> ${STALE_MIN} min)`);
|
||||
|
||||
// 3) orphan RTDB nodes (uid no longer exists in Auth)
|
||||
const orphans = {};
|
||||
for (const node of ['saves', 'ranks', 'users']) {
|
||||
const data = (await db.ref(node).get()).val() || {};
|
||||
orphans[node] = Object.keys(data).filter(uid => !uids.has(uid));
|
||||
console.log(`${node}: ${Object.keys(data).length} entries, ${orphans[node].length} orphan`);
|
||||
}
|
||||
|
||||
if (!APPLY) {
|
||||
console.log('\nWould delete:');
|
||||
console.log(' anonymous accounts :', anon.length);
|
||||
console.log(' stale lobby :', staleLobby.length);
|
||||
for (const node of Object.keys(orphans)) console.log(` orphan ${node.padEnd(12)}:`, orphans[node].length);
|
||||
console.log('\nRe-run with --apply to actually delete.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
let n = 0;
|
||||
for (let i = 0; i < anon.length; i += 1000) { const r = await auth.deleteUsers(anon.slice(i, i + 1000)); n += r.successCount; }
|
||||
console.log(`Deleted ${n} anonymous accounts.`);
|
||||
for (const uid of staleLobby) await db.ref('lobby/' + uid).remove();
|
||||
console.log(`Removed ${staleLobby.length} stale lobby entries.`);
|
||||
for (const node of Object.keys(orphans)) { for (const uid of orphans[node]) await db.ref(node + '/' + uid).remove(); console.log(`Removed ${orphans[node].length} orphan ${node}.`); }
|
||||
console.log('Done.');
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -5,10 +5,9 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Robot Clash – Admin</title>
|
||||
<!--
|
||||
Robot Clash backend admin. LOCAL TOOL ONLY - open by double-click, never upload.
|
||||
It only works for the one Firebase account whose UID is in the database rules (node "live"),
|
||||
so even if this file leaked it could not change anything without that account's password.
|
||||
Writes to /live, which every player reads (RC.Live in game/live.js).
|
||||
Robot Clash backend admin, served by the game server at /admin/ (e.g. https://roboclash.michael-media.de/admin/).
|
||||
Saving needs an account with role 'admin' (seed accounts michi / benni, see server/scripts/reset-db.js) -
|
||||
the server checks it, the page itself grants nothing. Writes the live settings every player reads (game/live.js).
|
||||
-->
|
||||
<style>
|
||||
:root { --bg:#0b0e13; --panel:#161b22; --panel2:#1d232d; --line:#2d3442; --text:#e8ebf2; --dim:#8d95a8;
|
||||
@@ -62,9 +61,9 @@
|
||||
<!-- login -->
|
||||
<div class="card" id="login">
|
||||
<h2>Anmelden</h2>
|
||||
<p class="muted">Mit dem Admin-Konto (E-Mail + Master-Passwort), dessen UID in den Firebase-Regeln steht.</p>
|
||||
<p class="muted">Mit einem Spielkonto, das auf dem Server Admin-Recht hat (z. B. michi oder benni).</p>
|
||||
<div class="row">
|
||||
<div><label>E-Mail</label><input type="email" id="mail" autocomplete="username"></div>
|
||||
<div><label>Name oder E-Mail</label><input type="text" id="mail" autocomplete="username"></div>
|
||||
<div><label>Passwort</label><input type="password" id="pass" autocomplete="current-password"></div>
|
||||
</div>
|
||||
<div class="bar"><button class="primary" id="bLogin">Anmelden</button></div>
|
||||
@@ -140,17 +139,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../game/kit/kit-core.js"></script>
|
||||
<script src="../game/parts.js"></script>
|
||||
<script src="../game/robot.js"></script>
|
||||
<script src="../game/combat.js"></script>
|
||||
<script src="../game/net.js"></script>
|
||||
<script src="/kit/kit-core.js"></script>
|
||||
<script src="/kit/kit-scores.js"></script>
|
||||
<script src="/parts.js"></script>
|
||||
<script src="/robot.js"></script>
|
||||
<script src="/combat.js"></script>
|
||||
<script src="/protocol.js"></script>
|
||||
<script src="/net.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
var RC = window.RC, Kit = window.Kit;
|
||||
var net = RC.Net({ apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w',
|
||||
dbUrl: 'https://robot-clash-aa37b-default-rtdb.firebaseio.com' });
|
||||
var net = RC.Net({ serverUrl: '' }); // same origin: the page is served by the game server
|
||||
// tiny adapter: the page's get/put/push/del calls -> the server's admin endpoints
|
||||
var db = {
|
||||
get: function (p) { return net.api('GET', p === 'live' ? '/api/live' : '/api/admin/events'); },
|
||||
put: function (p, v) { return net.api('PUT', '/api/admin/live', v).then(function (r) { return !!(r && r.ok); }); },
|
||||
push: function (p, v) { return net.api('POST', '/api/admin/events', v).then(function (r) { return r && r.name; }); },
|
||||
del: function (p) { return net.api('DELETE', '/api/admin/events/' + encodeURIComponent(p.split('/').pop())); },
|
||||
};
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
|
||||
// ---- build the pick lists from the real game data ----
|
||||
@@ -189,7 +196,7 @@
|
||||
$('panel').classList.remove('hide');
|
||||
$('who').textContent = acc.email || acc.name;
|
||||
$('uid').textContent = acc.uid;
|
||||
$('uidHint').textContent = 'Diese UID muss in den Firebase-Regeln bei "live" (und "admin" für Vorlagen) stehen, sonst wird Speichern abgelehnt.';
|
||||
$('uidHint').textContent = net.auth.current && net.auth.current.admin ? 'Admin-Recht: ja.' : 'Kein Admin-Recht - Speichern wird vom Server abgelehnt.';
|
||||
loadLive();
|
||||
loadPresets();
|
||||
}
|
||||
@@ -228,7 +235,7 @@
|
||||
$('evOn').onchange = toggleEv;
|
||||
|
||||
function loadLive() {
|
||||
net.db.get('live').then(function (d) { fill(d || {}); });
|
||||
db.get('live').then(function (d) { fill(d || {}); });
|
||||
}
|
||||
$('bReload').onclick = loadLive;
|
||||
|
||||
@@ -260,14 +267,14 @@
|
||||
$('bSave').onclick = function () {
|
||||
var data = collect(), msg = $('saveMsg');
|
||||
msg.className = 'status'; msg.textContent = 'Speichern…';
|
||||
net.db.put('live', data).then(function (ok) {
|
||||
db.put('live', data).then(function (ok) {
|
||||
if (ok) { msg.className = 'status ok'; msg.textContent = 'Gespeichert – alle Spieler sehen es sofort.'; $('dump').textContent = JSON.stringify(data, null, 2); }
|
||||
else { msg.className = 'status err'; msg.textContent = 'Abgelehnt. Steht deine UID in den Firebase-Regeln bei "live"?'; }
|
||||
else { msg.className = 'status err'; msg.textContent = 'Abgelehnt. Hat dein Konto Admin-Recht?'; }
|
||||
});
|
||||
};
|
||||
$('bClear').onclick = function () {
|
||||
if (!confirm('Wirklich alles zurücksetzen? Danach läuft kein Event, keine Nachricht, keine Sperre.')) return;
|
||||
net.db.put('live', {}).then(function (ok) {
|
||||
db.put('live', {}).then(function (ok) {
|
||||
var msg = $('saveMsg');
|
||||
msg.className = ok ? 'status ok' : 'status err';
|
||||
msg.textContent = ok ? 'Zurückgesetzt.' : 'Abgelehnt.';
|
||||
@@ -296,7 +303,7 @@
|
||||
}
|
||||
|
||||
function loadPresets() {
|
||||
net.db.get('admin/events').then(function (m) { renderPresets(m || {}); });
|
||||
db.get('admin/events').then(function (m) { renderPresets(m || {}); });
|
||||
}
|
||||
function renderPresets(m) {
|
||||
var box = $('presetList'), keys = Object.keys(m);
|
||||
@@ -317,7 +324,7 @@
|
||||
row.querySelector('[data-act="on"]').onclick = function () { activatePreset(p); };
|
||||
row.querySelector('[data-act="del"]').onclick = function () {
|
||||
if (!confirm('Vorlage „' + (p.name || '') + '“ löschen?')) return;
|
||||
net.db.del('admin/events/' + k).then(loadPresets);
|
||||
db.del('admin/events/' + k).then(loadPresets);
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -333,10 +340,10 @@
|
||||
var name = $('presetName').value.trim();
|
||||
if (!name) { alert('Bitte einen Vorlage-Namen eingeben.'); return; }
|
||||
var preset = { name: name, hours: parseInt($('presetHours').value, 10) || 48, event: eventFromForm() };
|
||||
net.db.push('admin/events', preset).then(function (key) {
|
||||
db.push('admin/events', preset).then(function (key) {
|
||||
$('presetName').value = '';
|
||||
var msg = $('saveMsg'); msg.className = key ? 'status ok' : 'status err';
|
||||
msg.textContent = key ? 'Vorlage gespeichert.' : 'Vorlage abgelehnt – steht die UID in den Regeln bei "admin"?';
|
||||
msg.textContent = key ? 'Vorlage gespeichert.' : 'Vorlage abgelehnt – hat dein Konto Admin-Recht?';
|
||||
loadPresets();
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/* Robot Clash - set a player's coins (and optionally fame) in the cloud save. For testing.
|
||||
*
|
||||
* npm install firebase-admin
|
||||
* node admin/setcoins.js --key serviceAccount.json --name SN09 --coins 2000000
|
||||
* node admin/setcoins.js --key serviceAccount.json --email me@x.de --coins 2000000 --fame 50000
|
||||
* node admin/setcoins.js --key serviceAccount.json --uid <uid> --coins 2000000
|
||||
*
|
||||
* It MERGES money/fame + a fresh ts into saves/<uid>, so the game takes it on next login (newer ts wins)
|
||||
* and the rest of the save (robots, parts) stays intact. The account must have synced at least once
|
||||
* (logged in after the cloud-save update) so a full save already exists.
|
||||
*/
|
||||
'use strict';
|
||||
const admin = require('firebase-admin');
|
||||
const fs = require('fs');
|
||||
|
||||
function arg(name, def) {
|
||||
const i = process.argv.indexOf('--' + name);
|
||||
if (i < 0) return def;
|
||||
const next = process.argv[i + 1];
|
||||
return next && !next.startsWith('--') ? next : true;
|
||||
}
|
||||
const keyPath = arg('key', process.env.GOOGLE_APPLICATION_CREDENTIALS);
|
||||
const DB = arg('db', 'https://robot-clash-aa37b-default-rtdb.firebaseio.com');
|
||||
const coins = arg('coins', undefined);
|
||||
const fame = arg('fame', undefined);
|
||||
let uid = arg('uid', undefined);
|
||||
const email = arg('email', undefined);
|
||||
const name = arg('name', undefined);
|
||||
|
||||
if (!keyPath || keyPath === true) { console.error('Need --key <serviceAccount.json>.'); process.exit(1); }
|
||||
if (coins === undefined && fame === undefined) { console.error('Need --coins <n> and/or --fame <n>.'); process.exit(1); }
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(JSON.parse(fs.readFileSync(keyPath, 'utf8'))),
|
||||
databaseURL: DB,
|
||||
});
|
||||
const auth = admin.auth();
|
||||
const db = admin.database();
|
||||
|
||||
(async () => {
|
||||
if (!uid && email) { uid = (await auth.getUserByEmail(email)).uid; }
|
||||
if (!uid && name) {
|
||||
// match the display name in users/<uid>/name (set on register/login)
|
||||
const users = (await db.ref('users').get()).val() || {};
|
||||
const hit = Object.entries(users).find(([, v]) => v && v.name === name);
|
||||
if (hit) uid = hit[0];
|
||||
if (!uid) { console.error(`No account found with name "${name}" in users/.`); process.exit(1); }
|
||||
}
|
||||
if (!uid) { console.error('Need one of --uid / --email / --name.'); process.exit(1); }
|
||||
|
||||
const snap = await db.ref('saves/' + uid).get();
|
||||
if (!snap.exists()) {
|
||||
console.error(`saves/${uid} does not exist yet. Let that account log in once (after the cloud-save update), then re-run.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const patch = { ts: Date.now() };
|
||||
if (coins !== undefined) patch.money = +coins;
|
||||
if (fame !== undefined) patch.fame = +fame;
|
||||
await db.ref('saves/' + uid).update(patch);
|
||||
console.log(`Updated saves/${uid}:`, patch, '\nThe player gets it on their next login/refresh.');
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
Reference in New Issue
Block a user