forked from DumbWareio/DumbDrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
416 lines (354 loc) · 12.8 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
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
const express = require('express');
const multer = require('multer');
const path = require('path');
const cors = require('cors');
const fs = require('fs');
const crypto = require('crypto');
const cookieParser = require('cookie-parser');
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
const uploadDir = './uploads'; // Local development
const maxFileSize = parseInt(process.env.MAX_FILE_SIZE || '1024') * 1024 * 1024; // Convert MB to bytes
const APPRISE_URL = process.env.APPRISE_URL;
const APPRISE_MESSAGE = process.env.APPRISE_MESSAGE || 'New file uploaded - {filename} ({size}), Storage used: {storage}';
const siteTitle = process.env.DUMBDROP_TITLE || 'DumbDrop';
const APPRISE_SIZE_UNIT = process.env.APPRISE_SIZE_UNIT;
// Brute force protection setup
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);
return attempts;
}
// Cleanup old lockouts every minute
setInterval(() => {
const now = Date.now();
for (const [ip, attempts] of loginAttempts.entries()) {
if (now - attempts.lastAttempt >= LOCKOUT_TIME) {
loginAttempts.delete(ip);
}
}
}, 60000);
// Validate and set PIN
const validatePin = (pin) => {
if (!pin) return null;
const cleanPin = pin.replace(/\D/g, ''); // Remove non-digits
return cleanPin.length >= 4 && cleanPin.length <= 10 ? cleanPin : null;
};
const PIN = validatePin(process.env.DUMBDROP_PIN);
// Logging helper
const log = {
info: (msg) => console.log(`[INFO] ${new Date().toISOString()} - ${msg}`),
error: (msg) => console.error(`[ERROR] ${new Date().toISOString()} - ${msg}`),
success: (msg) => console.log(`[SUCCESS] ${new Date().toISOString()} - ${msg}`)
};
// Helper function to ensure directory exists
async function ensureDirectoryExists(filePath) {
const dir = path.dirname(filePath);
try {
await fs.promises.mkdir(dir, { recursive: true });
} catch (err) {
log.error(`Failed to create directory ${dir}: ${err.message}`);
throw err;
}
}
// Ensure upload directory exists
try {
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
log.info(`Created upload directory: ${uploadDir}`);
}
fs.accessSync(uploadDir, fs.constants.W_OK);
log.success(`Upload directory is writable: ${uploadDir}`);
log.info(`Maximum file size set to: ${maxFileSize / (1024 * 1024)}MB`);
if (PIN) {
log.info('PIN protection enabled');
}
} catch (err) {
log.error(`Directory error: ${err.message}`);
log.error(`Failed to access or create upload directory: ${uploadDir}`);
log.error('Please check directory permissions and mounting');
process.exit(1);
}
// Middleware
app.use(cors());
app.use(cookieParser());
app.use(express.json());
// Helper function for constant-time string comparison
function safeCompare(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') {
return false;
}
// Use Node's built-in constant-time comparison
return crypto.timingSafeEqual(
Buffer.from(a.padEnd(32)),
Buffer.from(b.padEnd(32))
);
}
// Pin verification endpoint
app.post('/api/verify-pin', (req, res) => {
const { pin } = req.body;
const ip = req.ip;
// If no PIN is set in env, always return success
if (!PIN) {
return res.json({ success: true });
}
// Check for lockout
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.`
});
}
// Verify the PIN using constant-time comparison
if (safeCompare(pin, PIN)) {
// Reset attempts on successful login
resetAttempts(ip);
// Set secure cookie
res.cookie('DUMBDROP_PIN', pin, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/'
});
res.json({ success: true });
} else {
// Record failed attempt
const attempts = recordAttempt(ip);
const attemptsLeft = MAX_ATTEMPTS - attempts.count;
res.status(401).json({
success: false,
error: attemptsLeft > 0 ?
`Invalid PIN. ${attemptsLeft} attempts remaining.` :
'Too many attempts. Account locked for 15 minutes.'
});
}
});
// Check if PIN is required
app.get('/api/pin-required', (req, res) => {
res.json({
required: !!PIN,
length: PIN ? PIN.length : 0
});
});
// Pin protection middleware
const requirePin = (req, res, next) => {
if (!PIN) {
return next();
}
const providedPin = req.headers['x-pin'] || req.cookies.DUMBDROP_PIN;
if (!safeCompare(providedPin, PIN)) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
};
// Move the root and login routes before static file serving
app.get('/', (req, res) => {
if (PIN && !safeCompare(req.cookies.DUMBDROP_PIN, PIN)) {
return res.redirect('/login.html');
}
// Read the file and replace the title
let html = fs.readFileSync(path.join(__dirname, 'public', 'index.html'), 'utf8');
html = html.replace(/{{SITE_TITLE}}/g, siteTitle); // Use global replace
res.send(html);
});
app.get('/login.html', (req, res) => {
let html = fs.readFileSync(path.join(__dirname, 'public', 'login.html'), 'utf8');
html = html.replace(/{{SITE_TITLE}}/g, siteTitle); // Use global replace
res.send(html);
});
// Move static file serving after our dynamic routes
app.use(express.static('public'));
// PIN protection middleware should be before the routes that need protection
app.use('/upload', requirePin);
// Store ongoing uploads
const uploads = new Map();
// Routes
app.post('/upload/init', async (req, res) => {
const { filename, fileSize } = req.body;
const safeFilename = path.normalize(filename).replace(/^(\.\.(\/|\\|$))+/, '')
// Check file size limit
if (fileSize > maxFileSize) {
log.error(`File size ${fileSize} bytes exceeds limit of ${maxFileSize} bytes`);
return res.status(413).json({
error: 'File too large',
limit: maxFileSize,
limitInMB: maxFileSize / (1024 * 1024)
});
}
const uploadId = Date.now().toString();
const filePath = path.join(uploadDir, safeFilename);
try {
await ensureDirectoryExists(filePath);
uploads.set(uploadId, {
safeFilename,
filePath,
fileSize,
bytesReceived: 0,
writeStream: fs.createWriteStream(filePath)
});
log.info(`Initialized upload for ${safeFilename} (${fileSize} bytes)`);
res.json({ uploadId });
} catch (err) {
log.error(`Failed to initialize upload: ${err.message}`);
res.status(500).json({ error: 'Failed to initialize upload' });
}
});
app.post('/upload/chunk/:uploadId', express.raw({
limit: '10mb',
type: 'application/octet-stream'
}), async (req, res) => {
const { uploadId } = req.params;
const upload = uploads.get(uploadId);
const chunkSize = req.body.length;
if (!upload) {
return res.status(404).json({ error: 'Upload not found' });
}
try {
upload.writeStream.write(Buffer.from(req.body));
upload.bytesReceived += chunkSize;
const progress = Math.round((upload.bytesReceived / upload.fileSize) * 100);
log.info(`Received chunk for ${upload.safeFilename}: ${progress}%`);
res.json({
bytesReceived: upload.bytesReceived,
progress
});
// Check if upload is complete
if (upload.bytesReceived >= upload.fileSize) {
upload.writeStream.end();
uploads.delete(uploadId);
log.success(`Upload completed: ${upload.safeFilename}`);
// Update notification call to use safeFilename
await sendNotification(upload.safeFilename, upload.fileSize);
}
} catch (err) {
log.error(`Chunk upload failed: ${err.message}`);
res.status(500).json({ error: 'Failed to process chunk' });
}
});
app.post('/upload/cancel/:uploadId', (req, res) => {
const { uploadId } = req.params;
const upload = uploads.get(uploadId);
if (upload) {
upload.writeStream.end();
fs.unlink(upload.filePath, (err) => {
if (err) log.error(`Failed to delete incomplete upload: ${err.message}`);
});
uploads.delete(uploadId);
log.info(`Upload cancelled: ${upload.safeFilename}`);
}
res.json({ message: 'Upload cancelled' });
});
// Error handling middleware
app.use((err, req, res, next) => {
log.error(`Unhandled error: ${err.message}`);
res.status(500).json({ message: 'Internal server error', error: err.message });
});
// Start server
app.listen(port, () => {
log.info(`Server running at http://localhost:${port}`);
log.info(`Upload directory: ${uploadDir}`);
// Log custom title if set
if (process.env.DUMBDROP_TITLE) {
log.info(`Custom title set to: ${siteTitle}`);
}
// Add Apprise configuration logging
if (APPRISE_URL) {
log.info('Apprise notifications enabled');
} else {
log.info('Apprise notifications disabled - no URL configured');
}
// List directory contents
try {
const files = fs.readdirSync(uploadDir);
log.info(`Current directory contents (${files.length} files):`);
files.forEach(file => {
log.info(`- ${file}`);
});
} catch (err) {
log.error(`Failed to list directory contents: ${err.message}`);
}
});
// Remove async from formatFileSize function
function formatFileSize(bytes) {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = bytes;
let unitIndex = 0;
// If a specific unit is requested
if (APPRISE_SIZE_UNIT) {
const requestedUnit = APPRISE_SIZE_UNIT.toUpperCase();
const unitIndex = units.indexOf(requestedUnit);
if (unitIndex !== -1) {
size = bytes / Math.pow(1024, unitIndex);
return size.toFixed(2) + requestedUnit;
}
}
// Auto format to nearest unit
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
// Round to 2 decimal places
return size.toFixed(2) + units[unitIndex];
}
// Add this helper function
function calculateDirectorySize(directoryPath) {
let totalSize = 0;
const files = fs.readdirSync(directoryPath);
files.forEach(file => {
const filePath = path.join(directoryPath, file);
const stats = fs.statSync(filePath);
if (stats.isFile()) {
totalSize += stats.size;
}
});
return totalSize;
}
// Modify the sendNotification function to safely escape the message
async function sendNotification(filename, fileSize) {
if (!APPRISE_URL) return;
try {
const formattedSize = formatFileSize(fileSize);
const totalStorage = formatFileSize(calculateDirectorySize(uploadDir));
// Sanitize the message components
const sanitizedFilename = JSON.stringify(filename).slice(1, -1); // Escape special characters
const message = APPRISE_MESSAGE
.replace('{filename}', sanitizedFilename)
.replace('{size}', formattedSize)
.replace('{storage}', totalStorage);
// Use array syntax to avoid shell interpretation
await execAsync(['apprise', APPRISE_URL, '-b', message], {
shell: false
});
log.info(`Notification sent for: ${sanitizedFilename} (${formattedSize}, Total storage: ${totalStorage})`);
} catch (err) {
log.error(`Failed to send notification: ${err.message}`);
}
}