-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cjs
More file actions
630 lines (581 loc) · 19.7 KB
/
server.cjs
File metadata and controls
630 lines (581 loc) · 19.7 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
/**
* TimeTrackly Local Server - Backend
*
* ARCHITECTURE OVERVIEW:
* This is a simple, local-only Node.js HTTP server designed for single-user operation.
* It serves as the data persistence layer for the time tracking application, handling
* all file I/O operations for JSON-based data storage.
*
* DESIGN PHILOSOPHY - Single-User, Local-First:
* - NO authentication or user management (single-user system)
* - NO database (direct JSON file I/O)
* - NO external dependencies (uses only Node.js built-ins)
* - Simple file locking (no distributed locks needed)
* - Local-only binding (127.0.0.1 for security)
*
* KEY RESPONSIBILITIES:
* 1. Serve static frontend files (index.html, JS modules)
* 2. Manage three JSON data files:
* - mtt-data.json: Historical time entries (append-only in practice)
* - mtt-active-state.json: Currently running timers (frequent updates)
* - mtt-suggestions.json: User-editable task suggestions
* 3. Ensure data integrity via atomic writes
* 4. Provide health monitoring endpoint
*
* CRITICAL DESIGN DECISIONS:
* - Atomic writes: Use temp file + rename to prevent corruption on crashes
* - File locking: Prevent concurrent writes (rare with single user, but possible)
* - Request validation: Limit payload size to prevent accidental data issues
* - Structured logging: JSON format for easy parsing and debugging
*
* MAINTAINABILITY NOTES:
* - All file operations use async/await for clarity
* - Error handling provides specific context for debugging
* - Environment variables allow configuration without code changes
* - Health endpoint enables quick diagnostics
*
* @module server
*/
const http = require("http");
const fs = require("fs").promises;
const fsSync = require("fs");
const path = require("path");
// --- Configuration (can be overridden by environment variables) ---
const PORT = process.env.PORT || 13331;
const DATA_DIR = process.env.DATA_DIR || __dirname;
const DATA_FILE_PATH = path.join(DATA_DIR, "mtt-data.json");
const ACTIVE_STATE_PATH = path.join(DATA_DIR, "mtt-active-state.json");
const SUGGESTIONS_PATH = path.join(DATA_DIR, "mtt-suggestions.json");
const LOCK_FILE_PATH = path.join(DATA_DIR, "mtt-data.lock");
const MAX_PAYLOAD_SIZE = 1048576; // 1MB
// --- Logging Utility ---
const log = {
info: (msg, meta = {}) => {
console.log(
JSON.stringify({
level: "INFO",
timestamp: new Date().toISOString(),
message: msg,
...meta,
})
);
},
error: (msg, meta = {}) => {
console.error(
JSON.stringify({
level: "ERROR",
timestamp: new Date().toISOString(),
message: msg,
...meta,
})
);
},
warn: (msg, meta = {}) => {
console.warn(
JSON.stringify({
level: "WARN",
timestamp: new Date().toISOString(),
message: msg,
...meta,
})
);
},
};
// --- File Locking Utility ---
const acquireLock = async (timeout = 5000) => {
const startTime = Date.now();
while (fsSync.existsSync(LOCK_FILE_PATH)) {
if (Date.now() - startTime > timeout) {
throw new Error("Could not acquire file lock: timeout");
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
await fs.writeFile(LOCK_FILE_PATH, process.pid.toString());
};
const releaseLock = async () => {
try {
if (fsSync.existsSync(LOCK_FILE_PATH)) {
await fs.unlink(LOCK_FILE_PATH);
}
} catch (error) {
log.warn("Failed to release lock", { error: error.message });
}
};
// --- Atomic File Write Utility ---
/**
* Writes data to a file atomically using temp file + rename pattern.
*
* WHY ATOMIC WRITES MATTER:
* Without atomic writes, if the process crashes during file.writeFile(), the file
* can be left in a partially written state (corrupted). This is catastrophic for
* JSON files which must be perfectly formatted to parse correctly.
*
* HOW IT WORKS:
* 1. Write data to a temporary file (filename.tmp)
* 2. If successful, rename temp file to target filename
* 3. The rename operation is atomic at the OS level
*
* Result: Either the old file exists (if crash before rename) or the new file
* exists (if crash after rename). Never a partially-written file.
*
* SINGLE-USER CONTEXT:
* File locking prevents concurrent writes. While rare with single user, it's
* possible if user manually triggers multiple saves rapidly, or if a server
* restart occurs during a save operation.
*
* IMPACT: If you remove atomic writes, data corruption becomes likely during
* system crashes, power failures, or forced shutdowns.
*
* @param {string} filePath - Target file path
* @param {string} data - Data to write
* @throws {Error} If write operation fails
*/
const writeFileAtomic = async (filePath, data) => {
const tempPath = `${filePath}.tmp`;
try {
await acquireLock();
await fs.writeFile(tempPath, data, "utf8");
await fs.rename(tempPath, filePath);
log.info("File written atomically", { filePath });
} catch (error) {
// Clean up temp file if it exists
try {
if (fsSync.existsSync(tempPath)) {
await fs.unlink(tempPath);
}
} catch (cleanupError) {
log.warn("Failed to cleanup temp file", { tempPath });
}
throw error;
} finally {
await releaseLock();
}
};
// --- Request Validation Utility ---
/**
* Validates and parses JSON body from request with size limits.
*
* WHY VALIDATION MATTERS:
* Even in a single-user, local context, validation prevents:
* 1. Accidental corruption from malformed requests
* 2. Resource exhaustion from accidentally large payloads
* 3. Clear error messages for debugging
*
* PAYLOAD SIZE LIMIT (1MB):
* - Typical active state: ~1-10KB for dozens of timers
* - Typical historical data: ~100KB for thousands of entries
* - 1MB limit provides 10-100x safety margin
* - Prevents accidental infinite loops or bugs from filling disk
*
* SINGLE-USER CONTEXT:
* This isn't protection against malicious users (there are none), but against
* bugs in the frontend code or accidental data issues.
*
* @param {http.IncomingMessage} req - Request object
* @param {number} maxSize - Maximum payload size in bytes
* @returns {Promise<any>} Parsed JSON object
* @throws {Error} If payload too large, invalid JSON, or request error
*/
const validateJsonBody = (req, maxSize = MAX_PAYLOAD_SIZE) => {
return new Promise((resolve, reject) => {
let body = "";
let size = 0;
req.on("data", (chunk) => {
size += chunk.length;
if (size > maxSize) {
reject({
statusCode: 413,
message: "Payload too large",
});
req.connection.destroy();
return;
}
body += chunk.toString();
});
req.on("end", () => {
try {
const parsed = JSON.parse(body);
resolve(parsed);
} catch (err) {
reject({
statusCode: 400,
message: "Invalid JSON format",
});
}
});
req.on("error", (err) => {
reject({
statusCode: 500,
message: "Request error",
error: err.message,
});
});
});
};
// --- Pre-flight Check: Ensure data file exists on startup ---
const initializeDataFile = async () => {
try {
await fs.access(DATA_FILE_PATH);
log.info("Data file already exists", { path: DATA_FILE_PATH });
} catch {
log.info("Creating new data file", { path: DATA_FILE_PATH });
await writeFileAtomic(DATA_FILE_PATH, "[]");
log.info("Successfully created data file");
}
};
// --- Pre-flight Check: Ensure active state file exists on startup ---
const initializeActiveStateFile = async () => {
try {
await fs.access(ACTIVE_STATE_PATH);
log.info("Active state file already exists", { path: ACTIVE_STATE_PATH });
} catch {
log.info("Creating new active state file", { path: ACTIVE_STATE_PATH });
await writeFileAtomic(ACTIVE_STATE_PATH, "{}");
log.info("Successfully created active state file");
}
};
// --- Pre-flight Check: Ensure suggestions file exists on startup ---
const initializeSuggestionsFile = async () => {
try {
await fs.access(SUGGESTIONS_PATH);
log.info("Suggestions file already exists", { path: SUGGESTIONS_PATH });
} catch {
log.info("Creating new suggestions file", { path: SUGGESTIONS_PATH });
const defaultSuggestions = [
"Project Gemini / Coding",
"Project Gemini / Documentation",
"Internal Admin / Meetings",
"Internal Admin / Email Response",
"Client X / Proposal Draft",
"Learning / Tutorial Videos",
];
await writeFileAtomic(
SUGGESTIONS_PATH,
JSON.stringify(defaultSuggestions, null, 2)
);
log.info("Successfully created suggestions file");
}
};
// --- Initialize all necessary files before starting the server ---
const initializeAllFiles = async () => {
try {
await initializeDataFile();
await initializeActiveStateFile();
await initializeSuggestionsFile();
return true;
} catch (error) {
log.error("CRITICAL: Failed to initialize files", { error: error.message });
return false;
}
};
// --- Data Validation Function ---
/**
* Validates that an array contains valid historical entry objects.
*
* WHY VALIDATION MATTERS:
* - Ensures data integrity before persisting to disk
* - Prevents corrupted data from frontend bugs
* - Provides clear error messages for debugging
*
* REQUIRED FIELDS:
* - project (string): Project name
* - task (string): Task description
* - totalDurationMs (number): Duration in milliseconds
* - durationSeconds (number): Duration in seconds
* - endTime (ISO date string): When timer ended
* - createdAt (ISO date string): When timer started
* - notes (string, optional): User notes
*
* @param {Array} entries - Array of historical entry objects to validate
* @returns {string|null} Error message if invalid, null if valid
*/
const validateHistoricalEntries = (entries) => {
if (!Array.isArray(entries)) {
return "Data must be an array";
}
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
// Check required fields exist
if (!entry.project || typeof entry.project !== "string") {
return `Entry ${i}: project must be a non-empty string`;
}
if (!entry.task || typeof entry.task !== "string") {
return `Entry ${i}: task must be a non-empty string`;
}
if (typeof entry.totalDurationMs !== "number" || entry.totalDurationMs < 0) {
return `Entry ${i}: totalDurationMs must be a non-negative number`;
}
if (typeof entry.durationSeconds !== "number" || entry.durationSeconds < 0) {
return `Entry ${i}: durationSeconds must be a non-negative number`;
}
// Validate ISO date strings
const endTime = new Date(entry.endTime);
if (isNaN(endTime.getTime())) {
return `Entry ${i}: endTime must be a valid ISO date string`;
}
const createdAt = new Date(entry.createdAt);
if (isNaN(createdAt.getTime())) {
return `Entry ${i}: createdAt must be a valid ISO date string`;
}
// Optional notes field
if (entry.notes !== undefined && typeof entry.notes !== "string") {
return `Entry ${i}: notes must be a string`;
}
// Sanity check: duration should match time difference
const duration = endTime.getTime() - createdAt.getTime();
if (Math.abs(duration - entry.totalDurationMs) > 1000) {
// Allow 1 second tolerance for rounding
log.warn("Duration mismatch in entry", {
index: i,
calculatedMs: duration,
storedMs: entry.totalDurationMs,
});
}
}
return null; // All validations passed
};
// --- HTTP Request Handler ---
const requestHandler = async (req, res) => {
try {
// --- API Endpoint: /api/health ---
if (req.url === "/api/health" && req.method === "GET") {
const health = {
status: "ok",
timestamp: new Date().toISOString(),
uptime: process.uptime(),
dataFiles: {
data: fsSync.existsSync(DATA_FILE_PATH),
activeState: fsSync.existsSync(ACTIVE_STATE_PATH),
suggestions: fsSync.existsSync(SUGGESTIONS_PATH),
},
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(health, null, 2));
return;
}
// --- API Endpoint: /api/suggestions ---
if (req.url === "/api/suggestions" && req.method === "GET") {
try {
const data = await fs.readFile(SUGGESTIONS_PATH, "utf8");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(data);
} catch (error) {
log.error("Error reading suggestions file", { error: error.message });
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Error reading suggestions file" }));
}
return;
}
// --- API Endpoint: /api/active-state ---
if (req.url === "/api/active-state") {
// GET: Read and return the active state file
if (req.method === "GET") {
try {
const data = await fs.readFile(ACTIVE_STATE_PATH, "utf8");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(data);
} catch (error) {
log.error("Error reading active state file", {
error: error.message,
});
res.writeHead(500, { "Content-Type": "application/json" });
res.end(
JSON.stringify({ message: "Error reading active state file" })
);
}
return;
}
// POST: Receive new active state and overwrite the file
if (req.method === "POST") {
try {
const data = await validateJsonBody(req);
await writeFileAtomic(
ACTIVE_STATE_PATH,
JSON.stringify(data, null, 2)
);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Active state saved" }));
log.info("Active state saved successfully");
} catch (error) {
const statusCode = error.statusCode || 500;
const message = error.message || "Error writing to active state file";
log.error("Error saving active state", { error: message });
res.writeHead(statusCode, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message }));
}
return;
}
}
// --- API Endpoint: /api/data ---
if (req.url === "/api/data") {
// GET: Read and return all historical data from the JSON file.
if (req.method === "GET") {
try {
const data = await fs.readFile(DATA_FILE_PATH, "utf8");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(data);
} catch (error) {
log.error("Error reading data file", { error: error.message });
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Error reading data file" }));
}
return;
}
// POST: Receive new data and overwrite the historical data file.
if (req.method === "POST") {
try {
const data = await validateJsonBody(req);
// Validate data structure and content
const validationError = validateHistoricalEntries(data);
if (validationError) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: validationError }));
return;
}
await writeFileAtomic(DATA_FILE_PATH, JSON.stringify(data, null, 2));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Data saved successfully" }));
log.info("Historical data saved successfully", {
entriesCount: data.length,
});
} catch (error) {
const statusCode = error.statusCode || 500;
const message = error.message || "Error writing to data file";
log.error("Error saving data", { error: message });
res.writeHead(statusCode, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message }));
}
return;
}
}
// --- Static File Server: Serve index.html ---
if (req.url === "/" || req.url === "/index.html") {
try {
const content = await fs.readFile(path.join(__dirname, "index.html"));
res.writeHead(200, { "Content-Type": "text/html" });
res.end(content);
} catch (error) {
log.error("Error loading index.html", { error: error.message });
res.writeHead(500);
res.end("Critical Error: Could not load index.html");
}
return;
}
// --- Serve favicon ---
if (req.url === "/favicon.ico") {
// Simple SVG favicon (timer icon)
const faviconSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="45" fill="#4285f4"/><path d="M50 25 L50 50 L70 60" stroke="white" stroke-width="6" fill="none" stroke-linecap="round"/></svg>`;
res.writeHead(200, { "Content-Type": "image/svg+xml" });
res.end(faviconSVG);
return;
}
// --- Static File Server: Serve JS modules ---
if (req.url.startsWith("/js/") && req.url.endsWith(".js")) {
try {
// SECURITY: Prevent path traversal attacks (../../ sequences)
// Extract filename from URL and verify it's in /js/ directory
const requestedPath = path.normalize(req.url);
// Reject if path tries to escape /js/ directory
if (!requestedPath.startsWith("/js/") || requestedPath.includes("..")) {
log.warn("Rejected path traversal attempt", { url: req.url });
res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Access denied" }));
return;
}
const filePath = path.join(__dirname, requestedPath);
const resolvedPath = path.resolve(filePath);
const allowedDir = path.resolve(__dirname, "js");
// Double-check: ensure resolved path is within /js/ directory
if (!resolvedPath.startsWith(allowedDir)) {
log.warn("Rejected path traversal attempt (resolution check)", { url: req.url });
res.writeHead(403, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Access denied" }));
return;
}
const content = await fs.readFile(filePath, "utf8");
res.writeHead(200, { "Content-Type": "application/javascript" });
res.end(content);
} catch (error) {
log.error("Error loading JS module", {
error: error.message,
url: req.url,
});
res.writeHead(404);
res.end("JS module not found");
}
return;
}
// --- 404 Not Found for any other request ---
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Endpoint not found" }));
} catch (error) {
// Catch-all error handler for unexpected errors
log.error("Unexpected error in request handler", {
error: error.message,
stack: error.stack,
});
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Internal server error" }));
}
}
};
// --- Main Server Initialization ---
const startServer = async () => {
// Initialize all files before starting
const initialized = await initializeAllFiles();
if (!initialized) {
log.error("Failed to initialize files. Exiting.");
process.exit(1);
}
// Clean up any stale lock file
await releaseLock();
const server = http.createServer(requestHandler);
server.listen(PORT, "127.0.0.1", () => {
log.info("TimeTrackly Server started successfully", {
port: PORT,
url: `http://localhost:${PORT}`,
});
console.log(`✅ TimeTrackly Server is running.`);
console.log(
` Open your browser and navigate to http://localhost:${PORT}`
);
});
// Graceful shutdown
const shutdown = async (signal) => {
log.info("Shutdown signal received", { signal });
console.log(`\nShutting down server (${signal})...`);
// Clean up lock file
await releaseLock();
server.close(() => {
log.info("Server shut down successfully");
console.log("Server shut down successfully.");
process.exit(0);
});
// Force exit after 5 seconds if graceful shutdown fails
setTimeout(() => {
log.error("Forced shutdown after timeout");
console.error("Forced shutdown after timeout");
process.exit(1);
}, 5000);
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
// Handle uncaught errors
process.on("uncaughtException", (error) => {
log.error("Uncaught exception", {
error: error.message,
stack: error.stack,
});
shutdown("uncaughtException");
});
process.on("unhandledRejection", (reason, promise) => {
log.error("Unhandled rejection", { reason, promise });
});
};
// Start the server
startServer().catch((error) => {
log.error("Failed to start server", { error: error.message });
console.error("Failed to start server:", error);
process.exit(1);
});