Files
2026-11-05 23:47:14 +01:00

155 lines
6.3 KiB
JavaScript

// API de gestion des comptes d'Orbit.
// S'exécute avec Node uniquement (aucune dépendance) : HTTP + SQLite (node:sqlite).
// Au chargement du front, les anciens comptes stockés en localStorage sont
// importés automatiquement via POST /api/import afin de ne rien perdre.
import { createServer } from 'node:http';
import { DatabaseSync } from 'node:sqlite';
import { readFile, stat } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';
import { fileURLToPath } from 'node:url';
const PORT = Number(process.env.PORT) || 8787;
const HERE = fileURLToPath(new URL('.', import.meta.url));
const DB_PATH = process.env.ORBIT_DB || join(HERE, 'orbit.db');
const DIST_DIR = join(HERE, '..', 'dist', 'orbit', 'browser');
const db = new DatabaseSync(DB_PATH);
db.exec(`CREATE TABLE IF NOT EXISTS users (
key TEXT PRIMARY KEY,
name TEXT NOT NULL,
salt TEXT NOT NULL,
hash TEXT NOT NULL,
state TEXT NOT NULL DEFAULT '{}'
)`);
const KEY_RE = /^[a-z0-9_-]{3,16}$/;
const HASH_RE = /^[A-Za-z0-9+/=]+$/;
function readBody(req) {
return new Promise((resolve) => {
let data = '';
req.on('data', (c) => {
data += c;
if (data.length > 1_000_000) { resolve(null); req.destroy(); }
});
req.on('end', () => {
try { resolve(data ? JSON.parse(data) : null); } catch { resolve(null); }
});
req.on('error', () => resolve(null));
});
}
function send(res, status, obj) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(obj));
}
function validUserPayload(b) {
return !!b
&& typeof b.name === 'string' && b.name.length > 0 && b.name.length <= 16
&& typeof b.salt === 'string' && b.salt.length > 0
&& typeof b.hash === 'string' && HASH_RE.test(b.hash)
&& (b.state === undefined || (typeof b.state === 'object' && b.state !== null));
}
const insertUser = db.prepare('INSERT INTO users (key, name, salt, hash, state) VALUES (?, ?, ?, ?, ?)');
const getUser = db.prepare('SELECT key, name, salt, hash, state FROM users WHERE key = ?');
const setState = db.prepare('UPDATE users SET state = ? WHERE key = ?');
const countUsers = db.prepare('SELECT COUNT(*) AS n FROM users');
const listAll = db.prepare('SELECT key, name, salt, hash, state FROM users');
const server = createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const parts = url.pathname.split('/').filter(Boolean);
try {
if (parts[0] === 'api') {
// Création d'un compte (sel + hash PBKDF2 calculés côté client, comme à l'origine).
if (req.method === 'POST' && parts[1] === 'register') {
const b = await readBody(req);
if (!b || typeof b.key !== 'string' || !KEY_RE.test(b.key) || !validUserPayload(b)) {
return send(res, 400, { error: 'invalid' });
}
try {
insertUser.run(b.key, b.name, b.salt, b.hash, JSON.stringify(b.state ?? {}));
return send(res, 201, { ok: true });
} catch {
return send(res, 200, { taken: true });
}
}
// Récupération d'un compte (nécéssaire au login : le sel sert à recalculer le hash).
if (req.method === 'GET' && parts[1] === 'user' && parts[2]) {
const key = decodeURIComponent(parts[2]).toLowerCase();
if (!KEY_RE.test(key)) return send(res, 200, { missing: true });
const row = getUser.get(key);
if (!row) return send(res, 200, { missing: true });
return send(res, 200, {
key: row.key,
name: row.name,
salt: row.salt,
hash: row.hash,
state: JSON.parse(row.state || '{}')
});
}
// Sauvegarde de la progression (points, niveaux, objets...).
if (req.method === 'PUT' && parts[1] === 'state' && parts[2]) {
const key = decodeURIComponent(parts[2]).toLowerCase();
const b = await readBody(req);
if (!b || typeof b.state !== 'object' || b.state === null) {
return send(res, 400, { error: 'invalid' });
}
const info = setState.run(JSON.stringify(b.state), key);
if (info.changes === 0) return send(res, 404, { error: 'unknown user' });
return send(res, 200, { ok: true });
}
// Migration des comptes provenant de l'ancien stockage localStorage.
if (req.method === 'POST' && parts[1] === 'import') {
const b = await readBody(req);
let imported = 0;
if (b && b.users && typeof b.users === 'object') {
for (const [key, u] of Object.entries(b.users)) {
if (!KEY_RE.test(key) || !validUserPayload({ ...u, name: u && u.name })) continue;
try {
insertUser.run(key, u.name, u.salt, u.hash, JSON.stringify(u.state ?? {}));
imported++;
} catch { /* compte déjà présent : on ignore */ }
}
}
return send(res, 200, { imported });
}
if (req.method === 'GET' && parts[1] === 'stats') {
return send(res, 200, { users: countUsers.get().n });
}
return send(res, 404, { error: 'not found' });
}
// Service statique du build (préproduction) : node server/server.mjs suffit.
if (req.method === 'GET') {
const rel = normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, '');
let file = join(DIST_DIR, rel === '.' || rel === '/' || rel === '\\' ? 'index.html' : rel);
let st;
try { st = await stat(file); } catch { file = join(DIST_DIR, 'index.html'); st = await stat(file); }
if (st.isDirectory()) { file = join(DIST_DIR, 'index.html'); st = await stat(file); }
const types = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.json': 'application/json'
};
const body = await readFile(file);
res.writeHead(200, { 'Content-Type': types[extname(file).toLowerCase()] || 'application/octet-stream' });
return res.end(body);
}
return send(res, 404, { error: 'not found' });
} catch (e) {
return send(res, 500, { error: 'server error' });
}
});
server.listen(PORT, () => {
console.log(`API Orbit sur http://127.0.0.1:${PORT} (base : ${DB_PATH})`);
console.log(`Stats : GET /api/stats -> ${countUsers.get().n} compte(s)`);
});