-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1756 lines (1563 loc) · 66.6 KB
/
Copy pathserver.js
File metadata and controls
1756 lines (1563 loc) · 66.6 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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const { PORT, DB_PATH, STATS_CACHE_FILE, MULTI_USER, BASE_URL, SHARE_ADMIN_KEY } = require('./lib/config');
const { parseAll, backfillRateLimitEvents } = require('./lib/parser');
const Aggregator = require('./lib/aggregator');
const { AggregatorCache } = require('./lib/aggregator');
const { calculateCost, getPricingMeta } = require('./lib/pricing');
const pricingFetcher = require('./lib/pricing-fetcher');
const {
initDB, insertMessages, streamAllMessages, getParseState, setParseState, closeDB,
insertMessagesForUser, streamMessagesForUser,
regenerateApiKey, cleanExpiredSessions, findUserByApiKey,
getUnlockedAchievements, unlockAchievementsBatch, unlockAchievementsBatchAt, clearAchievementsForUser, replaceAchievementsForUser,
getMetadata, setMetadata,
insertRateLimitEvents, insertRateLimitEventsForUser,
getAllRateLimitEvents, getRateLimitEventsForUser,
createDevice, getDevicesForUser, getDeviceById, findDeviceByApiKey, findUserById,
renameDevice, deleteDevice, regenerateDeviceKey, updateDeviceLastSync,
getProjectShare, listProjectShares, createProjectShare, deleteProjectShare,
createProjectAlias, deleteProjectAlias, getProjectAliasRows,
getProjectAliasMap
} = require('./lib/db');
const achievements = require('./lib/achievements');
const { generateExportHTML } = require('./lib/export-html');
const Watcher = require('./lib/watcher');
const { authenticateRequest, authenticateApiKey, handleAuthRoute } = require('./lib/auth');
const github = require('./lib/github');
const anthropicApi = require('./lib/anthropic-api');
const planUsage = require('./lib/plan-usage');
const PUBLIC_DIR = path.join(__dirname, 'public');
// Read sync-agent files for install script generation
const SYNC_AGENT_INDEX = fs.readFileSync(path.join(__dirname, 'sync-agent', 'index.js'), 'utf-8');
const SYNC_AGENT_PKG = fs.readFileSync(path.join(__dirname, 'sync-agent', 'package.json'), 'utf-8');
// MIME types
const MIME = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml'
};
// --- Read Claude's own stats-cache.json ---
function readStatsCache() {
try {
return JSON.parse(fs.readFileSync(STATS_CACHE_FILE, 'utf-8'));
} catch {
return null;
}
}
// --- Init ---
console.log('Starting Claude Token Tracker...');
if (MULTI_USER) console.log('Multi-user mode enabled');
// 1. Initialize DB
initDB();
// 1b. Initialize GitHub module with DB reference
github.initGithub(require('./lib/db'));
// 1c. Initialize Anthropic API module with DB reference
anthropicApi.initAnthropicApi(require('./lib/db'));
// 1d. Initialize Plan Usage module with DB reference
planUsage.initPlanUsage(require('./lib/db'));
// 1e. Initialize Pricing module — loads cached overrides synchronously, then
// fetches fresh prices from LiteLLM in the background and schedules a 24h refresh.
pricingFetcher.initPricing(require('./lib/db'));
// 2. Load existing messages and parse JSONL (single-user only; multi-user uses per-user cache)
const aggregator = new Aggregator();
let parseState = {};
if (!MULTI_USER) {
// Load the project merge map before any messages so aliases fold during build.
aggregator.setProjectAliases(getProjectAliasMap(0));
// Stream messages straight into the aggregator instead of materializing the
// full array — the old peak (two ~150k-object arrays alive at once) grew the
// V8 heap by hundreds of MB that were never returned to the OS.
aggregator.addMessages(streamAllMessages());
if (aggregator.messageCount > 0) {
console.log(`Loaded ${aggregator.messageCount} messages from database`);
}
const existingRateLimitEvents = getAllRateLimitEvents();
if (existingRateLimitEvents.length > 0) {
aggregator.addRateLimitEvents(existingRateLimitEvents);
console.log(`Loaded ${existingRateLimitEvents.length} rate-limit events from database`);
}
// Parse new JSONL data incrementally
const t0 = Date.now();
const savedParseState = getParseState();
const { messages: newMessages, rateLimitEvents: newRateLimitEvents, parseState: newParseState } = parseAll(savedParseState);
parseState = newParseState;
if (newMessages.length > 0) {
// The aggregator already contains every DB message at this point, so its
// ID map doubles as the dedup set (no extra 150k-entry Set needed).
const trulyNew = newMessages.filter(m => !aggregator.hasMessage(m.id));
if (trulyNew.length > 0) {
insertMessages(trulyNew, calculateCost);
aggregator.addMessages(trulyNew);
console.log(`Parsed ${trulyNew.length} new messages in ${Date.now() - t0}ms`);
}
}
if (newRateLimitEvents.length > 0) {
insertRateLimitEvents(newRateLimitEvents);
aggregator.addRateLimitEvents(newRateLimitEvents);
console.log(`Parsed ${newRateLimitEvents.length} new rate-limit events`);
}
// Backfill rate-limit events if needed
if (existingRateLimitEvents.length === 0 && newRateLimitEvents.length === 0) {
const backfilled = backfillRateLimitEvents();
if (backfilled.length > 0) {
insertRateLimitEvents(backfilled);
aggregator.addRateLimitEvents(backfilled);
console.log(`Backfilled ${backfilled.length} rate-limit events from existing JSONL files`);
}
}
setParseState(parseState);
} else {
console.log('Multi-user mode: skipping global aggregator (per-user cache used instead)');
}
// DB helper for achievements module
const achievementsDb = { getUnlockedAchievements, unlockAchievementsBatch, unlockAchievementsBatchAt, clearAchievementsForUser, replaceAchievementsForUser };
// Metadata-flag prefix for the one-time historical achievements backfill (per
// user). v2: ratio/average achievements gated on tier-scaled minimum active
// days — bumping the version re-migrates existing data once.
const ACH_BACKFILL_FLAG = 'ach_backfill_v2_';
// 5. Check achievements on startup (single-user). A FRESH install with an
// existing Claude history would bulk-unlock hundreds of achievements stamped
// "now" — replay the history instead so unlock dates land on the day each
// condition was actually first met (no distorted timeline).
if (!MULTI_USER) {
try {
const needsBackfill = aggregator.messageCount > 0 &&
(getUnlockedAchievements(0).length === 0 || !getMetadata(ACH_BACKFILL_FLAG + 0));
if (needsBackfill) {
const res = achievements.backfillAchievements(aggregator, 0, achievementsDb);
setMetadata(ACH_BACKFILL_FLAG + 0, new Date().toISOString());
console.log(`Backfilled ${res.unlocked} achievements with historical dates across ${res.days} days (${res.from} – ${res.to})`);
} else {
const newAch = achievements.checkAchievements(aggregator, 0, achievementsDb);
if (newAch.length > 0) console.log(`Unlocked ${newAch.length} new achievements`);
}
} catch (e) { console.error('Achievement check failed on startup:', e.message); }
}
// Start file watcher (single-user only)
const watcher = new Watcher(aggregator, parseState, (newMsgs, rleEvents) => {
if (newMsgs.length > 0) insertMessages(newMsgs, calculateCost);
if (rleEvents && rleEvents.length > 0) insertRateLimitEvents(rleEvents);
setParseState(parseState);
try {
const newAch = achievements.checkAchievements(aggregator, 0, achievementsDb);
if (newAch.length > 0) {
watcher.broadcast({ type: 'achievement-unlocked', achievements: achievements.getAchievementsByKeys(newAch) });
}
} catch (e) { console.error('Achievement check failed:', e.message); }
});
if (!MULTI_USER) {
watcher.start();
}
// Multi-user aggregator cache
// Streaming loader keeps the per-user cache build from materializing the full
// message array (same RSS-peak reasoning as the single-user bootstrap).
const aggregatorCache = MULTI_USER ? new AggregatorCache(streamMessagesForUser, getRateLimitEventsForUser, getProjectAliasMap) : null;
// Re-apply the project merge map after a merge/un-merge and refresh caches so
// the change is visible immediately across dashboard + public shares.
function applyProjectMergeChange(userId) {
global._shareAggCache = null; // force the global (admin) share aggregator to rebuild
if (MULTI_USER) {
if (aggregatorCache) aggregatorCache.invalidateUser(userId);
} else {
aggregator.setProjectAliases(getProjectAliasMap(0));
aggregator.reset();
aggregator.addMessages(streamAllMessages());
aggregator.addRateLimitEvents(getAllRateLimitEvents());
}
}
// Clean expired sessions periodically (multi-user)
let sessionCleanupTimer = null;
if (MULTI_USER) {
sessionCleanupTimer = setInterval(() => cleanExpiredSessions(), 60 * 60 * 1000);
}
// --- Backup system ---
let backup = null;
try {
backup = require('./lib/backup');
backup.startAutoBackup();
} catch {
// backup module not yet available during Phase 2
}
// --- HTTP Server ---
// NO blanket `Access-Control-Allow-Origin: *` here. It made every API response
// readable by any website the user's browser visited (single-user mode has no
// auth at all), and — because writeHead's header object overrides setHeader —
// it also overwrote the deliberate origin allowlist on the public share
// endpoint, silently turning that allowlist into a wildcard. Endpoints that
// genuinely need CORS set the header themselves (see /api/public/share/:token).
function sendJSON(res, data, status = 200) {
const body = JSON.stringify(data);
const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' };
const cors = res.getHeader('Access-Control-Allow-Origin');
if (cors) headers['Access-Control-Allow-Origin'] = cors;
res.writeHead(status, headers);
res.end(body);
}
function serveStatic(res, filePath, req) {
const ext = path.extname(filePath);
const mime = MIME[ext] || 'application/octet-stream';
fs.stat(filePath, (statErr, stat) => {
if (statErr || !stat.isFile()) {
res.writeHead(404);
res.end('Not found');
return;
}
// Cheap ETag from mtime + size; browsers revalidate (must-revalidate) and
// get a 304 instead of re-downloading ~640KB of JS/CSS on every reload.
const etag = `"${stat.mtimeMs.toString(36)}-${stat.size.toString(36)}"`;
const cacheHeaders = {
'ETag': etag,
'Cache-Control': 'public, max-age=0, must-revalidate'
};
if (req && req.headers['if-none-match'] === etag) {
res.writeHead(304, cacheHeaders);
res.end();
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end('Not found');
return;
}
res.writeHead(200, { 'Content-Type': mime, 'Content-Length': data.length, ...cacheHeaders });
res.end(data);
});
});
}
/**
* Read request body as JSON
*/
function readBody(req, maxBytes = 10 * 1024 * 1024) {
return new Promise((resolve, reject) => {
let data = '';
let bytes = 0;
req.on('data', chunk => {
bytes += chunk.length;
if (bytes > maxBytes) { req.destroy(); return reject(new Error('Body too large')); }
data += chunk;
});
req.on('end', () => {
try { resolve(JSON.parse(data)); }
catch (e) { reject(e); }
});
req.on('error', reject);
});
}
/**
* Get the aggregator for the current request.
* In single-user mode: returns the global aggregator.
* In multi-user mode: returns a per-user aggregator from the cache.
* If deviceId is provided, returns a device-filtered aggregator.
*/
function getAggregator(user, deviceId) {
if (!MULTI_USER) return aggregator;
return aggregatorCache.get(user.id, deviceId || null);
}
/**
* Generate a self-contained install script for the sync agent
*/
function generateInstallScript(serverUrl, apiKey) {
return `#!/bin/bash
set -e
GREEN='\\033[0;32m'
YELLOW='\\033[1;33m'
RED='\\033[0;31m'
BLUE='\\033[0;34m'
BOLD='\\033[1m'
NC='\\033[0m'
info() { echo -e "\$BLUE▸\$NC \$1"; }
ok() { echo -e "\$GREEN✓\$NC \$1"; }
warn() { echo -e "\$YELLOW⚠\$NC \$1"; }
err() { echo -e "\$RED✗\$NC \$1"; }
INSTALL_DIR="\$HOME/claude-sync-agent"
echo -e "\$BOLD""Claude Sync Agent Installer""\$NC"
echo ""
# --- 1. Prerequisites ---
if ! command -v node &> /dev/null; then
err "Node.js is not installed. Install Node.js 18+ first."
exit 1
fi
NODE_VERSION=\$(node -v | sed 's/v//' | cut -d. -f1)
if [ "\$NODE_VERSION" -lt 18 ]; then
err "Node.js 18+ required (found \$(node -v))"
exit 1
fi
ok "Node.js \$(node -v)"
if ! command -v npm &> /dev/null; then
err "npm is not installed."
exit 1
fi
# --- 2. Handle existing installation ---
if [ -d "\$INSTALL_DIR" ]; then
info "Updating existing installation at \$INSTALL_DIR ..."
# Stop existing service before overwriting
OS_PRE=\$(uname -s)
if [ "\$OS_PRE" = "Darwin" ]; then
PLIST_PRE="\$HOME/Library/LaunchAgents/io.celox.claude-sync-agent.plist"
[ -f "\$PLIST_PRE" ] && launchctl unload "\$PLIST_PRE" 2>/dev/null || true
elif [ "\$OS_PRE" = "Linux" ]; then
systemctl --user stop claude-sync-agent 2>/dev/null || true
fi
fi
# --- 3. Install files ---
info "Installing to \$INSTALL_DIR ..."
mkdir -p "\$INSTALL_DIR"
cat > "\$INSTALL_DIR/index.js" << 'SYNCAGENTEOF'
${SYNC_AGENT_INDEX}
SYNCAGENTEOF
cat > "\$INSTALL_DIR/package.json" << 'SYNCAGENTEOF'
${SYNC_AGENT_PKG}
SYNCAGENTEOF
cat > "\$INSTALL_DIR/config.json" << SYNCAGENTEOF
{
"serverUrl": "${serverUrl}",
"apiKey": "${apiKey}"
}
SYNCAGENTEOF
ok "Files written"
# --- 4. Install dependencies ---
info "Installing dependencies..."
cd "\$INSTALL_DIR"
npm install --production --silent 2>&1 | tail -1
ok "Dependencies installed"
# --- 5. Verify server connection ---
info "Verifying server connection..."
HTTP_STATUS=\$(curl -s -o /dev/null -w "%{http_code}" \\
-X POST \\
-H "Authorization: Bearer ${apiKey}" \\
-H "Content-Type: application/json" \\
-d '{"messages":[]}' \\
"${serverUrl}/api/sync" 2>/dev/null || echo "000")
if [ "\$HTTP_STATUS" = "400" ]; then
ok "Server connection verified"
elif [ "\$HTTP_STATUS" = "401" ]; then
warn "API key rejected — regenerate it on the website"
elif [ "\$HTTP_STATUS" = "000" ]; then
warn "Could not reach server at ${serverUrl}"
else
warn "Unexpected response (HTTP \$HTTP_STATUS)"
fi
# --- 6. Autostart ---
NODE_PATH=\$(which node)
OS=\$(uname -s)
setup_launchd() {
local PLIST_DIR="\$HOME/Library/LaunchAgents"
local PLIST="\$PLIST_DIR/io.celox.claude-sync-agent.plist"
mkdir -p "\$PLIST_DIR"
[ -f "\$PLIST" ] && launchctl unload "\$PLIST" 2>/dev/null || true
cat > "\$PLIST" << PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>io.celox.claude-sync-agent</string>
<key>ProgramArguments</key>
<array>
<string>\$NODE_PATH</string>
<string>\$INSTALL_DIR/index.js</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>\$INSTALL_DIR/stdout.log</string>
<key>StandardErrorPath</key>
<string>\$INSTALL_DIR/stderr.log</string>
<key>WorkingDirectory</key>
<string>\$INSTALL_DIR</string>
</dict>
</plist>
PLISTEOF
launchctl load "\$PLIST" 2>/dev/null
ok "Autostart configured (launchd)"
ok "Agent is running — survives reboots"
echo ""
info "Logs: tail -f \$INSTALL_DIR/stdout.log"
info "Stop: launchctl unload \$PLIST"
info "Restart: launchctl unload \$PLIST && launchctl load \$PLIST"
info "Remove: launchctl unload \$PLIST && rm \$PLIST"
}
setup_systemd() {
local SERVICE_DIR="\$HOME/.config/systemd/user"
local SERVICE="\$SERVICE_DIR/claude-sync-agent.service"
mkdir -p "\$SERVICE_DIR"
cat > "\$SERVICE" << SERVICEEOF
[Unit]
Description=Claude Sync Agent
After=network.target
[Service]
ExecStart=\$NODE_PATH \$INSTALL_DIR/index.js
WorkingDirectory=\$INSTALL_DIR
Restart=on-failure
RestartSec=10
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
SERVICEEOF
systemctl --user daemon-reload
systemctl --user enable claude-sync-agent 2>/dev/null
systemctl --user restart claude-sync-agent
ok "Autostart configured (systemd)"
ok "Agent is running — survives reboots"
echo ""
info "Logs: journalctl --user -u claude-sync-agent -f"
info "Stop: systemctl --user stop claude-sync-agent"
info "Restart: systemctl --user restart claude-sync-agent"
info "Remove: systemctl --user disable --now claude-sync-agent"
}
echo ""
if [ "\$OS" = "Darwin" ] || [ "\$OS" = "Linux" ]; then
read -p "\$(echo -e "\$BLUE▸\$NC") Set up autostart? [Y/n] " -n 1 -r
echo
if [[ ! \$REPLY =~ ^[Nn]\$ ]]; then
if [ "\$OS" = "Darwin" ]; then
setup_launchd
else
if command -v systemctl &> /dev/null; then
setup_systemd
else
warn "systemd not available"
info "Use PM2 instead:"
info " pm2 start \$INSTALL_DIR/index.js --name claude-sync"
info " pm2 save"
fi
fi
else
info "Start manually: node \$INSTALL_DIR/index.js"
info "Or with PM2: pm2 start \$INSTALL_DIR/index.js --name claude-sync && pm2 save"
fi
else
warn "Unknown OS — skipping autostart"
info "Start manually: node \$INSTALL_DIR/index.js"
fi
echo ""
echo -e "\$GREEN\$BOLD=== Installation complete ===\$NC"
echo " Directory: \$INSTALL_DIR"
echo " Server: ${serverUrl}"
echo ""
`;
}
/**
* Generate a self-contained PowerShell install script for the sync agent (Windows)
*/
function generateWindowsInstallScript(serverUrl, apiKey) {
// Use single-quoted heredocs (@'...'@) for index.js and package.json (no interpolation)
// Use double-quoted heredoc (@"..."@) for config.json (needs variable interpolation)
return `#Requires -Version 5.0
$ErrorActionPreference = "Stop"
function Write-Info($msg) { Write-Host " $msg" -ForegroundColor Cyan }
function Write-Ok($msg) { Write-Host " $msg" -ForegroundColor Green }
function Write-Warn($msg) { Write-Host " $msg" -ForegroundColor Yellow }
function Write-Err($msg) { Write-Host " $msg" -ForegroundColor Red }
$InstallDir = Join-Path $env:USERPROFILE "claude-sync-agent"
Write-Host ""
Write-Host " Claude Sync Agent Installer" -ForegroundColor White
Write-Host ""
# --- 1. Prerequisites ---
$nodeCmd = Get-Command node -ErrorAction SilentlyContinue
if (-not $nodeCmd) {
Write-Err "Node.js is not installed. Install Node.js 18+ first."
exit 1
}
$nodeVersion = (node -v) -replace '^v', ''
$nodeMajor = [int]($nodeVersion.Split('.')[0])
if ($nodeMajor -lt 18) {
Write-Err "Node.js 18+ required (found v$nodeVersion)"
exit 1
}
Write-Ok "Node.js v$nodeVersion"
# --- 2. Handle existing installation ---
if (Test-Path $InstallDir) {
Write-Info "Updating existing installation at $InstallDir ..."
$task = Get-ScheduledTask -TaskName "ClaudeSyncAgent" -ErrorAction SilentlyContinue
if ($task) {
Stop-ScheduledTask -TaskName "ClaudeSyncAgent" -ErrorAction SilentlyContinue
}
}
# --- 3. Install files ---
Write-Info "Installing to $InstallDir ..."
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
$indexJs = @'
${SYNC_AGENT_INDEX}
'@
Set-Content -Path (Join-Path $InstallDir "index.js") -Value $indexJs -Encoding UTF8
$packageJson = @'
${SYNC_AGENT_PKG}
'@
Set-Content -Path (Join-Path $InstallDir "package.json") -Value $packageJson -Encoding UTF8
$configJson = @"
{
"serverUrl": "${serverUrl}",
"apiKey": "${apiKey}"
}
"@
Set-Content -Path (Join-Path $InstallDir "config.json") -Value $configJson -Encoding UTF8
Write-Ok "Files written"
# --- 4. Install dependencies ---
Write-Info "Installing dependencies..."
Push-Location $InstallDir
& npm.cmd install --production --silent 2>&1 | Out-Null
Pop-Location
Write-Ok "Dependencies installed"
# --- 5. Verify server connection ---
Write-Info "Verifying server connection..."
try {
$response = Invoke-WebRequest -Uri "${serverUrl}/api/sync" -Method POST \`
-Headers @{ "Authorization" = "Bearer ${apiKey}"; "Content-Type" = "application/json" } \`
-Body '{"messages":[]}' -UseBasicParsing -ErrorAction Stop
Write-Ok "Server connection verified"
} catch {
$status = 0
if ($_.Exception.Response) {
$status = [int]$_.Exception.Response.StatusCode
}
if ($status -eq 400) {
Write-Ok "Server connection verified"
} elseif ($status -eq 401) {
Write-Warn "API key rejected - regenerate it on the website"
} else {
Write-Warn "Could not reach server at ${serverUrl}"
}
}
# --- 6. Autostart (Task Scheduler) ---
Write-Info "Setting up autostart (Task Scheduler)..."
$nodePath = (Get-Command node).Source
$action = New-ScheduledTaskAction -Execute $nodePath -Argument (Join-Path $InstallDir "index.js") -WorkingDirectory $InstallDir
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Hours 0)
Register-ScheduledTask -TaskName "ClaudeSyncAgent" -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null
Start-ScheduledTask -TaskName "ClaudeSyncAgent" -ErrorAction SilentlyContinue
Write-Ok "Autostart configured (Task Scheduler)"
Write-Ok "Agent is running — survives reboots"
Write-Host ""
Write-Host " === Installation complete ===" -ForegroundColor Green
Write-Host " Directory: $InstallDir"
Write-Host " Server: ${serverUrl}"
Write-Host ""
Write-Info "Stop: Stop-ScheduledTask -TaskName ClaudeSyncAgent"
Write-Info "Restart: Start-ScheduledTask -TaskName ClaudeSyncAgent"
Write-Info "Remove: Unregister-ScheduledTask -TaskName ClaudeSyncAgent -Confirm:\`$false"
Write-Host ""
`;
}
const server = http.createServer((req, res) => {
const parsed = url.parse(req.url, true);
const pathname = parsed.pathname;
const query = parsed.query;
// Auth routes (always accessible)
if (pathname.startsWith('/auth/')) {
if (handleAuthRoute(req, res, pathname, sendJSON)) return;
}
// Config endpoint (tells frontend about mode)
if (pathname === '/api/config') {
return sendJSON(res, { multiUser: MULTI_USER, hasGithubToken: !!process.env.GITHUB_TOKEN });
}
// Sync endpoint — API key auth, separate from session auth
if (pathname === '/api/sync' && req.method === 'POST') {
const auth = authenticateApiKey(req);
if (!auth) return sendJSON(res, { error: 'Unauthorized' }, 401);
const syncUser = auth.user;
const syncDevice = auth.device;
const deviceId = syncDevice ? syncDevice.id : null;
readBody(req).then(body => {
const messages = body.messages;
const rateLimitEvents = body.rateLimitEvents;
const hasMessages = Array.isArray(messages) && messages.length > 0;
const hasRateLimitEvents = Array.isArray(rateLimitEvents) && rateLimitEvents.length > 0;
const hasPlanUsage = !!body.planUsage;
if (!hasMessages && !hasRateLimitEvents && !hasPlanUsage) {
return sendJSON(res, { error: 'No data provided' }, 400);
}
if (hasMessages) {
insertMessagesForUser(messages, calculateCost, syncUser.id, deviceId);
}
if (hasRateLimitEvents) {
insertRateLimitEventsForUser(rateLimitEvents, syncUser.id, deviceId);
}
// Store plan usage data if provided (backwards-compatible)
if (body.planUsage) {
planUsage.storeSyncedPlanUsage(syncUser.id, body.planUsage);
}
// Update device last sync time
if (deviceId) updateDeviceLastSync(deviceId);
// Incrementally update cached aggregators (avoids full rebuild from 67k+ messages)
if (aggregatorCache && (hasMessages || hasRateLimitEvents)) {
const aggMessages = hasMessages ? messages.map(m => ({
id: m.id, timestamp: m.timestamp, model: m.model, sessionId: m.sessionId,
project: m.project, inputTokens: m.inputTokens || 0, outputTokens: m.outputTokens || 0,
cacheReadTokens: m.cacheReadTokens || 0, cacheCreateTokens: m.cacheCreateTokens || 0,
stopReason: m.stopReason, tools: m.tools || [], toolCounts: m.toolCounts || {},
isSubagent: !!(m.isSubagent), linesAdded: m.linesAdded || 0,
linesRemoved: m.linesRemoved || 0, linesWritten: m.linesWritten || 0
})) : null;
aggregatorCache.addToUser(syncUser.id, aggMessages, hasRateLimitEvents ? rateLimitEvents : null);
}
// Check achievements for this user (always use all-devices aggregator)
try {
const userAgg = aggregatorCache.get(syncUser.id);
const newAch = achievements.checkAchievements(userAgg, syncUser.id, achievementsDb);
if (newAch.length > 0) {
watcher.broadcast({ type: 'achievement-unlocked', achievements: achievements.getAchievementsByKeys(newAch), userId: syncUser.id });
}
} catch (e) { console.error('Achievement check failed for user', syncUser.id, ':', e.message); }
// Broadcast SSE update to this user's clients
watcher.broadcast({ type: 'update', count: hasMessages ? messages.length : 0, userId: syncUser.id });
return sendJSON(res, { inserted: hasMessages ? messages.length : 0, rateLimitEvents: hasRateLimitEvents ? rateLimitEvents.length : 0 });
}).catch(err => {
return sendJSON(res, { error: 'Invalid JSON: ' + err.message }, 400);
});
return;
}
// Sync agent install script download — uses device-specific API key
if (pathname === '/api/sync-agent/install.sh' && req.method === 'GET') {
if (!MULTI_USER) return sendJSON(res, { error: 'Not available in single-user mode' }, 404);
let scriptUser = authenticateRequest(req);
if (!scriptUser && query.key) {
scriptUser = findUserByApiKey(query.key);
if (!scriptUser) {
const dev = findDeviceByApiKey(query.key);
if (dev) scriptUser = findUserById(dev.user_id);
}
}
if (!scriptUser) return sendJSON(res, { error: 'Unauthorized' }, 401);
// Resolve device API key
let apiKey;
if (query.device) {
const device = getDeviceById(parseInt(query.device));
if (!device || device.user_id !== scriptUser.id) return sendJSON(res, { error: 'Device not found' }, 404);
apiKey = device.api_key;
} else {
const devices = getDevicesForUser(scriptUser.id);
apiKey = devices.length > 0 ? devices[0].api_key : scriptUser.api_key;
}
const script = generateInstallScript(BASE_URL, apiKey);
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': 'attachment; filename="install-sync-agent.sh"',
'Cache-Control': 'no-cache'
});
return res.end(script);
}
// Sync agent PowerShell install script download (Windows)
if (pathname === '/api/sync-agent/install.ps1' && req.method === 'GET') {
if (!MULTI_USER) return sendJSON(res, { error: 'Not available in single-user mode' }, 404);
let scriptUser = authenticateRequest(req);
if (!scriptUser && query.key) {
scriptUser = findUserByApiKey(query.key);
if (!scriptUser) {
const dev = findDeviceByApiKey(query.key);
if (dev) scriptUser = findUserById(dev.user_id);
}
}
if (!scriptUser) return sendJSON(res, { error: 'Unauthorized' }, 401);
let apiKey;
if (query.device) {
const device = getDeviceById(parseInt(query.device));
if (!device || device.user_id !== scriptUser.id) return sendJSON(res, { error: 'Device not found' }, 404);
apiKey = device.api_key;
} else {
const devices = getDevicesForUser(scriptUser.id);
apiKey = devices.length > 0 ? devices[0].api_key : scriptUser.api_key;
}
const script = generateWindowsInstallScript(BASE_URL, apiKey);
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': 'attachment; filename="install-sync-agent.ps1"',
'Cache-Control': 'no-cache'
});
return res.end(script);
}
// Static files — always accessible (login page needs them)
if (!pathname.startsWith('/api/')) {
let filePath = pathname === '/' ? '/index.html' : pathname;
filePath = path.join(PUBLIC_DIR, filePath);
// Prevent path traversal
if (!filePath.startsWith(PUBLIC_DIR)) {
res.writeHead(403);
return res.end('Forbidden');
}
return serveStatic(res, filePath, req);
}
// --- Public share endpoint (no auth required) ---
// Rate limiting for share endpoint: max 30 requests per minute per IP
if (!global._shareRateLimit) global._shareRateLimit = new Map();
if (pathname.startsWith('/api/public/share/') && req.method === 'GET') {
const clientIp = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket.remoteAddress;
const now = Date.now();
const windowMs = 60000;
const maxRequests = 30;
const ipHits = global._shareRateLimit.get(clientIp) || [];
const recentHits = ipHits.filter(t => t > now - windowMs);
if (recentHits.length >= maxRequests) {
res.writeHead(429, { 'Content-Type': 'application/json', 'Retry-After': '60' });
return res.end(JSON.stringify({ error: 'Too many requests' }));
}
recentHits.push(now);
global._shareRateLimit.set(clientIp, recentHits);
// Cleanup old entries every 100 requests
if (global._shareRateLimit.size > 1000) {
for (const [ip, hits] of global._shareRateLimit) {
if (hits.every(t => t < now - windowMs)) global._shareRateLimit.delete(ip);
}
}
const shareToken = pathname.split('/api/public/share/')[1];
if (!shareToken || shareToken.length !== 48 || !/^[a-f0-9]+$/.test(shareToken)) {
return sendJSON(res, { error: 'Invalid token format' }, 400);
}
const share = getProjectShare(shareToken);
if (!share) return sendJSON(res, { error: 'Not found' }, 404);
// In multi-user mode, use cached global aggregator
const shareAgg = MULTI_USER ? (() => {
const now = Date.now();
if (!global._shareAggCache || now - global._shareAggCacheTime > 300000) {
const { streamAllMessages } = require('./lib/db');
const a = new Aggregator();
// SECURITY: do NOT apply a cross-user alias union here. This aggregator
// spans every user's messages and backs the global/admin shares; folding
// it with another user's merge map would let any user rewrite project-name
// resolution for everyone's shares (cross-tenant poisoning). Shares resolve
// to the literal project name in multi-user mode. Per-user merges only
// affect each user's own (scoped) dashboard aggregator.
a.addMessages(streamAllMessages());
global._shareAggCache = a;
global._shareAggCacheTime = now;
}
return global._shareAggCache;
})() : aggregator;
const projectData = shareAgg.getProjectDetail(share.project, query.from, query.to);
if (!projectData) return sendJSON(res, { error: 'Not found' }, 404);
// Return full project data for customer transparency
const sessionList = Array.isArray(projectData.sessionList) ? projectData.sessionList : [];
const response = {
label: share.label || 'Projekt',
period: { from: query.from || null, to: query.to || null },
summary: {
total_input_tokens: projectData.inputTokens || 0,
total_output_tokens: projectData.outputTokens || 0,
total_cache_read_tokens: projectData.cacheReadTokens || 0,
total_cache_create_tokens: projectData.cacheCreateTokens || 0,
total_messages: projectData.messages || 0,
total_sessions: projectData.sessions || 0,
total_cost: projectData.cost || 0,
lines_added: projectData.linesAdded || 0,
lines_removed: projectData.linesRemoved || 0,
lines_written: projectData.linesWritten || 0,
total_duration_min: projectData.totalDurationMin || 0,
total_active_min: projectData.totalActiveMin || 0,
first_activity: projectData.firstTs || null,
last_activity: projectData.lastTs || null,
models_used: (projectData.models || []).map(m => ({
name: m.name,
messages: m.messages,
cost: m.cost || 0,
})),
tools: (projectData.tools || []).slice(0, 15).map(t => ({
name: t.name,
calls: t.calls || t.count || 0,
})),
},
daily: (projectData.daily || []).map(d => ({
date: d.date,
input_tokens: d.inputTokens || 0,
output_tokens: d.outputTokens || 0,
cache_read_tokens: d.cacheReadTokens || 0,
messages: d.messages || 0,
cost: d.cost || 0,
lines_added: d.linesAdded || 0,
lines_removed: d.linesRemoved || 0,
lines_written: d.linesWritten || 0,
})),
sessions: sessionList.map(s => ({
start: s.firstMessage,
end: s.lastMessage,
messages: s.messages || 0,
input_tokens: s.inputTokens || 0,
output_tokens: s.outputTokens || 0,
cost: s.cost || 0,
duration_min: s.durationMin || 0,
active_min: s.activeMin || 0,
model: s.model,
lines_added: s.linesAdded || 0,
lines_removed: s.linesRemoved || 0,
lines_written: s.linesWritten || 0,
})),
};
// Restrict CORS to known origins
const origin = req.headers.origin || '';
const allowedOrigins = ['https://ops.celox.io', 'https://tracker.celox.io', 'http://localhost:5173', 'http://localhost:8090'];
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
return sendJSON(res, response);
}
// CORS preflight for share endpoint
if (pathname.startsWith('/api/public/share/') && req.method === 'OPTIONS') {
const origin = req.headers.origin || '';
const allowedOrigins = ['https://ops.celox.io', 'https://tracker.celox.io', 'http://localhost:5173', 'http://localhost:8090'];
if (allowedOrigins.includes(origin)) {
res.writeHead(204, {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
});
} else {
res.writeHead(204);
}
return res.end();
}
// --- Share admin key management (session auth only, for settings UI) ---
if (pathname === '/api/share-admin-key' && req.method === 'GET') {
const sessionUser = authenticateRequest(req);
if (MULTI_USER && !sessionUser) return sendJSON(res, { error: 'Unauthorized' }, 401);
return sendJSON(res, {
key: SHARE_ADMIN_KEY || null,
base_url: BASE_URL || `http://localhost:${PORT}`,
});
}
if (pathname === '/api/share-admin-key' && req.method === 'POST') {
const sessionUser = authenticateRequest(req);
if (MULTI_USER && !sessionUser) return sendJSON(res, { error: 'Unauthorized' }, 401);
const crypto = require('crypto');
const newKey = crypto.randomBytes(32).toString('hex');
// Write to .env file
const envPath = path.join(__dirname, '.env');
try {
let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : '';
if (envContent.includes('SHARE_ADMIN_KEY=')) {
envContent = envContent.replace(/SHARE_ADMIN_KEY=.*/g, `SHARE_ADMIN_KEY=${newKey}`);
} else {
envContent += `\nSHARE_ADMIN_KEY=${newKey}`;
}
fs.writeFileSync(envPath, envContent);
// Update in-memory (requires restart for full effect, but update the module cache)
require('./lib/config').SHARE_ADMIN_KEY = newKey;
return sendJSON(res, { key: newKey, note: 'Key aktualisiert. Server-Neustart empfohlen.' });
} catch (err) {
return sendJSON(res, { error: err.message }, 500);
}
}
// --- Share admin API (admin key auth, before multi-user check) ---
if (pathname.startsWith('/api/shares')) {
const authHeader = req.headers.authorization || '';
const currentShareKey = require('./lib/config').SHARE_ADMIN_KEY;
const isAdmin = currentShareKey && authHeader === `Bearer ${currentShareKey}`;
const sessionUser = authenticateRequest(req);
if (!isAdmin && !(MULTI_USER ? sessionUser : true)) {
return sendJSON(res, { error: 'Unauthorized' }, 401);
}
// In multi-user mode, use a cached global aggregator (rebuilt every 5 min)
const shareAgg = MULTI_USER ? (() => {
const now = Date.now();
if (!global._shareAggCache || now - global._shareAggCacheTime > 300000) {
const { streamAllMessages } = require('./lib/db');
const a = new Aggregator();
// SECURITY: do NOT apply a cross-user alias union here. This aggregator
// spans every user's messages and backs the global/admin shares; folding
// it with another user's merge map would let any user rewrite project-name
// resolution for everyone's shares (cross-tenant poisoning). Shares resolve
// to the literal project name in multi-user mode. Per-user merges only
// affect each user's own (scoped) dashboard aggregator.
a.addMessages(streamAllMessages());
global._shareAggCache = a;
global._shareAggCacheTime = now;
}
return global._shareAggCache;
})() : aggregator;
if (pathname === '/api/shares/projects' && req.method === 'GET') {
const projects = shareAgg.getProjects();
return sendJSON(res, (projects || []).map(p => ({
name: p.name,
messages: p.messages,
sessions: p.sessions,
last_activity: p.lastTs,
})));
}
if (pathname === '/api/shares' && req.method === 'GET') {
return sendJSON(res, listProjectShares());
}