-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
110 lines (95 loc) · 3.38 KB
/
Copy pathserver.js
File metadata and controls
110 lines (95 loc) · 3.38 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
import express from 'express';
import basicAuth from 'express-basic-auth';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = process.env.PORT || 3000;
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const DATA_FILE = path.join(DATA_DIR, 'tracker.json');
const USERNAME = process.env.TRACKER_USER || 'tracker';
const PASSWORD = process.env.TRACKER_PASSWORD;
// Ensure data directory exists
await fs.mkdir(DATA_DIR, { recursive: true });
// Trust the reverse proxy (nginx) so we get correct IPs in logs
app.set('trust proxy', 1);
// Basic auth at this layer is optional. When deployed behind nginx Basic Auth
// on a loopback-only port, the reverse proxy is the auth boundary. If
// TRACKER_PASSWORD is set, enable Express-level auth too.
if (PASSWORD) {
app.use(basicAuth({
users: { [USERNAME]: PASSWORD },
challenge: true,
realm: 'Debt Tracker',
}));
}
app.use(express.json({ limit: '512kb' }));
// Simple request log (no body — keeps password tries out of logs)
app.use((req, res, next) => {
const t = new Date().toISOString();
console.log(`${t} ${req.method} ${req.path}`);
next();
});
// === API ===
// Read tracker data
app.get('/api/data', async (req, res) => {
try {
const text = await fs.readFile(DATA_FILE, 'utf-8');
res.json({ data: JSON.parse(text) });
} catch (err) {
if (err.code === 'ENOENT') {
res.json({ data: null });
} else {
console.error('Read error:', err);
res.status(500).json({ error: 'Failed to read data' });
}
}
});
// Write tracker data (full replace; data is small)
app.post('/api/data', async (req, res) => {
try {
if (!req.body || typeof req.body !== 'object') {
return res.status(400).json({ error: 'Invalid body' });
}
// Atomic write: write to temp, then rename
const tmp = DATA_FILE + '.tmp';
await fs.writeFile(tmp, JSON.stringify(req.body, null, 2), 'utf-8');
await fs.rename(tmp, DATA_FILE);
res.json({ ok: true });
} catch (err) {
console.error('Write error:', err);
res.status(500).json({ error: 'Failed to write data' });
}
});
// Backup snapshot (for paranoia — call before destructive operations)
app.post('/api/backup', async (req, res) => {
try {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupFile = path.join(DATA_DIR, `tracker-${stamp}.bak.json`);
await fs.copyFile(DATA_FILE, backupFile);
res.json({ ok: true, file: path.basename(backupFile) });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Health check (no auth needed - mount before basicAuth would be cleaner but this is fine)
app.get('/api/health', (req, res) => {
res.json({ ok: true, time: new Date().toISOString() });
});
// === STATIC FRONTEND ===
// Serve the built Vite app from /dist
app.use(express.static(path.join(__dirname, 'dist')));
// SPA fallback: any non-API route returns index.html
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api/')) return next();
res.sendFile(path.join(__dirname, 'dist', 'index.html'), (err) => {
if (err) {
res.status(404).send('Frontend not built. Run: npm run build');
}
});
});
app.listen(PORT, () => {
console.log(`Debt tracker running on port ${PORT}`);
console.log(`Data file: ${DATA_FILE}`);
});