Files
kuentagym/api/server.js
T
Duarte Santos 3333b4decd openGym: Open-Source-Release als Self-Hosting-App
Rebranding GymLog → openGym. Ein-Befehl-Self-Hosting via Docker Compose:
web (nginx serviert App + Proxy /api → api, ein Origin für Passkeys), api
(Node/WebAuthn), media-Service lädt Übungs-GIFs beim ersten Start automatisch.
Passkey-Domain über .env konfigurierbar (RP_ID/ORIGIN/WEB_PORT/RP_NAME),
Secure-Cookie nur bei HTTPS (http://localhost funktioniert). MIT-Lizenz,
README fürs Self-Hosting, docs/SELF_HOSTING.md, CONTRIBUTING.md.

Standalone-Stack Ende-zu-Ende getestet (Passkey-Register/-Login, Daten-Sync,
User-Isolation über den Proxy auf http://localhost).
2026-07-19 16:18:34 +02:00

240 lines
9.6 KiB
JavaScript

/* opengym-api — passkey (WebAuthn) auth + per-user state storage for openGym
No framework, JSON-file storage, signed session cookies. */
import http from 'node:http';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse
} from '@simplewebauthn/server';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
const RP_ID = process.env.RP_ID || 'localhost';
const ORIGIN = process.env.ORIGIN || 'http://localhost:8080';
const RP_NAME = process.env.RP_NAME || 'openGym';
const SESSION_DAYS = 365;
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
fs.mkdirSync(DATA, { recursive: true });
/* ---------- secret + db ---------- */
const secretFile = path.join(DATA, 'secret');
if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(32).toString('hex'), { mode: 0o600 });
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
const dbFile = path.join(DATA, 'db.json');
let db = { users: [], creds: [] };
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2)); }
function atomicWrite(file, content) {
const tmp = file + '.tmp';
fs.writeFileSync(tmp, content);
fs.renameSync(tmp, file);
}
const stateFile = uid => path.join(DATA, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
/* ---------- sessions (signed cookie) ---------- */
function sign(payload) {
const mac = crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
return payload + '.' + mac;
}
function verifySig(token) {
const i = token.lastIndexOf('.');
if (i < 0) return null;
const payload = token.slice(0, i), mac = token.slice(i + 1);
const expect = crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
try {
if (!crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(expect))) return null;
} catch { return null; }
return payload;
}
function makeSession(uid) {
const exp = Date.now() + SESSION_DAYS * 86400000;
return sign(uid + ':' + exp);
}
function readSession(req) {
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
const i = c.indexOf('='); return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
}));
const tok = cookies.gymsid;
if (!tok) return null;
const payload = verifySig(tok);
if (!payload) return null;
const [uid, exp] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
return db.users.find(u => u.id === uid) || null;
}
function sessionCookie(uid) {
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
}
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
/* ---------- challenge store (in-memory, 5 min TTL) ---------- */
const challenges = new Map(); // cid -> {challenge, name?, uid?, exp}
function putChallenge(data) {
const cid = crypto.randomBytes(16).toString('base64url');
challenges.set(cid, { ...data, exp: Date.now() + 5 * 60000 });
return cid;
}
function takeChallenge(cid) {
const c = challenges.get(cid);
challenges.delete(cid);
if (!c || c.exp < Date.now()) return null;
return c;
}
setInterval(() => { for (const [k, v] of challenges) if (v.exp < Date.now()) challenges.delete(k); }, 60000).unref();
/* ---------- helpers ---------- */
function json(res, code, obj, extraHeaders) {
const body = JSON.stringify(obj);
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...(extraHeaders || {}) });
res.end(body);
}
function readBody(req) {
return new Promise((resolve, reject) => {
let size = 0; const chunks = [];
req.on('data', d => {
size += d.length;
if (size > MAX_BODY) { reject(new Error('body too large')); req.destroy(); return; }
chunks.push(d);
});
req.on('end', () => {
try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
catch { reject(new Error('bad json')); }
});
req.on('error', reject);
});
}
const b64uToBuf = s => Buffer.from(s, 'base64url');
/* ---------- routes ---------- */
const routes = {
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
'GET /api/me': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
json(res, 200, { user: { id: user.id, name: user.name } });
},
'POST /api/register/options': async (req, res) => {
const body = await readBody(req);
const name = String(body.name || '').trim().slice(0, 40);
if (!name) return json(res, 400, { error: 'name required' });
const uid = crypto.randomBytes(12).toString('base64url');
const options = await generateRegistrationOptions({
rpName: RP_NAME, rpID: RP_ID,
userID: Buffer.from(uid), userName: name, userDisplayName: name,
attestationType: 'none',
authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
excludeCredentials: []
});
const cid = putChallenge({ challenge: options.challenge, name, uid });
json(res, 200, { cid, options });
},
'POST /api/register/verify': async (req, res) => {
const body = await readBody(req);
const c = takeChallenge(body.cid);
if (!c || !c.uid) return json(res, 400, { error: 'challenge expired — try again' });
let verification;
try {
verification = await verifyRegistrationResponse({
response: body.credential,
expectedChallenge: c.challenge,
expectedOrigin: ORIGIN,
expectedRPID: RP_ID,
requireUserVerification: false
});
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
if (!verification.verified) return json(res, 400, { error: 'not verified' });
const { credential } = verification.registrationInfo;
if (db.creds.find(x => x.id === credential.id)) return json(res, 409, { error: 'credential already registered' });
const user = { id: c.uid, name: c.name, created: new Date().toISOString() };
db.users.push(user);
db.creds.push({
id: credential.id, userId: user.id,
publicKey: Buffer.from(credential.publicKey).toString('base64url'),
counter: credential.counter || 0,
transports: body.credential?.response?.transports || []
});
saveDb();
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
},
'POST /api/login/options': async (req, res) => {
const options = await generateAuthenticationOptions({
rpID: RP_ID, userVerification: 'preferred', allowCredentials: []
});
const cid = putChallenge({ challenge: options.challenge });
json(res, 200, { cid, options });
},
'POST /api/login/verify': async (req, res) => {
const body = await readBody(req);
const c = takeChallenge(body.cid);
if (!c) return json(res, 400, { error: 'challenge expired — try again' });
const cred = db.creds.find(x => x.id === body.credential?.id);
if (!cred) return json(res, 404, { error: 'unknown passkey — create a profile first' });
let verification;
try {
verification = await verifyAuthenticationResponse({
response: body.credential,
expectedChallenge: c.challenge,
expectedOrigin: ORIGIN,
expectedRPID: RP_ID,
requireUserVerification: false,
credential: {
id: cred.id,
publicKey: b64uToBuf(cred.publicKey),
counter: cred.counter,
transports: cred.transports
}
});
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
if (!verification.verified) return json(res, 400, { error: 'not verified' });
cred.counter = verification.authenticationInfo.newCounter;
saveDb();
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
try {
const state = JSON.parse(fs.readFileSync(stateFile(user.id), 'utf8'));
json(res, 200, { state });
} catch { json(res, 200, { state: null }); }
},
'PUT /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' });
delete body.state.active; // in-progress workouts stay device-local
atomicWrite(stateFile(user.id), JSON.stringify(body.state));
json(res, 200, { ok: true, ts: body.state._ts || null });
}
};
http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
const key = req.method + ' ' + url.pathname;
const handler = routes[key];
if (!handler) return json(res, 404, { error: 'not found' });
try { await handler(req, res); }
catch (e) {
console.error(key, e);
if (!res.headersSent) json(res, 500, { error: 'server error' });
}
}).listen(PORT, () => console.log(`gym-api on :${PORT} (rpID=${RP_ID}, origin=${ORIGIN})`));