-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
247 lines (207 loc) · 7.01 KB
/
server.js
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
require('dotenv').config();
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || 3000;
// Environment variables
const PIN = process.env.DUMBDO_PIN;
const MIN_PIN_LENGTH = 4;
const MAX_PIN_LENGTH = 10;
// Middleware
app.use(express.json());
app.use(cookieParser());
// Brute force protection
const loginAttempts = new Map(); // Stores IP addresses and their attempt counts
const MAX_ATTEMPTS = 5; // Maximum allowed attempts
const LOCKOUT_TIME = 15 * 60 * 1000; // 15 minutes in milliseconds
// Reset attempts for an IP
function resetAttempts(ip) {
loginAttempts.delete(ip);
}
// Check if an IP is locked out
function isLockedOut(ip) {
const attempts = loginAttempts.get(ip);
if (!attempts) return false;
if (attempts.count >= MAX_ATTEMPTS) {
const timeElapsed = Date.now() - attempts.lastAttempt;
if (timeElapsed < LOCKOUT_TIME) {
return true;
}
resetAttempts(ip);
}
return false;
}
// Record an attempt for an IP
function recordAttempt(ip) {
const attempts = loginAttempts.get(ip) || { count: 0, lastAttempt: 0 };
attempts.count += 1;
attempts.lastAttempt = Date.now();
loginAttempts.set(ip, attempts);
}
// Cleanup old lockouts periodically
setInterval(() => {
const now = Date.now();
for (const [ip, attempts] of loginAttempts.entries()) {
if (now - attempts.lastAttempt >= LOCKOUT_TIME) {
loginAttempts.delete(ip);
}
}
}, 60000); // Clean up every minute
// Constant-time string comparison
function secureCompare(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') {
return false;
}
return crypto.timingSafeEqual(
Buffer.from(a.padEnd(MAX_PIN_LENGTH, '0')),
Buffer.from(b.padEnd(MAX_PIN_LENGTH, '0'))
);
}
// Public PIN Routes - these don't require authentication
app.get('/api/pin-required', (req, res) => {
const lockoutTime = isLockedOut(req.ip);
const attempts = loginAttempts.get(req.ip);
const attemptsLeft = attempts ? MAX_ATTEMPTS - attempts.count : MAX_ATTEMPTS;
res.json({
required: !!PIN,
length: PIN ? PIN.length : MIN_PIN_LENGTH,
locked: isLockedOut(req.ip),
attemptsLeft: Math.max(0, attemptsLeft),
lockoutMinutes: lockoutTime ? Math.ceil((LOCKOUT_TIME - (Date.now() - attempts.lastAttempt)) / 1000 / 60) : 0
});
});
app.post('/api/verify-pin', (req, res) => {
const { pin } = req.body;
const ip = req.ip;
// Check if IP is locked out
if (isLockedOut(ip)) {
const attempts = loginAttempts.get(ip);
const timeLeft = Math.ceil((LOCKOUT_TIME - (Date.now() - attempts.lastAttempt)) / 1000 / 60);
return res.status(429).json({
error: `Too many attempts. Please try again in ${timeLeft} minutes.`,
locked: true,
lockoutMinutes: timeLeft
});
}
// Validate PIN length
if (PIN && (pin.length < MIN_PIN_LENGTH || pin.length > MAX_PIN_LENGTH)) {
recordAttempt(ip);
const attempts = loginAttempts.get(ip);
return res.status(401).json({
valid: false,
error: `PIN must be between ${MIN_PIN_LENGTH} and ${MAX_PIN_LENGTH} digits`,
attemptsLeft: MAX_ATTEMPTS - attempts.count
});
}
// Add artificial delay to further prevent timing attacks
const delay = crypto.randomInt(50, 150);
setTimeout(() => {
if (!PIN || secureCompare(pin, PIN)) {
// Reset attempts on successful login
resetAttempts(ip);
// Set secure cookie
res.cookie('DUMBDO_PIN', pin, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
});
res.json({ valid: true });
} else {
// Record failed attempt
recordAttempt(ip);
const attempts = loginAttempts.get(ip);
const attemptsLeft = MAX_ATTEMPTS - attempts.count;
res.status(401).json({
valid: false,
error: `Invalid PIN. ${attemptsLeft} attempts remaining before lockout.`,
attemptsLeft
});
}
}, delay);
});
// Serve static files that don't need PIN protection
app.get('/login.js', (req, res) => {
res.sendFile(path.join(__dirname, 'login.js'));
});
app.get('/styles.css', (req, res) => {
res.sendFile(path.join(__dirname, 'styles.css'));
});
app.get('/favicon.svg', (req, res) => {
res.sendFile(path.join(__dirname, 'favicon.svg'));
});
// PIN validation helper
function isValidPin(providedPin) {
return !PIN || (providedPin && secureCompare(providedPin, PIN));
}
// PIN validation middleware - everything after this requires PIN
app.use((req, res, next) => {
const providedPin = req.cookies.DUMBDO_PIN || req.headers['x-pin'];
if (isValidPin(providedPin)) {
return next();
}
if (req.xhr || req.path.startsWith('/api/')) {
return res.status(401).json({ error: 'Invalid PIN' });
}
if (req.path !== '/login') {
return res.redirect('/login');
}
next();
});
// Protected routes below
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/login', (req, res) => {
const providedPin = req.cookies.DUMBDO_PIN || req.headers['x-pin'];
if (isValidPin(providedPin)) {
res.redirect('/');
} else {
res.sendFile(path.join(__dirname, 'login.html'));
}
});
// Protect all other static files
app.use(express.static('.'));
// Data directory and file path
const DATA_DIR = path.join(__dirname, 'data');
const DATA_FILE = path.join(DATA_DIR, 'todos.json');
// Ensure the data directory and file exist
async function initDataFile() {
try {
await fs.access(DATA_DIR);
} catch {
await fs.mkdir(DATA_DIR);
}
try {
await fs.access(DATA_FILE);
} catch {
await fs.writeFile(DATA_FILE, JSON.stringify({}));
}
console.log('Todo list stored at:', DATA_FILE);
}
// Protected API routes
app.get('/api/todos', async (req, res) => {
try {
const data = await fs.readFile(DATA_FILE, 'utf8');
res.json(JSON.parse(data));
} catch (error) {
res.status(500).json({ error: 'Failed to read todos' });
}
});
app.post('/api/todos', async (req, res) => {
try {
await fs.writeFile(DATA_FILE, JSON.stringify(req.body, null, 2));
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to save todos' });
}
});
// Initialize and start server
initDataFile().then(() => {
app.listen(port, () => {
console.log(`DumbDo server running at http://localhost:${port}`);
console.log('PIN protection:', PIN ? 'enabled' : 'disabled');
});
});