@@ -23,7 +23,7 @@ if (!fs.existsSync(distPath)) {
2323
2424const app = express ( ) ;
2525
26- // Rate limit to 100 req/min per IP
26+ // Rate limit to 100 req/min per IP (dev-only implementation)
2727const rateLimit = new Map ( ) ;
2828setInterval ( ( ) => rateLimit . clear ( ) , 60000 ) ; // Clear every minute to prevent memory growth
2929app . 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 - z A - Z 0 - 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