Skip to content

Commit b225132

Browse files
fix: enhance upload security with file validation and size limits
1 parent 98cfc42 commit b225132

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

dev-server/index.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ if (!fs.existsSync(distPath)) {
2323

2424
const app = express();
2525

26-
// Rate limit to 100 req/min per IP
26+
// Rate limit to 100 req/min per IP (dev-only implementation)
2727
const rateLimit = new Map();
2828
setInterval(() => rateLimit.clear(), 60000); // Clear every minute to prevent memory growth
2929
app.use((req, res, next) => {
@@ -81,6 +81,8 @@ app.post("/upload", function (req, res) {
8181
const form = formidable({
8282
multiples: false,
8383
keepExtensions: true,
84+
maxFileSize: 25 * 1024 * 1024, // 25MB limit
85+
maxFiles: 1,
8486
});
8587

8688
form.parse(req, (err, fields, files) => {
@@ -96,12 +98,24 @@ app.post("/upload", function (req, res) {
9698

9799
// Sanitize filename to prevent path traversal
98100
const newFileName = path.basename(uploadedFile.originalFilename);
101+
102+
// Validate file extension (whitelist for document scanner)
103+
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.pdf', '.bmp', '.tiff', '.tif'];
104+
const fileExt = path.extname(newFileName).toLowerCase();
105+
if (!allowedExtensions.includes(fileExt)) {
106+
return res.status(400).json({ success: false, message: "File type not allowed. Allowed types: jpg, jpeg, png, pdf, bmp, tiff" });
107+
}
108+
109+
// Sanitize filename to remove potentially dangerous characters
110+
const sanitizedName = newFileName.replace(/[^a-zA-Z0-9._-]/g, '_');
111+
99112
const fileSavePath = __dirname;
100-
const newFilePath = path.resolve(fileSavePath, newFileName);
113+
const newFilePath = path.resolve(fileSavePath, sanitizedName);
101114

102-
// Verify path is within allowed directory
103-
if (!newFilePath.startsWith(fileSavePath + path.sep)) {
104-
return res.status(400).json({ success: false, message: "Invalid filename" });
115+
// Verify path is within allowed directory (robust check using relative path)
116+
const relativePath = path.relative(fileSavePath, newFilePath);
117+
if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
118+
return res.status(400).json({ success: false, message: "Invalid filename - path traversal detected" });
105119
}
106120

107121
// Move the uploaded file to the desired directory

0 commit comments

Comments
 (0)