-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
241 lines (212 loc) · 7.73 KB
/
server.js
File metadata and controls
241 lines (212 loc) · 7.73 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
const express = require('express');
const fs = require('fs');
const path = require('path');
const session = require('express-session');
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 80;
const DATA_FILE = 'data/data.json';
const DATA_FILE_EXAMPLE = 'data/data.json.example';
// Ensure data directory exists and initialize with example if needed
function initializeDataFile() {
const dataDir = path.dirname(DATA_FILE);
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
if (!fs.existsSync(DATA_FILE)) {
if (fs.existsSync(DATA_FILE_EXAMPLE)) {
fs.copyFileSync(DATA_FILE_EXAMPLE, DATA_FILE);
console.log('✓ Initialized data.json from example');
} else {
// Fallback: create minimal structure
const defaultData = {
globalSettings: { printerPower: 100, electricityPrice: 0.12, currencySymbol: '🦁' },
jobs: [],
nextId: 1
};
fs.writeFileSync(DATA_FILE, JSON.stringify(defaultData, null, 2));
console.log('✓ Created default data.json');
}
}
}
initializeDataFile();
// Default credentials (use environment variables for production)
const AUTH_USERNAME = process.env.AUTH_USERNAME || 'admin';
const AUTH_PASSWORD = process.env.AUTH_PASSWORD || 'admin';
// Safety checks
if (!AUTH_PASSWORD || AUTH_PASSWORD.trim() === '') {
console.error('\n⛔ SECURITY ERROR: Password cannot be empty');
console.error('Set AUTH_PASSWORD environment variable with a non-empty value');
process.exit(1);
}
if ((AUTH_USERNAME === 'admin' && AUTH_PASSWORD === 'admin') && !process.env.ALLOW_DEFAULT_CREDENTIALS) {
console.error('\n⛔ SECURITY ERROR: Using default credentials (admin/admin)');
console.error('Set custom AUTH_USERNAME and AUTH_PASSWORD environment variables');
console.error('Example: docker-compose up');
console.error('Or set ALLOW_DEFAULT_CREDENTIALS=true to override (NOT recommended)\n');
process.exit(1);
}
// Generate secure session secret if not provided or is placeholder
let SESSION_SECRET = process.env.SESSION_SECRET;
if (!SESSION_SECRET || SESSION_SECRET === 'change-this-secret-key' || SESSION_SECRET === 'change-this-in-production') {
SESSION_SECRET = crypto.randomBytes(32).toString('hex');
console.log('Generated random SESSION_SECRET for this session');
}
app.use(express.json());
app.use(session({
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: false, maxAge: 24 * 60 * 60 * 1000 } // 24 hours
}));
// Authentication middleware
function requireAuth(req, res, next) {
if (req.session.authenticated) {
next();
} else {
res.redirect('/login.html');
}
}
// Login endpoint
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
if (username === AUTH_USERNAME && password === AUTH_PASSWORD) {
req.session.authenticated = true;
res.sendStatus(200);
} else {
res.sendStatus(401);
}
});
// Logout endpoint
app.post('/api/logout', (req, res) => {
req.session.destroy();
res.sendStatus(200);
});
// Protected data endpoints
app.get('/api/data', requireAuth, (req, res) => {
try {
if (fs.existsSync(DATA_FILE)) {
const data = fs.readFileSync(DATA_FILE, 'utf8');
res.json(JSON.parse(data));
} else {
// Default data
const defaultData = {
globalSettings: { printerPower: 100, electricityPrice: 0.12, currencySymbol: '🦁' },
jobs: [],
nextId: 1
};
res.json(defaultData);
}
} catch (err) {
console.error('Error loading data:', err);
res.status(500).send('Error loading data');
}
});
app.post('/api/data', requireAuth, (req, res) => {
try {
fs.writeFileSync(DATA_FILE, JSON.stringify(req.body, null, 2));
res.sendStatus(200);
} catch (err) {
console.error('Error saving data:', err);
res.status(500).send('Error saving data');
}
});
// Import endpoint with backup
app.post('/api/import', requireAuth, (req, res) => {
try {
// Check if data is different before backing up
let shouldBackup = true;
if (fs.existsSync(DATA_FILE)) {
const currentData = fs.readFileSync(DATA_FILE, 'utf8');
const newData = JSON.stringify(req.body, null, 2);
if (currentData === newData) {
shouldBackup = false;
console.log('⏭️ Import skipped backup - data unchanged');
}
}
// Backup existing data before import only if different
if (shouldBackup && fs.existsSync(DATA_FILE)) {
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}T${String(now.getHours()).padStart(2,'0')}-${String(now.getMinutes()).padStart(2,'0')}`;
const backupFile = `${DATA_FILE}.import-backup-${timestamp}`;
fs.copyFileSync(DATA_FILE, backupFile);
console.log(`✓ Import backup created: ${backupFile}`);
// Keep only last 10 import backups
const backupFiles = fs.readdirSync(path.dirname(DATA_FILE))
.filter(f => f.startsWith('data.json.import-backup-'))
.map(f => path.join(path.dirname(DATA_FILE), f))
.sort()
.reverse();
if (backupFiles.length > 10) {
backupFiles.slice(10).forEach(f => {
fs.unlinkSync(f);
console.log(`✓ Removed old import backup: ${path.basename(f)}`);
});
}
}
fs.writeFileSync(DATA_FILE, JSON.stringify(req.body, null, 2));
res.sendStatus(200);
} catch (err) {
console.error('Error importing data:', err);
res.status(500).send('Error importing data');
}
});
// Serve login page without authentication
app.get('/login.html', (req, res) => {
res.sendFile(path.join(__dirname, 'login.html'));
});
// Get last backup timestamp
app.get('/api/last-backup', requireAuth, (req, res) => {
try {
const backupFiles = fs.readdirSync(path.dirname(DATA_FILE))
.filter(f => f.startsWith('data.json.auto-backup-'))
.map(f => {
const stats = fs.statSync(path.join(path.dirname(DATA_FILE), f));
return { name: f, time: stats.mtime };
})
.sort((a, b) => b.time - a.time);
if (backupFiles.length > 0) {
res.json({ lastBackup: backupFiles[0].time });
} else {
res.json({ lastBackup: null });
}
} catch (err) {
console.error('Error getting last backup:', err);
res.json({ lastBackup: null });
}
});
// Protect all other static files
app.use(requireAuth, express.static('.'));
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// Automatic periodic backup every 6 hours
function createAutoBackup() {
try {
if (fs.existsSync(DATA_FILE)) {
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}T${String(now.getHours()).padStart(2,'0')}-${String(now.getMinutes()).padStart(2,'0')}`;
const backupFile = `${DATA_FILE}.auto-backup-${timestamp}`;
fs.copyFileSync(DATA_FILE, backupFile);
console.log(`✓ Auto backup created: ${backupFile}`);
// Keep only last 5 auto backups
const backupFiles = fs.readdirSync(path.dirname(DATA_FILE))
.filter(f => f.startsWith('data.json.auto-backup-'))
.map(f => path.join(path.dirname(DATA_FILE), f))
.sort()
.reverse();
if (backupFiles.length > 5) {
backupFiles.slice(5).forEach(f => {
fs.unlinkSync(f);
console.log(`✓ Removed old auto backup: ${path.basename(f)}`);
});
}
}
} catch (err) {
console.error('Error creating auto backup:', err);
}
}
// Create initial backup on startup
createAutoBackup();
// Schedule periodic backups every 6 hours (21600000 ms)
setInterval(createAutoBackup, 6 * 60 * 60 * 1000);