-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
739 lines (619 loc) · 22.7 KB
/
Copy pathserver.js
File metadata and controls
739 lines (619 loc) · 22.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
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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 3000;
const DATA_DIR = path.join(__dirname, 'data');
const DATA_FILE = path.join(DATA_DIR, 'lists.json');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
// Trust proxy (required for correct IP detection behind Nginx/Docker/LXC proxies)
app.set('trust proxy', 1);
// Simple in-memory rate limiter
const rateLimit = new Map();
const RATE_LIMIT_WINDOW = parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000; // 15 minutes default
const MAX_REQUESTS = parseInt(process.env.RATE_LIMIT_MAX) || 1000; // 1000 requests default
function rateLimiter(req, res, next) {
// Use IP as the identifier.
// Note: In a real multi-user app with auth, you'd use the user ID.
// Here, we stick to IP to prevent abuse, but we've increased the limit
// to accommodate multiple users behind the same NAT/Proxy.
const ip = req.ip;
const now = Date.now();
if (!rateLimit.has(ip)) {
rateLimit.set(ip, { count: 1, startTime: now });
return next();
}
const userData = rateLimit.get(ip);
if (now - userData.startTime > RATE_LIMIT_WINDOW) {
// Reset window
userData.count = 1;
userData.startTime = now;
return next();
}
if (userData.count >= MAX_REQUESTS) {
console.warn(`Rate limit exceeded for IP: ${ip}`);
return res.status(429).json({ error: 'Too many requests, please try again later.' });
}
userData.count++;
next();
}
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Serve static files with caching policy
app.use(express.static('public', {
setHeaders: (res, path) => {
if (path.endsWith('index.html')) {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
} else {
// Cache other static assets (JS/CSS/Images) for a long time (1 year)
// since they are hashed by Vite
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
}
}));
app.use('/api', rateLimiter); // Apply rate limiting to API routes
// Ensure data directory exists
async function ensureDataDir() {
try {
await fs.access(DATA_DIR);
} catch {
await fs.mkdir(DATA_DIR, { recursive: true });
}
}
// Helper to read data
async function readData() {
try {
const data = await fs.readFile(DATA_FILE, 'utf8');
return JSON.parse(data);
} catch (err) {
if (err.code === 'ENOENT') {
return {};
}
console.error('Error reading data file:', err);
return {};
}
}
async function readUsers() {
try {
const data = await fs.readFile(USERS_FILE, 'utf8');
return JSON.parse(data);
} catch (err) {
if (err.code === 'ENOENT') {
return {};
}
console.error('Error reading users file:', err);
return {};
}
}
async function writeUsers(users) {
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
}
// Mutex for atomic operations
class Mutex {
constructor() {
this.queue = [];
this.locked = false;
}
async run(fn) {
return new Promise((resolve, reject) => {
this.queue.push({ fn, resolve, reject });
this.process();
});
}
async process() {
if (this.locked || this.queue.length === 0) return;
this.locked = true;
const { fn, resolve, reject } = this.queue.shift();
try {
const result = await fn();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.locked = false;
this.process();
}
}
}
const dbMutex = new Mutex();
// Helper to write data (direct write, concurrency handled by Mutex)
async function writeData(data) {
await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2));
broadcastChange();
}
// SSE Clients
let clients = [];
// Generate unique client ID
function generateClientId() {
return crypto.randomUUID();
}
// SSE Endpoint
app.get('/api/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const clientId = generateClientId();
const newClient = {
id: clientId,
res,
lastSeen: Date.now()
};
clients.push(newClient);
console.log(`SSE client connected: ${clientId} (${clients.length} total)`);
// Send initial connection message
res.write(`data: ${JSON.stringify({ type: 'connected', clientId })}\n\n`);
req.on('close', () => {
clients = clients.filter(client => client.id !== clientId);
console.log(`SSE client disconnected: ${clientId} (${clients.length} remaining)`);
});
});
function broadcastChange() {
const message = `data: ${JSON.stringify({ type: 'update' })}\n\n`;
clients = clients.filter(client => {
try {
client.res.write(message);
client.lastSeen = Date.now();
return true;
} catch (error) {
console.error('Failed to broadcast to client:', client.id, error.message);
return false; // Remove dead connection
}
});
}
// Heartbeat to detect stale connections
setInterval(() => {
const now = Date.now();
const timeout = 60000; // 1 minute
clients = clients.filter(client => {
try {
// Send heartbeat
client.res.write(': heartbeat\n\n');
// Check if client is stale
if (now - client.lastSeen > timeout) {
console.log(`Removing stale client: ${client.id}`);
return false;
}
return true;
} catch (error) {
console.log(`Removing dead client: ${client.id}`);
return false;
}
});
}, 30000); // Every 30 seconds
// Input validation helpers
function validateItemData(item) {
if (!item || typeof item !== 'object') {
return { valid: false, error: 'Invalid item data' };
}
if (!item.text || typeof item.text !== 'string' || item.text.trim() === '') {
return { valid: false, error: 'Item text is required' };
}
if (item.text.length > 128) {
return { valid: false, error: 'Item text must be 128 characters or less' };
}
if (item.amount !== undefined && (typeof item.amount !== 'number' || item.amount < 1)) {
return { valid: false, error: 'Invalid amount' };
}
return { valid: true };
}
function sanitizeUpdates(updates) {
const allowedFields = ['text', 'completed', 'amount'];
return Object.keys(updates)
.filter(key => allowedFields.includes(key))
.reduce((obj, key) => {
obj[key] = updates[key];
return obj;
}, {});
}
// Helper to get list data safely
function getList(data, listId) {
return data[listId] || null;
}
// Helper to touch a list (update timestamp)
function touchList(data, listId) {
const list = getList(data, listId);
if (list) {
list.updatedAt = Date.now();
}
}
// API Routes
// Register/Update User
app.post('/api/users/register', async (req, res) => {
await dbMutex.run(async () => {
try {
const { username, displayName } = req.body;
if (!username || typeof username !== 'string' || username.trim() === '') {
return res.status(400).json({ error: 'Username is required' });
}
const safeUsername = username.trim().toLowerCase();
const safeDisplayName = displayName ? displayName.trim() : safeUsername;
const users = await readUsers();
// Check if username exists
if (users[safeUsername]) {
// If it exists, we only allow updating if it's the same "session" or we just treat it as a login/update
// For this simple app, we'll allow updating the display name for the existing username
users[safeUsername].displayName = safeDisplayName;
users[safeUsername].lastSeen = Date.now();
} else {
// Register new user
users[safeUsername] = {
username: safeUsername,
displayName: safeDisplayName,
createdAt: Date.now(),
lastSeen: Date.now()
};
}
await writeUsers(users);
res.json({ success: true, user: users[safeUsername] });
} catch (error) {
console.error('Error registering user:', error);
res.status(500).json({ error: 'Failed to register user' });
}
});
});
// Get all users (Config Mode)
app.get('/api/users', async (req, res) => {
try {
const users = await readUsers();
// Convert users object to array for frontend
const userList = Object.values(users).map(user => ({
name: user.username,
displayName: user.displayName,
createdAt: user.createdAt,
lastSeen: user.lastSeen
}));
res.json(userList);
} catch (error) {
console.error('Error getting users:', error);
res.status(500).json({ error: 'Failed to get users' });
}
});
// Delete a user
app.delete('/api/users/:username', async (req, res) => {
await dbMutex.run(async () => {
try {
const username = req.params.username.toLowerCase();
const users = await readUsers();
if (!users[username]) {
return res.status(404).json({ error: 'User not found' });
}
delete users[username];
await writeUsers(users);
res.json({ success: true });
} catch (error) {
console.error('Error deleting user:', error);
res.status(500).json({ error: 'Failed to delete user' });
}
});
});
// Get user's favorite lists
app.get('/api/favorites/:username', async (req, res) => {
try {
const username = req.params.username.toLowerCase();
const users = await readUsers();
const user = users[username];
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user.favorites || []);
} catch (error) {
console.error('Error getting favorites:', error);
res.status(500).json({ error: 'Failed to get favorites' });
}
});
// Toggle favorite status for a list
app.post('/api/favorites/:username/:listId', async (req, res) => {
await dbMutex.run(async () => {
try {
const username = req.params.username.toLowerCase();
const listId = req.params.listId;
const users = await readUsers();
const user = users[username];
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
if (!user.favorites) {
user.favorites = [];
}
const index = user.favorites.indexOf(listId);
if (index > -1) {
// Remove from favorites
user.favorites.splice(index, 1);
} else {
// Add to favorites
user.favorites.push(listId);
}
await writeUsers(users);
res.json({ success: true, favorites: user.favorites });
} catch (error) {
console.error('Error toggling favorite:', error);
res.status(500).json({ error: 'Failed to toggle favorite' });
}
});
});
// Get all lists (Config Mode)
app.get('/api/lists', async (req, res) => {
try {
const data = await readData();
const lists = Object.entries(data).map(([name, value]) => {
return {
name,
displayName: value.displayName || name,
creatorName: value.creatorName,
createdBy: value.createdBy,
updatedAt: value.updatedAt,
itemCount: value.items.length
};
});
res.json(lists);
} catch (error) {
console.error('Error getting lists:', error);
res.status(500).json({ error: 'Failed to retrieve lists' });
}
});
// Create a new list with a display name (Config Mode)
app.post('/api/lists', async (req, res) => {
await dbMutex.run(async () => {
try {
const { displayName, createdBy, creatorName } = req.body;
if (!displayName || typeof displayName !== 'string' || displayName.trim() === '') {
return res.status(400).json({ error: 'Display name is required' });
}
if (displayName.length > 20) {
return res.status(400).json({ error: 'Display name must be 20 characters or less' });
}
const safeName = displayName.trim();
// Generate a unique ID for the list
const listId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const data = await readData();
data[listId] = {
items: [],
displayName: safeName,
createdBy: createdBy || null,
creatorName: creatorName || null,
updatedAt: Date.now()
};
await writeData(data);
res.json({ success: true, listId, displayName: safeName });
} catch (error) {
console.error('Error creating list:', error);
res.status(500).json({ error: 'Failed to create list' });
}
});
});
// Get a specific list details
app.get('/api/lists/:listId', async (req, res) => {
try {
const { listId } = req.params;
const data = await readData();
const list = getList(data, listId);
if (!list) {
return res.status(404).json({ error: 'List not found' });
}
const listDetails = {
name: listId,
displayName: list.displayName || listId,
updatedAt: list.updatedAt,
itemCount: list.items.length
};
res.json(listDetails);
} catch (error) {
console.error('Error getting list details:', error);
res.status(500).json({ error: 'Failed to retrieve list details' });
}
});
// Delete a specific list (Config Mode)
app.delete('/api/lists/:listId', async (req, res) => {
await dbMutex.run(async () => {
try {
const { listId } = req.params;
const data = await readData();
if (data[listId]) {
delete data[listId];
await writeData(data);
// Also remove from all users' favorites
const users = await readUsers();
let usersUpdated = false;
for (const username in users) {
const user = users[username];
if (user.favorites && user.favorites.includes(listId)) {
user.favorites = user.favorites.filter(id => id !== listId);
usersUpdated = true;
}
}
if (usersUpdated) {
await writeUsers(users);
}
}
res.json({ success: true });
} catch (error) {
console.error('Error deleting list:', error);
res.status(500).json({ error: 'Failed to delete list' });
}
});
});
// Get items for a specific list
app.get('/api/items/:listId', async (req, res) => {
try {
const { listId } = req.params;
const data = await readData();
if (!data[listId]) {
return res.status(404).json({ error: 'List not found' });
}
const list = getList(data, listId);
const items = list ? list.items : [];
res.json(items);
} catch (error) {
console.error('Error getting items:', error);
res.status(500).json({ error: 'Failed to retrieve items' });
}
});
// Add a single item
app.post('/api/items/:listId', async (req, res) => {
await dbMutex.run(async () => {
try {
const { listId } = req.params;
const incoming = req.body;
// Build a normalized item for validation
const candidate = {
text: incoming && incoming.text,
amount: incoming && incoming.amount,
completed: !!(incoming && incoming.completed),
addedBy: incoming && incoming.addedBy ? String(incoming.addedBy) : 'Guest',
authorName: incoming && incoming.authorName ? String(incoming.authorName) : (incoming && incoming.addedBy ? String(incoming.addedBy) : 'Guest')
};
const validation = validateItemData(candidate);
if (!validation.valid) {
return res.status(400).json({ error: validation.error });
}
const data = await readData();
// Initialize list if missing (recreation logic)
if (!data[listId]) {
data[listId] = {
items: [],
displayName: incoming.displayName || listId,
updatedAt: Date.now()
};
}
const list = getList(data, listId);
// Ensure a unique server-generated id
let id = incoming && incoming.id ? String(incoming.id) : null;
if (!id || list.items.some(it => it.id === id)) {
id = crypto.randomUUID();
}
const newItem = {
id,
text: String(candidate.text).trim(),
completed: !!candidate.completed,
amount: typeof candidate.amount === 'number' ? candidate.amount : 1,
addedBy: String(candidate.addedBy),
authorName: String(candidate.authorName)
};
list.items.push(newItem);
list.updatedAt = Date.now();
await writeData(data);
res.json({ success: true, item: newItem });
} catch (error) {
console.error('Error adding item:', error);
res.status(500).json({ error: 'Failed to add item' });
}
});
});
// Update a single item
app.patch('/api/items/:listId/:itemId', async (req, res) => {
await dbMutex.run(async () => {
try {
const { listId, itemId } = req.params;
const updates = req.body;
const data = await readData();
const list = getList(data, listId);
if (!list) {
return res.status(404).json({ error: 'List not found' });
}
const itemIndex = list.items.findIndex(item => String(item.id) === itemId);
if (itemIndex === -1) {
return res.status(404).json({ error: 'Item not found' });
}
// Sanitize and apply updates
const sanitizedUpdates = sanitizeUpdates(updates);
if (sanitizedUpdates.text !== undefined) {
if (typeof sanitizedUpdates.text !== 'string' || sanitizedUpdates.text.trim() === '' || sanitizedUpdates.text.length > 128) {
return res.status(400).json({ error: 'Invalid text for update' });
}
sanitizedUpdates.text = sanitizedUpdates.text.trim();
}
if (sanitizedUpdates.amount !== undefined) {
if (typeof sanitizedUpdates.amount !== 'number' || sanitizedUpdates.amount < 1) {
return res.status(400).json({ error: 'Invalid amount for update' });
}
}
list.items[itemIndex] = { ...list.items[itemIndex], ...sanitizedUpdates };
list.updatedAt = Date.now();
await writeData(data);
res.json({ success: true, item: list.items[itemIndex] });
} catch (error) {
console.error('Error updating item:', error);
res.status(500).json({ error: 'Failed to update item' });
}
});
});
// Delete all items in a list (Clear List)
app.delete('/api/items/:listId', async (req, res) => {
await dbMutex.run(async () => {
try {
const { listId } = req.params;
const data = await readData();
const list = getList(data, listId);
if (list) {
list.items = [];
list.updatedAt = Date.now();
await writeData(data);
}
res.json({ success: true });
} catch (error) {
console.error('Error clearing list:', error);
res.status(500).json({ error: 'Failed to clear list' });
}
});
});
// Delete all completed items
app.delete('/api/items/:listId/completed', async (req, res) => {
await dbMutex.run(async () => {
try {
const { listId } = req.params;
const data = await readData();
const list = getList(data, listId);
if (!list) {
return res.status(404).json({ error: 'List not found' });
}
list.items = list.items.filter(item => !item.completed);
list.updatedAt = Date.now();
await writeData(data);
res.json({ success: true });
} catch (error) {
console.error('Error deleting completed items:', error);
res.status(500).json({ error: 'Failed to delete completed items' });
}
});
});
// Delete a single item
app.delete('/api/items/:listId/:itemId', async (req, res) => {
await dbMutex.run(async () => {
try {
const { listId, itemId } = req.params;
const data = await readData();
const list = getList(data, listId);
if (!list) {
return res.status(404).json({ error: 'List not found' });
}
list.items = list.items.filter(item => String(item.id) !== itemId);
list.updatedAt = Date.now();
await writeData(data);
res.json({ success: true });
} catch (error) {
console.error('Error deleting item:', error);
res.status(500).json({ error: 'Failed to delete item' });
}
});
});
// API Root
app.get('/api', (req, res) => {
res.json({ message: 'Shopping List API is running' });
});
// SPA Fallback: Serve index.html for any unknown routes (non-API)
app.get('*', rateLimiter, (req, res) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Initialize and start server
async function startServer() {
await ensureDataDir();
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
});
}
startServer().catch(console.error);