-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
683 lines (613 loc) · 28 KB
/
server.js
File metadata and controls
683 lines (613 loc) · 28 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import { createServer } from "http";
import { readFile, writeFile, mkdir, stat, readdir } from "fs/promises";
import { join, dirname } from "path";
import { homedir } from "os";
import { randomBytes, randomUUID, createHmac, timingSafeEqual } from "crypto";
import { fileURLToPath } from "url";
import { BASE_SENSITIVE_PATTERNS, loadCustomPatterns, parseLine, extractDisplayMessage, validateShareTokenEntries, hashPassword, listSessions as _listSessions, getProjectMessages as _getProjectMessages, listProjects as _listProjects, computeProjectStats as _computeProjectStats } from "./lib.js";
// ── Load .env ───────────────────────────────────────────
const __dirname = dirname(fileURLToPath(import.meta.url));
try {
const envContent = await readFile(join(__dirname, ".env"), "utf8");
for (const line of envContent.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eq = trimmed.indexOf("=");
if (eq > 0) {
const key = trimmed.slice(0, eq).trim();
const val = trimmed.slice(eq + 1).trim();
if (!process.env[key]) process.env[key] = val;
}
}
console.log(" Loaded .env");
} catch {}
// ── Config ──────────────────────────────────────────────
const PORT = process.env.CC_LIVE_PORT || 3456;
const CLAUDE_DIR = process.env.CLAUDE_DIR || join(homedir(), ".claude");
const PROJECTS_DIR = join(CLAUDE_DIR, "projects");
const MAX_PROJECTS = 50;
const MAX_AGE_DAYS = 7;
const ONE_WEEK_MS = MAX_AGE_DAYS * 24 * 60 * 60 * 1000;
// ── State ───────────────────────────────────────────────
const clients = new Map(); // clientId -> { res, token? }
const watchedFiles = new Map(); // filepath -> { offset, sessionId, projectName, interval }
const sessions = new Map(); // sessionId -> { projectName, messages[], active }
const shareTokens = new Map(); // token -> { project, createdAt, passwordHash? }
// ── SSE helpers ─────────────────────────────────────────
function sseSend(res, event, data) {
if (res.writableEnded) return;
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}
// Heartbeat to keep SSE connections alive through proxies
setInterval(() => {
for (const [, c] of clients) {
if (!c.res.writableEnded) c.res.write(": heartbeat\n\n");
}
}, 15000);
function broadcast(event, data, projectName) {
for (const [, c] of clients) {
// If client is on a share token, only send if project matches
if (c.token) {
const share = shareTokens.get(c.token);
if (!share || share.project !== projectName) continue;
}
sseSend(c.res, event, data);
}
}
function broadcastViewerCount() {
for (const [, c] of clients) {
if (!c.res.writableEnded) sseSend(c.res, "viewer_count", { count: clients.size });
}
}
// ── Share token persistence ──────────────────────────────
const SHARE_TOKENS_FILE = join(__dirname, "data", "share-tokens.json");
async function loadShareTokens() {
try {
const content = await readFile(SHARE_TOKENS_FILE, "utf8");
const entries = JSON.parse(content);
const valid = validateShareTokenEntries(entries);
for (const [token, info] of valid) {
shareTokens.set(token, info);
}
if (shareTokens.size > 0) console.log(` Restored ${shareTokens.size} share token(s)`);
} catch (e) {
if (e.code === "ENOENT") { /* first run */ }
else if (e instanceof SyntaxError) console.warn(" share-tokens.json corrupt, starting empty");
else console.warn(" Could not load share-tokens.json:", e.message);
}
}
let _saveInProgress = false;
let _saveQueued = false;
async function saveShareTokens() {
if (_saveInProgress) { _saveQueued = true; return; }
_saveInProgress = true;
do {
_saveQueued = false;
try {
await mkdir(join(__dirname, "data"), { recursive: true });
const obj = Object.fromEntries(shareTokens);
await writeFile(SHARE_TOKENS_FILE, JSON.stringify(obj, null, 2), "utf8");
} catch (e) {
console.error(" Failed to save share tokens:", e.message);
}
} while (_saveQueued);
_saveInProgress = false;
}
// ── Share token helpers ─────────────────────────────────
const COOKIE_SECRET = randomBytes(32).toString("hex");
function signToken(token, passwordHash) {
return createHmac("sha256", COOKIE_SECRET).update(token + ":" + passwordHash).digest("hex");
}
function getCookie(req, name) {
const cookies = req.headers.cookie;
if (!cookies) return null;
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const match = cookies.match(new RegExp(`(?:^|;\\s*)${escaped}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
}
function verifyShareAuth(req, token, passwordHash) {
if (!passwordHash) return true; // no password set
const sig = getCookie(req, `cc-auth-${token}`);
if (!sig) return false;
const expected = signToken(token, passwordHash);
if (sig.length !== expected.length) return false;
return timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
}
function generateToken() {
return randomBytes(12).toString("hex"); // 24-char hex
}
function resolveToken(token) {
if (!token) return null;
return shareTokens.get(token) || null;
}
// ── Danmaku helpers ─────────────────────────────────────
const DANMAKU_DIR = join(__dirname, "data", "danmaku");
const DANMAKU_MAX_ENTRIES = 5000;
const danmakuLocks = new Map();
function escapeHtml(s) {
return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
async function loadDanmaku(project) {
try {
const safe = project.replace(/[/\\]/g, "_");
const content = await readFile(join(DANMAKU_DIR, `${safe}.json`), "utf8");
return JSON.parse(content);
} catch { return []; }
}
async function saveDanmaku(project, data) {
await mkdir(DANMAKU_DIR, { recursive: true });
const safe = project.replace(/[/\\]/g, "_");
await writeFile(join(DANMAKU_DIR, `${safe}.json`), JSON.stringify(data), "utf8");
}
// Per-project mutex to prevent read-modify-write races
async function appendDanmaku(project, entry) {
if (!danmakuLocks.has(project)) danmakuLocks.set(project, []);
const q = danmakuLocks.get(project);
if (q.length > 0) {
await new Promise(r => q.push(r));
}
try {
const existing = await loadDanmaku(project);
existing.push(entry);
// Cap at DANMAKU_MAX_ENTRIES, drop oldest
if (existing.length > DANMAKU_MAX_ENTRIES) {
existing.splice(0, existing.length - DANMAKU_MAX_ENTRIES);
}
await saveDanmaku(project, existing);
} finally {
const next = q.shift();
if (q.length === 0) danmakuLocks.delete(project);
if (next) next();
}
}
// ── JSONL parsing & redaction (imported from lib.js) ────
// ── Sensitive data redaction ──────────────────────────────
const SENSITIVE_PATTERNS = [...BASE_SENSITIVE_PATTERNS, ...loadCustomPatterns(process.env)];
if (process.env.CC_LIVE_REDACT_1) {
console.log(` Loaded ${SENSITIVE_PATTERNS.length - BASE_SENSITIVE_PATTERNS.length} custom redaction rule(s)`);
}
// ── Session file discovery ──────────────────────────────
async function findAllSessionFiles() {
const now = Date.now();
const cutoff = now - ONE_WEEK_MS;
const projectFiles = new Map(); // projectName -> [files]
try {
const dirs = await readdir(PROJECTS_DIR);
for (const dir of dirs) {
const dirPath = join(PROJECTS_DIR, dir);
let st;
try { st = await stat(dirPath); if (!st.isDirectory()) continue; } catch { continue; }
const projectName = dir.replace(/^-/, "").replace(/-/g, "/").replace(/^\//, "");
const entries = await readdir(dirPath);
const recentFiles = [];
for (const entry of entries) {
if (entry.endsWith(".jsonl")) {
const fullPath = join(dirPath, entry);
try {
const fst = await stat(fullPath);
if (fst.mtimeMs >= cutoff) {
recentFiles.push({ path: fullPath, sessionId: entry.replace(".jsonl", ""), projectName, mtime: fst.mtimeMs, size: fst.size, isSubagent: false });
}
} catch {}
}
}
if (recentFiles.length > 0) {
projectFiles.set(projectName, recentFiles);
}
}
} catch (e) { console.error("Scan error:", e.message); }
// Sort projects by most recent file mtime, take top MAX_PROJECTS
const sortedProjects = [...projectFiles.entries()]
.map(([name, files]) => ({ name, files, latestMtime: Math.max(...files.map(f => f.mtime)) }))
.sort((a, b) => b.latestMtime - a.latestMtime)
.slice(0, MAX_PROJECTS);
const allFiles = sortedProjects.flatMap(p => p.files);
allFiles.sort((a, b) => b.mtime - a.mtime);
return allFiles;
}
// ── Watch a single file for new content ─────────────────
async function watchFile(filePath, sessionId, projectName, fromByteOffset) {
if (watchedFiles.has(filePath)) return;
// Read current content to get correct char offset (byte offset != char offset for UTF-8)
let charOffset = 0;
try {
const current = await readFile(filePath, "utf8");
charOffset = current.length;
} catch {}
const meta = { byteOffset: fromByteOffset, charOffset, sessionId, projectName, isSubagent: false };
watchedFiles.set(filePath, meta);
if (!sessions.has(sessionId)) {
sessions.set(sessionId, { projectName, isSubagent: false, messages: [], active: true });
broadcast("session-new", { sessionId, projectName, isSubagent: false }, projectName);
}
meta.interval = setInterval(async () => {
try {
const st = await stat(filePath);
if (st.size <= meta.byteOffset) return;
const content = await readFile(filePath, "utf8");
const newContent = content.slice(meta.charOffset);
meta.charOffset = content.length;
meta.byteOffset = st.size;
for (const line of newContent.split("\n")) {
const trimmed = line.trim();
if (!trimmed) continue;
const raw = parseLine(trimmed);
if (!raw) continue;
const msg = extractDisplayMessage(raw);
if (!msg) continue;
const session = sessions.get(sessionId);
if (session) {
session.messages.push(msg);
if (session.messages.length > 500) session.messages = session.messages.slice(-300);
}
broadcast("message", { sessionId, ...msg }, projectName);
}
} catch {}
}, 500);
console.log(` Watching: ${projectName || sessionId.slice(0, 8)}`);
}
// ── Load history from a JSONL file ──────────────────────
async function loadHistory(filePath, sessionId, limit) {
try {
const content = await readFile(filePath, "utf8");
const lines = content.trim().split("\n").filter(Boolean);
const tail = lines.slice(-limit);
const messages = [];
for (const line of tail) {
const raw = parseLine(line.trim());
if (!raw) continue;
const msg = extractDisplayMessage(raw);
if (msg) messages.push(msg);
}
return messages;
} catch { return []; }
}
// ── Discover & watch all session files ──────────────────
let lastScanCount = 0;
async function discoverAndWatch() {
const files = await findAllSessionFiles();
for (const f of files) {
if (!watchedFiles.has(f.path)) {
// Load history first, then watch from end of file
const history = await loadHistory(f.path, f.sessionId, 200);
if (history.length > 0) {
if (!sessions.has(f.sessionId)) {
sessions.set(f.sessionId, { projectName: f.projectName, isSubagent: false, messages: [], active: true });
broadcast("session-new", { sessionId: f.sessionId, projectName: f.projectName, isSubagent: false }, f.projectName);
}
const session = sessions.get(f.sessionId);
session.messages = history;
broadcast("history-loaded", { sessionId: f.sessionId, projectName: f.projectName, messageCount: history.length }, f.projectName);
}
watchFile(f.path, f.sessionId, f.projectName, f.size);
}
}
if (files.length !== lastScanCount) {
lastScanCount = files.length;
console.log(`Tracking ${files.length} sessions across all projects`);
}
}
// ── API helpers ─────────────────────────────────────────
function listSessions(projectFilter) {
return _listSessions(sessions, projectFilter);
}
function getProjectMessages(projectName, before, limit) {
return _getProjectMessages(sessions, projectName, before, limit);
}
function listProjects() {
return _listProjects(sessions);
}
function computeProjectStats(projectName) {
return _computeProjectStats(sessions, projectName);
}
// ── Read JSON body helper ───────────────────────────────
function readBody(req, maxBytes = 10240) {
return new Promise((resolve) => {
const chunks = [];
let size = 0;
let oversized = false;
req.on("data", (c) => {
if (oversized) return;
size += c.length;
if (size > maxBytes) { oversized = true; req.destroy(); resolve(null); return; }
chunks.push(c);
});
req.on("end", () => {
if (oversized) return;
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
catch { resolve(null); }
});
req.on("error", () => resolve(null));
});
}
// ── HTTP + SSE server ───────────────────────────────────
function isLocalRequest(req) {
const host = (req.headers.host || "").toLowerCase();
return host === `localhost:${PORT}` || host === `127.0.0.1:${PORT}` || host === `[::1]:${PORT}`;
}
let detectedPublicOrigin = process.env.CC_LIVE_PUBLIC_URL || null; // e.g. https://xxx.ngrok-free.dev
const server = createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`);
const tokenParam = url.searchParams.get("t");
const share = resolveToken(tokenParam);
const local = isLocalRequest(req);
// CORS for all
res.setHeader("Access-Control-Allow-Origin", "*");
if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; }
// Password auth gate for share tokens (API routes only — frontend must always be served)
const needsAuth = !local && share && share.passwordHash && !verifyShareAuth(req, tokenParam, share.passwordHash);
if (needsAuth && url.pathname.startsWith("/api/") && !url.pathname.startsWith("/api/shares")) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "password required" }));
return;
}
// ── Share management API (local only) ─────────────────
// List shares
if (req.method === "GET" && url.pathname === "/api/shares") {
if (!local) { res.writeHead(403); res.end(); return; }
const list = [];
for (const [token, info] of shareTokens) {
list.push({ token, project: info.project, createdAt: info.createdAt, hasPassword: !!info.passwordHash });
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(list));
return;
}
// Create share
if (req.method === "POST" && url.pathname === "/api/shares") {
if (!local) { res.writeHead(403); res.end(); return; }
const body = await readBody(req);
if (body === null) {
res.writeHead(413, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "request body too large" }));
return;
}
if (!body.project) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "project required" }));
return;
}
// Verify project exists
const projects = listProjects();
if (!projects.find((p) => p.name === body.project)) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "project not found" }));
return;
}
const token = generateToken();
const password = body.password || null;
shareTokens.set(token, { project: body.project, createdAt: Date.now(), passwordHash: password ? hashPassword(password) : null });
saveShareTokens();
const shareUrl = `/?t=${token}`;
console.log(` Share created: ${body.project} -> ${token}${password ? " (password-protected)" : " (public)"}`);
res.writeHead(201, { "Content-Type": "application/json" });
const result = { token, url: shareUrl, project: body.project };
if (password) result.password = password;
res.end(JSON.stringify(result));
return;
}
// Delete share
const deleteShareMatch = url.pathname.match(/^\/api\/shares\/([a-f0-9]+)$/);
if (req.method === "DELETE" && deleteShareMatch) {
if (!local) { res.writeHead(403); res.end(); return; }
const t = deleteShareMatch[1];
if (shareTokens.has(t)) {
shareTokens.delete(t);
saveShareTokens();
console.log(` Share revoked: ${t}`);
res.writeHead(204);
res.end();
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "token not found" }));
}
return;
}
// Authenticate share (password check)
const authShareMatch = url.pathname.match(/^\/api\/shares\/([a-f0-9]+)\/auth$/);
if (req.method === "POST" && authShareMatch) {
const t = authShareMatch[1];
const shareInfo = shareTokens.get(t);
if (!shareInfo || !shareInfo.passwordHash) {
// Return same generic error for both missing token and no-password token
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "authentication failed" }));
return;
}
const body = await readBody(req);
if (!body || !body.password) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "password required" }));
return;
}
if (hashPassword(body.password) !== shareInfo.passwordHash) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "authentication failed" }));
return;
}
const sig = signToken(t, shareInfo.passwordHash);
res.setHeader("Set-Cookie", `cc-auth-${t}=${sig}; HttpOnly; SameSite=Lax; Path=/; Max-Age=86400`);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
return;
}
// ── Project stats ──────────────────────────────────────
if (url.pathname === "/api/project-stats") {
const project = url.searchParams.get("project");
if (!project) { res.writeHead(400); res.end(); return; }
if (!local && (!share || share.project !== project)) { res.writeHead(200, "application/json"); res.end("{}"); return; }
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(computeProjectStats(project)));
return;
}
// ── List projects ─────────────────────────────────────
if (url.pathname === "/api/projects") {
if (!local && !share) { res.writeHead(200, { "Content-Type": "application/json" }); res.end("[]"); return; }
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(listProjects()));
return;
}
// ── Project messages (paginated) ──────────────────────
if (url.pathname === "/api/project-messages") {
const project = url.searchParams.get("project");
if (!project) { res.writeHead(400); res.end(); return; }
if (!local && (!share || share.project !== project)) { res.writeHead(200, { "Content-Type": "application/json" }); res.end("[]"); return; }
const before = url.searchParams.has("before") ? url.searchParams.get("before") : null;
const limit = Math.min(Number(url.searchParams.get("limit") || 50), 200);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(getProjectMessages(project, before, limit)));
return;
}
// ── Danmaku API ───────────────────────────────────────
if (req.method === "GET" && url.pathname === "/api/danmaku") {
if (!local && !share) { res.writeHead(403); res.end(); return; }
const project = url.searchParams.get("project");
if (!project) { res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "project required" })); return; }
// Scope check: share users can only access their own project
if (share && share.project !== project) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "access denied" })); return; }
const danmaku = await loadDanmaku(project);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(danmaku));
return;
}
if (req.method === "POST" && url.pathname === "/api/danmaku") {
if (!local && !share) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "forbidden" })); return; }
const body = await readBody(req);
if (body === null) {
res.writeHead(413, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "request body too large" }));
return;
}
if (!body.content || !body.content.trim()) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "content required" }));
return;
}
// Determine project: share users use their token's project, local must provide it
const project = share ? share.project : body.project;
if (!project) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "project required" }));
return;
}
// Scope check: share users can only send to their own project
if (share && share.project !== project) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "access denied" })); return; }
const content = escapeHtml(body.content.trim().slice(0, 200));
const nickname = escapeHtml((body.nickname || "匿名").slice(0, 20));
const entry = {
id: randomUUID(),
nickname,
content,
timestamp: new Date().toISOString(),
};
await appendDanmaku(project, entry);
broadcast("danmaku", entry, project);
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify(entry));
return;
}
// ── SSE endpoint ──────────────────────────────────────
if (url.pathname === "/events") {
// External without token: deny
if (!local && !share) {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
sseSend(res, "sessions", []);
sseSend(res, "share-info", { project: null, error: "access denied" });
req.on("close", () => {});
return;
}
// Token-based access: must be valid
if (tokenParam && !share) {
res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid token" }));
return;
}
// Password-protected share: check auth cookie
if (share && share.passwordHash && !verifyShareAuth(req, tokenParam, share.passwordHash)) {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
sseSend(res, "password-required", { token: tokenParam });
res.end();
return;
}
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
const clientId = Date.now().toString(36) + Math.random().toString(36).slice(2);
const clientInfo = { res, token: share ? tokenParam : null };
clients.set(clientId, clientInfo);
console.log(`Client connected: ${clientId} (${clients.size} total)${share ? ` [share: ${share.project}]` : local ? " [local]" : " [external]"}`);
// Send filtered sessions
const projectFilter = share ? share.project : null;
sseSend(res, "sessions", listSessions(projectFilter));
if (share) sseSend(res, "share-info", { project: share.project });
// Send public origin for share URL generation
if (detectedPublicOrigin) sseSend(res, "public-origin", detectedPublicOrigin);
req.on("close", () => { clients.delete(clientId); broadcastViewerCount(); });
broadcastViewerCount();
return;
}
// ── API: list sessions ────────────────────────────────
if (url.pathname === "/api/sessions") {
if (!local && !share) { res.writeHead(200, { "Content-Type": "application/json" }); res.end("[]"); return; }
const projectFilter = share ? share.project : null;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(listSessions(projectFilter)));
return;
}
// ── API: session history ──────────────────────────────
const sessionMatch = url.pathname.match(/^\/api\/session\/(.+)$/);
if (sessionMatch) {
const sid = sessionMatch[1];
const session = sessions.get(sid);
if (session && session.messages.length > 0) {
// If share token, verify project match
if (share && session.projectName !== share.project) {
res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "access denied" }));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ sessionId: sid, projectName: session.projectName, messages: session.messages }));
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not found" }));
}
return;
}
// ── Serve static files (.js, .css) ──────────────────────
if (url.pathname.startsWith("/js/") || url.pathname.startsWith("/style")) {
const publicDir = join(__dirname, "public");
const filePath = join(publicDir, url.pathname);
if (!filePath.startsWith(publicDir)) { res.writeHead(403); res.end(); return; }
const ext = filePath.endsWith(".js") ? "application/javascript"
: filePath.endsWith(".css") ? "text/css"
: "application/octet-stream";
try {
const data = await readFile(filePath);
res.writeHead(200, { "Content-Type": `${ext}; charset=utf-8` });
res.end(data);
} catch {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
return;
}
// ── Serve frontend ────────────────────────────────────
const FRONTEND_PATH = join(__dirname, "public", "index.html");
try {
const html = await readFile(FRONTEND_PATH, "utf8");
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(html);
} catch (e) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Failed to load frontend");
}
});
// ── Startup ─────────────────────────────────────────────
await loadShareTokens();
server.listen(PORT, () => {
console.log(`\n CC Live running at http://localhost:${PORT}\n`);
console.log(" Share publicly:");
console.log(` cloudflared tunnel --url http://localhost:${PORT}\n`);
discoverAndWatch();
});
// Re-scan every 10s for new sessions
setInterval(discoverAndWatch, 10000);