-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js.clean
More file actions
660 lines (560 loc) · 20.6 KB
/
server.js.clean
File metadata and controls
660 lines (560 loc) · 20.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
const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const path = require("path");
const fs = require("fs");
// Import our library modules
const ServiceManager = require("./lib/services");
const PRPCClient = require("./lib/api");
const LogManager = require("./lib/logs");
const NetworkManager = require("./lib/network");
const SystemMonitor = require("./lib/system");
// Load configuration
const config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
// Initialize Express app
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Initialize Terminal Manager
const terminalManager = require("./lib/terminal");
// Middleware
app.use(express.json());
app.use(express.static("public"));
// Rate limiting (simple in-memory implementation)
const requestCounts = new Map();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const MAX_REQUESTS = config.security.rateLimit.maxRequestsPerMinute || 60;
function checkRateLimit(req, res, next) {
if (!config.security.rateLimit.enabled) {
return next();
}
const ip = req.ip;
const now = Date.now();
if (!requestCounts.has(ip)) {
requestCounts.set(ip, { count: 1, resetTime: now + RATE_LIMIT_WINDOW });
return next();
}
const record = requestCounts.get(ip);
if (now > record.resetTime) {
record.count = 1;
record.resetTime = now + RATE_LIMIT_WINDOW;
return next();
}
if (record.count >= MAX_REQUESTS) {
return res.status(429).json({ error: "Rate limit exceeded" });
}
record.count++;
next();
}
app.use(checkRateLimit);
// ============================================================================
// API ENDPOINTS
// ============================================================================
/**
* Dashboard overview
*/
app.get("/api/dashboard", async (req, res) => {
try {
const [services, system, network, prpcHealth] = await Promise.all([
ServiceManager.getStatusSummary(),
SystemMonitor.getAllStats(),
NetworkManager.getSummary(),
PRPCClient.healthCheck()
]);
res.json({
success: true,
timestamp: new Date().toISOString(),
services,
system,
network,
prpc: prpcHealth
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Get all service statuses
*/
app.get("/api/services", async (req, res) => {
try {
const statuses = await ServiceManager.getAllStatus();
res.json({ success: true, services: statuses });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Get single service status
*/
app.get("/api/services/:name", async (req, res) => {
try {
const status = await ServiceManager.getStatus(req.params.name);
res.json({ success: true, service: status });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
/**
* Control a service (start/stop/restart)
*/
app.post("/api/services/:name/:action", async (req, res) => {
if (!config.security.enableServiceControl) {
return res.status(403).json({ success: false, error: "Service control is disabled" });
}
try {
const result = await ServiceManager.controlService(
req.params.name,
req.params.action
);
res.json(result);
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
/**
* Restart all services
*/
app.post("/api/services/restart-all", async (req, res) => {
if (!config.security.enableServiceControl) {
return res.status(403).json({ success: false, error: "Service control is disabled" });
}
try {
const results = await ServiceManager.restartAll();
res.json({ success: true, results });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Get logs for a service
*/
app.get("/api/logs/:service", async (req, res) => {
try {
const lines = parseInt(req.query.lines) || 50;
const filter = req.query.filter || null;
const logs = await LogManager.getLogs(req.params.service, lines, filter);
res.json(logs);
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
/**
* Find pubkey (restart pod and extract from logs)
*/
app.post("/api/find-pubkey", async (req, res) => {
try {
const result = await LogManager.findPubkey();
res.json(result);
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* pRPC API calls
*/
app.post("/api/prpc/:method", async (req, res) => {
try {
const method = req.params.method;
const params = req.body.params || {};
let result;
// Handle known methods
switch (method) {
case "get-version":
result = await PRPCClient.getVersion();
break;
case "get-stats":
result = await PRPCClient.getStats();
break;
case "get-pods":
result = await PRPCClient.getPods();
break;
default:
// Custom method
result = await PRPCClient.customCall(method, params);
}
res.json(result);
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Network diagnostics
*/
app.get("/api/network", async (req, res) => {
try {
const diagnostics = await NetworkManager.runDiagnostics();
res.json({ success: true, diagnostics });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* System stats
*/
app.get("/api/system", async (req, res) => {
// Xandeum disk space endpoint
app.get("/api/xandeum-space", async (req, res) => {
// Devnet eligibility check endpoint
app.get("/api/devnet-eligibility", async (req, res) => {
try {
const axios = require("axios");
// Fetch all pod credits
const response = await axios.get("https://podcredits.xandeum.network/api/pods-credits");
const allPods = response.data.pods_credits;
if (!allPods || !Array.isArray(allPods)) {
return res.status(500).json({ success: false, error: "Invalid API response" });
}
// Extract credits values and sort
const creditsValues = allPods.map(pod => pod.credits || 0).sort((a, b) => b - a);
// Calculate statistics
const highest = creditsValues[0] || 0;
const percentile95Index = Math.floor(creditsValues.length * 0.05);
const percentile95 = creditsValues[percentile95Index] || 0;
const threshold = percentile95 * 0.8;
// This would need the pod public key - you may need to adjust based on how to identify your pod
res.json({
success: true,
devnet: {
highest: highest,
percentile95: percentile95,
threshold: threshold,
currentPod: currentPodCredits,
eligible: isEligible,
totalPods: creditsValues.length,
calculation: `80% of 95th percentile: ${percentile95.toFixed(2)} × 0.8 = ${threshold.toFixed(2)}`
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// Get local pod public key
app.get("/api/pod-pubkey", async (req, res) => {
try {
const fs = require("fs");
const keypairPath = "/local/keypairs/pnode-keypair.json";
if (fs.existsSync(keypairPath)) {
const keypairData = JSON.parse(fs.readFileSync(keypairPath, "utf8"));
res.json({ success: true, pubkey: keypairData.publicKey });
} else {
res.json({ success: false, error: "Keypair not found" });
}
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
try {
const axios = require("axios");
// Fetch all pod credits
const response = await axios.get("https://podcredits.xandeum.network/api/pods-credits");
const allPods = response.data.pods_credits;
if (!allPods || !Array.isArray(allPods)) {
return res.status(500).json({ success: false, error: "Invalid API response" });
}
// Extract credits values and sort
const creditsValues = allPods.map(pod => pod.credits || 0).sort((a, b) => b - a);
// Calculate statistics
const highest = creditsValues[0] || 0;
const percentile95Index = Math.floor(creditsValues.length * 0.05);
const percentile95 = creditsValues[percentile95Index] || 0;
const threshold = percentile95 * 0.8;
// This would need the pod public key - you may need to adjust based on how to identify your pod
res.json({
success: true,
devnet: {
highest: highest,
percentile95: percentile95,
threshold: threshold,
currentPod: currentPodCredits,
eligible: isEligible,
totalPods: creditsValues.length,
calculation: `80% of 95th percentile: ${percentile95.toFixed(2)} × 0.8 = ${threshold.toFixed(2)}`
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
try {
const { execSync } = require("child_process");
// Calculate disk space for Xandeum components
let xandminerSize = 0;
let xandminerdSize = 0;
// Check for xandeum data directory
let xandeumDataSize = 0;
try {
const xandeumDataOutput = execSync("du -sb /root/.xandeum 2>/dev/null || echo 0", { encoding: "utf-8" });
xandeumDataSize = parseInt(xandeumDataOutput.split("\t")[0]) || 0;
} catch (e) {}
let podSize = 0;
try {
const xandminerOutput = execSync("du -sb /root/xandminer /root/.xandeum 2>/dev/null | grep xandminer 2>/dev/null || echo 0", { encoding: "utf-8" });
xandminerSize = parseInt(xandminerOutput.split(" ")[0]) || 0;
} catch (e) {}
try {
const xandminerdOutput = execSync("du -sb /root/xandminer /root/.xandeum 2>/dev/null | grep xandminerd 2>/dev/null || echo 0", { encoding: "utf-8" });
xandminerdSize = parseInt(xandminerdOutput.split(" ")[0]) || 0;
// Check for xandeum data directory
let xandeumDataSize = 0;
try {
const xandeumDataOutput = execSync("du -sb /root/.xandeum 2>/dev/null || echo 0", { encoding: "utf-8" });
xandeumDataSize = parseInt(xandeumDataOutput.split("\t")[0]) || 0;
} catch (e) {}
} catch (e) {}
try {
const podOutput = execSync("dpkg -L pod 2>/dev/null | xargs du -cb 2>/dev/null | tail -1 || echo 0", { encoding: "utf-8" });
podSize = parseInt(podOutput.split(" ")[0]) || 0;
} catch (e) {}
// Track xandeum-pages file
let xandeumPagesSize = 0;
try {
const pagesOutput = execSync("stat -c%s /xandeum-pages 2>/dev/null || echo 0", { encoding: "utf-8" });
xandeumPagesSize = parseInt(pagesOutput.trim()) || 0;
} catch (e) {}
const totalBytes = xandminerSize + xandminerdSize + podSize + xandeumPagesSize;
const totalMB = (totalBytes / 1024 / 1024).toFixed(2);
const totalGB = (totalBytes / 1024 / 1024 / 1024).toFixed(2);
res.json({
success: true,
xandeum: {
xandminer: { bytes: xandminerSize, mb: (xandminerSize / 1024 / 1024).toFixed(2) },
xandminerd: { bytes: xandminerdSize, mb: (xandminerdSize / 1024 / 1024).toFixed(2) },
pod: { bytes: podSize, mb: (podSize / 1024 / 1024).toFixed(2) },
xandeumPages: { bytes: xandeumPagesSize, mb: (xandeumPagesSize / 1024 / 1024).toFixed(2), gb: (xandeumPagesSize / 1024 / 1024 / 1024).toFixed(2) },
total: { bytes: totalBytes, mb: totalMB, gb: totalGB }
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
});
// Xandeum disk space endpoint
app.get("/api/xandeum-space", async (req, res) => {
// Devnet eligibility check endpoint
app.get("/api/devnet-eligibility", async (req, res) => {
try {
const axios = require("axios");
// Fetch all pod credits
const response = await axios.get("https://podcredits.xandeum.network/api/pods-credits");
const allPods = response.data.pods_credits;
if (!allPods || !Array.isArray(allPods)) {
return res.status(500).json({ success: false, error: "Invalid API response" });
}
// Extract credits values and sort
const creditsValues = allPods.map(pod => pod.credits || 0).sort((a, b) => b - a);
// Calculate statistics
const highest = creditsValues[0] || 0;
const percentile95Index = Math.floor(creditsValues.length * 0.05);
const percentile95 = creditsValues[percentile95Index] || 0;
const threshold = percentile95 * 0.8;
// This would need the pod public key - you may need to adjust based on how to identify your pod
res.json({
success: true,
devnet: {
highest: highest,
percentile95: percentile95,
threshold: threshold,
currentPod: currentPodCredits,
eligible: isEligible,
totalPods: creditsValues.length,
calculation: `80% of 95th percentile: ${percentile95.toFixed(2)} × 0.8 = ${threshold.toFixed(2)}`
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
try {
const { execSync } = require("child_process");
// Calculate disk space for Xandeum components
let xandminerSize = 0;
let xandminerdSize = 0;
// Check for xandeum data directory
let xandeumDataSize = 0;
try {
const xandeumDataOutput = execSync("du -sb /root/.xandeum 2>/dev/null || echo 0", { encoding: "utf-8" });
xandeumDataSize = parseInt(xandeumDataOutput.split("\t")[0]) || 0;
} catch (e) {}
let podSize = 0;
try {
const xandminerOutput = execSync("du -sb /root/xandminer /root/.xandeum 2>/dev/null | grep xandminer 2>/dev/null || echo 0", { encoding: "utf-8" });
xandminerSize = parseInt(xandminerOutput.split(" ")[0]) || 0;
} catch (e) {}
try {
const xandminerdOutput = execSync("du -sb /root/xandminer /root/.xandeum 2>/dev/null | grep xandminerd 2>/dev/null || echo 0", { encoding: "utf-8" });
xandminerdSize = parseInt(xandminerdOutput.split(" ")[0]) || 0;
// Check for xandeum data directory
let xandeumDataSize = 0;
try {
const xandeumDataOutput = execSync("du -sb /root/.xandeum 2>/dev/null || echo 0", { encoding: "utf-8" });
xandeumDataSize = parseInt(xandeumDataOutput.split("\t")[0]) || 0;
} catch (e) {}
} catch (e) {}
try {
const podOutput = execSync("dpkg -L pod 2>/dev/null | xargs du -cb 2>/dev/null | tail -1 || echo 0", { encoding: "utf-8" });
podSize = parseInt(podOutput.split(" ")[0]) || 0;
} catch (e) {}
// Track xandeum-pages file
let xandeumPagesSize = 0;
try {
const pagesOutput = execSync("stat -c%s /xandeum-pages 2>/dev/null || echo 0", { encoding: "utf-8" });
xandeumPagesSize = parseInt(pagesOutput.trim()) || 0;
} catch (e) {}
const totalBytes = xandminerSize + xandminerdSize + podSize + xandeumPagesSize;
const totalMB = (totalBytes / 1024 / 1024).toFixed(2);
const totalGB = (totalBytes / 1024 / 1024 / 1024).toFixed(2);
res.json({
success: true,
xandeum: {
xandminer: { bytes: xandminerSize, mb: (xandminerSize / 1024 / 1024).toFixed(2) },
xandminerd: { bytes: xandminerdSize, mb: (xandminerdSize / 1024 / 1024).toFixed(2) },
pod: { bytes: podSize, mb: (podSize / 1024 / 1024).toFixed(2) },
xandeumPages: { bytes: xandeumPagesSize, mb: (xandeumPagesSize / 1024 / 1024).toFixed(2), gb: (xandeumPagesSize / 1024 / 1024 / 1024).toFixed(2) },
total: { bytes: totalBytes, mb: totalMB, gb: totalGB }
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Health check
*/
app.get("/api/health", async (req, res) => {
try {
const [systemHealth, serviceStatus] = await Promise.all([
SystemMonitor.getHealthStatus(),
ServiceManager.getStatusSummary()
]);
const overallScore = Math.floor(
(systemHealth.score * 0.4) +
((serviceStatus.summary.running / serviceStatus.summary.total) * 100 * 0.6)
);
res.json({
success: true,
score: overallScore,
status: overallScore >= 80 ? "healthy" : overallScore >= 50 ? "warning" : "critical",
system: systemHealth,
services: serviceStatus
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Get terminal activity log
*/
app.get("/api/terminal/activity", (req, res) => {
// TMUX status endpoint
const limit = parseInt(req.query.limit) || 100;
const log = terminalManager.getActivityLog(limit);
res.json({ success: true, log });
});
// ============================================================================
// WEBSOCKET TERMINAL HANDLER
// ============================================================================
wss.on("connection", (ws) => {
if (!config.security.enableTerminal) {
ws.close(1008, "Terminal access is disabled");
return;
}
const sessionId = generateSessionId();
let ptyProcess = null;
console.log(`[Terminal] New connection: ${sessionId}`);
try {
ptyProcess = terminalManager.createSession(sessionId);
// Send data from PTY to WebSocket
ptyProcess.on("data", (data) => {
try {
ws.send(data);
} catch (error) {
console.error(`[Terminal] Error sending data: ${error.message}`);
}
});
// Handle PTY exit
ptyProcess.on("exit", () => {
console.log(`[Terminal] PTY exited: ${sessionId}`);
terminalManager.destroySession(sessionId);
ws.close();
});
} catch (error) {
console.error(`[Terminal] Error creating session: ${error.message}`);
ws.send(`Error: ${error.message}\r\n`);
ws.close();
return;
}
// Handle incoming data from WebSocket
ws.on("message", (data) => {
try {
const message = JSON.parse(data);
if (message.type === "input") {
terminalManager.writeToSession(sessionId, message.data);
} else if (message.type === "resize") {
terminalManager.resizeSession(sessionId, message.cols, message.rows);
}
} catch (error) {
console.error(`[Terminal] Error processing message: ${error.message}`);
}
});
// Handle WebSocket close
ws.on("close", () => {
console.log(`[Terminal] Connection closed: ${sessionId}`);
terminalManager.destroySession(sessionId);
});
// Handle WebSocket error
ws.on("error", (error) => {
console.error(`[Terminal] WebSocket error: ${error.message}`);
terminalManager.destroySession(sessionId);
});
});
// ============================================================================
// CLEANUP & STARTUP
// ============================================================================
// Clean up inactive terminal sessions periodically
setInterval(() => {
terminalManager.cleanupInactiveSessions();
}, 300000); // Every 5 minutes
// Generate random session ID
function generateSessionId() {
return `term_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
// Start server
const HOST = config.server.host;
const PORT = config.server.port;
server.listen(PORT, HOST, () => {
console.log("");
console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.log(" Xandeum Pod Monitor");
console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.log("");
console.log(` Server: http://${HOST}:${PORT}`);
console.log(` Host: ${HOST === "127.0.0.1" ? "Localhost only" : "Public"}`);
console.log(` Security: Rate limiting ${config.security.rateLimit.enabled ? "enabled" : "disabled"}`);
console.log(` Terminal: ${config.security.enableTerminal ? "Enabled" : "Disabled"}`);
console.log(` Services: ${config.security.enableServiceControl ? "Control enabled" : "Read-only"}`);
console.log("");
if (HOST === "127.0.0.1") {
console.log(" Access remotely via SSH tunnel:");
console.log(` ssh -L ${PORT}:localhost:${PORT} user@your-server`);
}
console.log("");
console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.log("");
});
// Handle graceful shutdown
process.on("SIGINT", () => {
console.log("\n\nShutting down gracefully...");
server.close(() => {
console.log("Server closed");
process.exit(0);
});
});
process.on("SIGTERM", () => {
console.log("\n\nReceived SIGTERM, shutting down...");
server.close(() => {
console.log("Server closed");
process.exit(0);
});
});