spurenlos / src /server.js
2BPareidol1a
Logo mit echtem Alpha-Kanal (Flood-Fill: Verlauf-Hintergrund entfernt, 512x512), MIME-Mapping für PNG, Referenzen auf logo.png
02caec5
Raw History Blame Contribute Delete
9.99 kB
const http = require('http');
const fs = require('fs');
const path = require('path');
const { randomUUID } = require('crypto');
const HOST = process.env.HOST || '127.0.0.1';
const PORT = Number(process.env.PORT || 3000);
const ROOM_TTL_MS = 60 * 60 * 1000;
const MESSAGE_TTL_MS = 60 * 1000;
// Chiffrat-Payload (base64url von AES-GCM) ist länger als Klartext.
// Der Server verarbeitet NUR Chiffrat — Klartext erreicht ihn nie.
const MAX_MESSAGE_LENGTH = 4096;
// Heartbeat-Timeout: Client pollt alle 1.8s (lastSeenAt wird dabei aktualisiert).
// Wer länger als 10s nicht pollt, gilt als abwesend (Browser-Crash, Netzabriss,
// Tab-Kill) und wird serverseitig entfernt + allen anderen gemeldet.
const PARTICIPANT_TIMEOUT_MS = 10 * 1000;
// Obergrenze pro Raum: verhindert Missbrauch als offener Broadcast-Kanal.
// Bestehende Mitglieder dürfen sich auch bei vollem Raum wieder anmelden
// (clientId identisch → wasPresent === true).
const MAX_PARTICIPANTS = 20;
const rooms = new Map();
function now() {
return Date.now();
}
function getRoom(roomKey) {
const room = rooms.get(roomKey);
if (!room) {
return null;
}
if (room.expiresAt <= now()) {
rooms.delete(roomKey);
return null;
}
return room;
}
function createRoom(roomKey) {
const ts = now();
const room = {
key: roomKey,
createdAt: ts,
expiresAt: ts + ROOM_TTL_MS,
participants: new Map(),
messages: [],
events: []
};
rooms.set(roomKey, room);
return room;
}
function sanitizeMessage(text) {
// Chiffrat ist base64url (kein Whitespace, keine Semantik für den Server).
// Nur Länge begrenzen — niemals Inhalt interpretieren oder normalisieren.
return String(text || '').slice(0, MAX_MESSAGE_LENGTH);
}
function addEvent(room, type, payload = {}) {
room.events.push({ id: randomUUID(), ts: now(), type, ...payload });
if (room.events.length > 200) {
room.events.splice(0, room.events.length - 200);
}
}
function expireRoomData(room) {
const ts = now();
room.messages = room.messages.filter((m) => m.expiresAt > ts);
}
// Entfernt Teilnehmer, deren letzter Heartbeat zu lange zurückliegt
// (unzuverlässige Client-Leave-Signale wie sendBeacon braucht der Server
// dafür nicht mehr). Erzeugt pro Entfernung ein participant_left-Event.
function expireStaleParticipants(room) {
const ts = now();
for (const [clientId, participant] of room.participants.entries()) {
if (ts - participant.lastSeenAt > PARTICIPANT_TIMEOUT_MS) {
room.participants.delete(clientId);
addEvent(room, 'participant_left', {
alias: participant.alias,
participants: room.participants.size,
reason: 'timeout'
});
}
}
}
function cleanupExpired() {
const ts = now();
for (const [key, room] of rooms.entries()) {
room.messages = room.messages.filter((m) => m.expiresAt > ts);
expireStaleParticipants(room);
if (room.expiresAt <= ts) {
rooms.delete(key);
}
}
}
function json(res, status, payload) {
const body = JSON.stringify(payload);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Cache-Control': 'no-store'
});
res.end(body);
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
if (body.length > 1_000_000) {
reject(new Error('payload_too_large'));
req.destroy();
}
});
req.on('end', () => {
if (!body) {
resolve({});
return;
}
try {
resolve(JSON.parse(body));
} catch {
reject(new Error('invalid_json'));
}
});
req.on('error', reject);
});
}
const STATIC_ROUTES = {
'/': '/index.html',
'/app': '/app.html'
};
function serveStatic(req, res) {
const base = `http://${req.headers.host || 'localhost'}`;
const pathname = new URL(req.url, base).pathname;
const urlPath = STATIC_ROUTES[pathname] || pathname;
const filePath = path.join(__dirname, 'public', path.normalize(urlPath));
if (!filePath.startsWith(path.join(__dirname, 'public'))) {
res.writeHead(403);
res.end('forbidden');
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end('not found');
return;
}
const ext = path.extname(filePath);
const contentType = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml'
}[ext] || 'application/octet-stream';
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-store'
});
res.end(data);
});
}
async function handleApi(req, res) {
const url = new URL(req.url, `http://${req.headers.host}`);
cleanupExpired();
if (req.method === 'GET' && url.pathname === '/healthz') {
return json(res, 200, {
status: 'ok',
uptimeSec: Math.round(process.uptime()),
rooms: rooms.size
});
}
if (req.method === 'POST' && url.pathname === '/api/session/join') {
const body = await readBody(req);
const roomKey = String(body.roomKey || '').trim();
const alias = String(body.alias || 'anonymous').trim().slice(0, 30) || 'anonymous';
const mode = String(body.mode || 'join').trim() === 'create' ? 'create' : 'join';
if (roomKey.length < 16) {
return json(res, 400, { error: 'room_key_too_short', minLength: 16 });
}
const clientId = String(body.clientId || randomUUID());
let room = getRoom(roomKey);
if (mode === 'join' && !room) {
return json(res, 404, { error: 'room_not_found' });
}
if (mode === 'create' && room) {
return json(res, 409, { error: 'room_already_exists' });
}
if (mode === 'create' && !room) {
room = createRoom(roomKey);
addEvent(room, 'room_created');
}
const wasPresent = room.participants.has(clientId);
if (!wasPresent && room.participants.size >= MAX_PARTICIPANTS) {
return json(res, 409, { error: 'room_full', maxParticipants: MAX_PARTICIPANTS });
}
room.participants.set(clientId, { alias, lastSeenAt: now() });
if (!wasPresent) {
addEvent(room, 'participant_joined', { alias, participants: room.participants.size });
}
return json(res, 200, {
ok: true,
clientId,
roomKey,
roomExpiresAt: room.expiresAt,
messageTtlMs: MESSAGE_TTL_MS,
roomTtlMs: ROOM_TTL_MS
});
}
if (req.method === 'POST' && url.pathname === '/api/session/leave') {
const body = await readBody(req);
const roomKey = String(body.roomKey || '').trim();
const clientId = String(body.clientId || '').trim();
const room = getRoom(roomKey);
if (!room || !clientId) {
return json(res, 200, { ok: true });
}
const participant = room.participants.get(clientId);
room.participants.delete(clientId);
if (participant) {
addEvent(room, 'participant_left', { alias: participant.alias, participants: room.participants.size });
}
return json(res, 200, { ok: true });
}
if (req.method === 'POST' && url.pathname === '/api/message/send') {
const body = await readBody(req);
const roomKey = String(body.roomKey || '').trim();
const clientId = String(body.clientId || '').trim();
// Nur Chiffrat — der Server kennt den Klartext nie.
const cipher = sanitizeMessage(body.cipher);
const room = getRoom(roomKey);
if (!room) {
return json(res, 404, { error: 'room_not_found_or_expired' });
}
if (!room.participants.has(clientId)) {
return json(res, 403, { error: 'not_joined' });
}
if (!cipher) {
return json(res, 400, { error: 'empty_message' });
}
const sender = room.participants.get(clientId);
const ts = now();
const messageId = randomUUID();
room.messages.push({
id: messageId,
cipher,
alias: sender.alias,
createdAt: ts,
expiresAt: ts + MESSAGE_TTL_MS
});
addEvent(room, 'message_sent', { alias: sender.alias });
expireRoomData(room);
// id + createdAt: der Sender kann damit seine eigene Nachricht
// identifizieren (z. B. für den Sound — niemand will den eigenen Ping hören).
return json(res, 200, { ok: true, id: messageId, createdAt: ts });
}
if (req.method === 'GET' && url.pathname === '/api/session/state') {
const roomKey = String(url.searchParams.get('roomKey') || '').trim();
const clientId = String(url.searchParams.get('clientId') || '').trim();
const sinceTs = Number(url.searchParams.get('sinceTs') || 0);
const room = getRoom(roomKey);
if (!room) {
return json(res, 404, { error: 'room_not_found_or_expired' });
}
const participant = room.participants.get(clientId);
if (!participant) {
return json(res, 403, { error: 'not_joined' });
}
participant.lastSeenAt = now();
expireRoomData(room);
return json(res, 200, {
now: now(),
roomExpiresAt: room.expiresAt,
participants: room.participants.size,
// Permanente Alias-Liste für die Teilnehmer-Anzeige im Client.
aliases: [...room.participants.values()].map((p) => p.alias),
messages: room.messages,
events: room.events.filter((e) => e.ts > sinceTs)
});
}
return json(res, 404, { error: 'not_found' });
}
const server = http.createServer(async (req, res) => {
try {
if (req.url.startsWith('/api/') || req.url.startsWith('/healthz')) {
await handleApi(req, res);
return;
}
serveStatic(req, res);
} catch (error) {
json(res, 500, { error: 'internal_error', message: error.message });
}
});
setInterval(cleanupExpired, 5000);
server.listen(PORT, HOST, () => {
console.log(`SPULO MVP listening on http://${HOST}:${PORT}`);
});