forked from Curbob/LobsterBoard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cjs
More file actions
259 lines (226 loc) · 9.17 KB
/
Copy pathserver.cjs
File metadata and controls
259 lines (226 loc) · 9.17 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
/**
* LobsterBoard Builder Server
*
* A simple server to:
* - Serve builder static files
* - Handle loading and saving of config.json for the builder
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 8080;
const HOST = process.env.HOST || '127.0.0.1';
// ── Library modules ──
const config = require('./server/config.cjs');
const { CWD, PKG_DIR, PAGES_DIRS, PAGES_DIR, MIME_TYPES } = config;
const { loadPages, matchPageRoute } = require('./server/pages.cjs');
const { cachedStats, sseClients } = require('./server/stats.cjs');
const auth = require('./server/auth.cjs');
const { DASHBOARD_PASSWORD, sessions, isValidSession, getSessionCookie } = auth;
const { isPublicMode } = require('./server/secrets.cjs');
const { sendResponse, sendJson, sendError } = require('./server/response.cjs');
// ── Initialize pages ──
let loadedPages = loadPages();
console.log(`📄 Loaded ${loadedPages.length} page(s): ${loadedPages.map(p => p.icon + ' ' + p.title).join(', ') || 'none'}`);
// ── Route modules ──
const ctx = { __dirname };
const authRoutes = require('./server/routes/auth.cjs')(ctx);
const configRoutes = require('./server/routes/config.cjs')();
const serverRoutes = require('./server/routes/servers.cjs')();
const dataRoutes = require('./server/routes/data.cjs')();
const aiUsageRoutes = require('./server/routes/ai-usage.cjs')();
const systemRoutes = require('./server/routes/system.cjs')(ctx);
const proxyRoutes = require('./server/routes/proxy.cjs')();
const templateRoutes = require('./server/routes/templates.cjs')(ctx);
const fileRoutes = require('./server/routes/files.cjs')(ctx);
const server = http.createServer(async (req, res) => {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
// ── Auth: serve login page + login/logout actions ──
if (req.method === 'GET' && pathname === '/login') {
const loginPath = path.join(__dirname, 'login.html');
fs.readFile(loginPath, (err, data) => {
if (err) { sendResponse(res, 404, 'text/plain', 'Login page not found'); return; }
sendResponse(res, 200, 'text/html', data);
});
return;
}
if (req.method === 'POST' && pathname === '/api/auth/login') {
return authRoutes.handle(req, res, pathname, parsedUrl);
}
if (req.method === 'POST' && pathname === '/api/auth/logout') {
return authRoutes.handle(req, res, pathname, parsedUrl);
}
// ── Auth: enforce session for all other routes ──
if (DASHBOARD_PASSWORD) {
const token = getSessionCookie(req);
if (!isValidSession(token)) {
if (pathname.startsWith('/api/')) {
sendJson(res, 401, { status: 'error', message: 'Not authenticated' });
} else {
res.writeHead(302, { 'Location': '/login' });
res.end();
}
return;
}
}
// CORS preflight
if (req.method === 'OPTIONS' && (pathname === '/config' || pathname.startsWith('/api/') || pathname === '/api/pages')) {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
});
res.end();
return;
}
// ── Route delegation ──
// Auth-related routes (PIN, mode, secrets)
if (authRoutes.handle(req, res, pathname, parsedUrl)) return;
// Public mode guard: block edit-related APIs
if (isPublicMode()) {
const editPaths = ['/config'];
const isEditApi = (req.method === 'POST' && editPaths.includes(pathname)) ||
(req.method === 'POST' && pathname.startsWith('/api/templates/')) ||
(req.method === 'DELETE' && pathname.startsWith('/api/templates/'));
if (isEditApi) {
sendJson(res, 403, { error: 'Dashboard is in public mode. Editing is disabled.' });
return;
}
}
// Config routes
if (configRoutes.handle(req, res, pathname)) return;
// Server profiles routes
if (serverRoutes.handle(req, res, pathname)) return;
// Pages system routing
const pageMatch = matchPageRoute(loadedPages, req.method, pathname, parsedUrl);
if (pageMatch) {
if (pageMatch.type === 'list') {
sendJson(res, 200, loadedPages.filter(p => p.nav !== false).map(p => ({ id: p.id, title: p.title, icon: p.icon, description: p.description, order: p.order })));
return;
}
if (pageMatch.type === 'redirect') {
res.writeHead(302, { Location: pageMatch.location });
res.end();
return;
}
if (pageMatch.type === 'static') {
const resolved = path.resolve(pageMatch.filePath);
const isAllowed = PAGES_DIRS.some(dir => resolved.startsWith(path.resolve(dir)));
if (!isAllowed) {
sendResponse(res, 403, 'text/plain', 'Forbidden');
return;
}
const ext = path.extname(resolved).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(resolved, (err, data) => {
if (err) { sendResponse(res, 404, 'text/plain', 'Not Found'); return; }
sendResponse(res, 200, contentType, data);
});
return;
}
if (pageMatch.type === 'api') {
if (req.method === 'GET') {
try {
const result = await pageMatch.handler(req, res, { query: pageMatch.query, body: {}, params: pageMatch.params });
if (result !== undefined && !res.writableEnded) sendJson(res, res.statusCode || 200, result);
} catch (e) { sendError(res, e.message); }
return;
}
const MAX_BODY = 1024 * 1024;
let body = '';
let overflow = false;
req.on('data', chunk => { body += chunk.toString(); if (body.length > MAX_BODY) { overflow = true; req.destroy(); } });
req.on('end', async () => {
if (overflow) { sendError(res, 'Request body too large', 413); return; }
let parsed = {};
try { if (body) parsed = JSON.parse(body); } catch (_) {}
try {
const result = await pageMatch.handler(req, res, { query: pageMatch.query, body: parsed, params: pageMatch.params });
if (result !== undefined && !res.writableEnded) sendJson(res, res.statusCode || 200, result);
} catch (e) { sendError(res, e.message); }
});
return;
}
}
// Data routes (todos, notes)
if (dataRoutes.handle(req, res, pathname)) return;
// AI usage routes
if (await aiUsageRoutes.handle(req, res, pathname)) return;
// System routes (cron, logs, releases, today, activity)
if (systemRoutes.handle(req, res, pathname, parsedUrl)) return;
// Proxy routes (RSS, calendar, quote)
if (proxyRoutes.handle(req, res, pathname, parsedUrl)) return;
// Stats routes
if (req.method === 'GET' && pathname === '/api/stats') {
sendJson(res, 200, cachedStats);
return;
}
if (req.method === 'GET' && pathname === '/api/stats/stream') {
if (sseClients.size >= 10) {
sendError(res, 'Too many SSE connections', 429);
return;
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
res.write(`data: ${JSON.stringify(cachedStats)}\n\n`);
sseClients.add(res);
req.on('close', () => sseClients.delete(res));
return;
}
// Template routes
if (templateRoutes.handle(req, res, pathname, parsedUrl)) return;
// File routes (latest-image, browse-dirs)
if (fileRoutes.handle(req, res, pathname, parsedUrl)) return;
// Serve static files
const publicPath = path.join(CWD, 'public', pathname);
const publicResolved = path.resolve(publicPath);
if (publicResolved.startsWith(path.join(CWD, 'public') + path.sep) && fs.existsSync(publicPath)) {
const ext = path.extname(publicPath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(publicPath, (err, data) => {
if (err) { sendError(res, err.message); return; }
sendResponse(res, 200, contentType, data);
});
return;
}
let filePath = path.join(__dirname, pathname);
if (pathname === '/') {
filePath = path.join(__dirname, 'app.html');
}
const resolved = path.resolve(filePath);
if (!resolved.startsWith(__dirname + path.sep) && resolved !== __dirname) {
sendResponse(res, 403, 'text/plain', 'Forbidden');
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
sendResponse(res, 404, 'text/plain', 'Not Found');
} else {
sendError(res, `Server error: ${err.message}`);
}
return;
}
sendResponse(res, 200, contentType, data);
});
});
// Graceful shutdown
process.on('SIGTERM', () => server.close(() => process.exit(0)));
process.on('SIGINT', () => server.close(() => process.exit(0)));
server.listen(PORT, HOST, () => {
const authStatus = DASHBOARD_PASSWORD
? ' Password auth: ENABLED (DASHBOARD_PASSWORD is set)'
: ' Password auth: DISABLED — set DASHBOARD_PASSWORD=yourpassword to enable';
console.log(`
LobsterBoard Builder Server running at http://${HOST}:${PORT}
${authStatus}
Press Ctrl+C to stop
`);
});