File size: 9,991 Bytes
fd81975
 
 
 
 
 
 
 
 
 
 
 
18f9fa9
 
 
 
0e93ff0
 
 
 
fd81975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18f9fa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd81975
 
 
 
18f9fa9
fd81975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02caec5
 
 
 
fd81975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e93ff0
 
 
fd81975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99c6696
fd81975
99c6696
fd81975
 
 
 
 
 
 
 
 
99c6696
 
 
fd81975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e93ff0
 
fd81975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99c6696
fd81975
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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}`);
});