Spaces:
Running

File size: 9,893 Bytes
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d75
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d75
ef747c9
7a35d75
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d75
ef747c9
7a35d75
 
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d75
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d75
 
 
ef747c9
 
7a35d75
ef747c9
 
 
 
 
 
 
 
 
 
 
7a35d75
ef747c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @fileoverview Security middleware for file upload validation and path sanitization.
 * Implements comprehensive security measures to prevent malicious uploads and path traversal attacks.
 * @module middleware/security
 */

import rateLimit from 'express-rate-limit';
import fs from 'fs-extra';
import path from 'path';

/**
 * Magic bytes signatures for supported archive formats.
 * These are the first bytes of valid archive files.
 * @constant {Object}
 */
const MAGIC_BYTES = {
  // ZIP magic bytes: PK\x03\x04 (also PK\x05\x06 for empty ZIP, PK\x07\x08 for spanned)
  zip: [
    [0x50, 0x4b, 0x03, 0x04], // Standard ZIP
    [0x50, 0x4b, 0x05, 0x06], // Empty ZIP
    [0x50, 0x4b, 0x07, 0x08], // Spanned ZIP
  ],
  // RAR magic bytes - support both RAR4 and RAR5
  // RAR4: Rar!\x1a\x07\x00
  // RAR5: Rar!\x1a\x07\x01\x00
  // Common prefix: Rar!\x1a\x07 (6 bytes)
  rar: [
    [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07], // Common RAR signature (works for both RAR4 and RAR5)
  ],
};

/**
 * Allowed file extensions for upload.
 * @constant {Set<string>}
 */
const ARCHIVE_EXTENSIONS = new Set(['.zip', '.rar']);

/**
 * Maximum filename length to prevent filesystem issues.
 * @constant {number}
 */
const MAX_FILENAME_LENGTH = 255;

/**
 * Regex pattern for characters to remove from filenames.
 * Allows alphanumeric, dots, hyphens, underscores, and spaces.
 * @constant {RegExp}
 */
const UNSAFE_FILENAME_CHARS = /[^a-zA-Z0-9.\-_\s]/g;

/**
 * Creates a rate limiter middleware for upload endpoint.
 * Limits requests based on IP address to prevent abuse.
 * 
 * @returns {Function} Express rate limit middleware
 */
export const createUploadRateLimiter = () => {
  const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW) || 3600000; // 1 hour
  const max = parseInt(process.env.RATE_LIMIT_MAX) || 10;

  return rateLimit({
    windowMs,
    max,
    message: {
      error: true,
      message: 'Too many upload requests. Please try again later.',
      code: 'RATE_LIMIT_EXCEEDED',
    },
    standardHeaders: true,
    legacyHeaders: false,
    // Use IP address for rate limiting
    keyGenerator: (req) => req.ip,
  });
};

/**
 * Validates file extension against allowed list.
 * 
 * @param {string} filename - The filename to validate
 * @returns {boolean} True if extension is allowed
 */
export const isArchiveExtension = (filename) => {
  const ext = path.extname(filename).toLowerCase();
  return ARCHIVE_EXTENSIONS.has(ext);
};

/**
 * Validates file magic bytes to ensure file content matches extension.
 * SECURITY: This prevents malicious files disguised with wrong extensions.
 * 
 * @async
 * @param {string} filePath - Path to the file to validate
 * @param {string} expectedType - Expected file type ('zip' or 'rar')
 * @returns {Promise<boolean>} True if magic bytes match expected type
 */
export const validateMagicBytes = async (filePath, expectedType) => {
  try {
    const expectedSignatures = MAGIC_BYTES[expectedType];
    if (!expectedSignatures || expectedSignatures.length === 0) {
      return false;
    }

    // Find the maximum signature length we need to read
    const maxLength = Math.max(...expectedSignatures.map(sig => sig.length));

    // Read the first bytes of the file
    const fileBuffer = await fs.readFile(filePath);
    const buffer = fileBuffer.slice(0, maxLength);

    // Debug logging
    console.log(`Validating ${expectedType} file, first ${maxLength} bytes:`, 
      Array.from(buffer).map(b => '0x' + b.toString(16).padStart(2, '0')).join(', ')
    );

    // Check against each possible signature
    for (const expectedBytes of expectedSignatures) {
      let matches = true;
      for (let i = 0; i < expectedBytes.length; i++) {
        if (buffer[i] !== expectedBytes[i]) {
          matches = false;
          break;
        }
      }
      if (matches) {
        console.log(`Magic bytes match for ${expectedType}`);
        return true;
      }
    }

    console.log(`No magic bytes match found for ${expectedType}`);
    return false;
  } catch (error) {
    console.error('Magic bytes validation error:', error.message);
    return false;
  }
};

/**
 * Sanitizes a filename by removing dangerous characters and limiting length.
 * SECURITY: Prevents directory traversal and filesystem exploits through filenames.
 * 
 * @param {string} filename - The filename to sanitize
 * @returns {string} Sanitized filename
 */
export const sanitizeFilename = (filename) => {
  if (!filename || typeof filename !== 'string') {
    return 'unnamed_file';
  }

  // Remove path components
  let sanitized = path.basename(filename);

  // Remove unsafe characters
  sanitized = sanitized.replace(UNSAFE_FILENAME_CHARS, '_');

  // Remove leading/trailing dots and spaces
  sanitized = sanitized.replace(/^[\s.]+|[\s.]+$/g, '');

  // Limit length
  if (sanitized.length > MAX_FILENAME_LENGTH) {
    const ext = path.extname(sanitized);
    const name = path.basename(sanitized, ext);
    sanitized = name.substring(0, MAX_FILENAME_LENGTH - ext.length) + ext;
  }

  // Fallback if empty after sanitization
  if (!sanitized) {
    return 'unnamed_file';
  }

  return sanitized;
};

/**
 * Validates a path to prevent directory traversal attacks.
 * SECURITY: Rejects paths containing ".." or absolute path indicators.
 * 
 * @param {string} requestedPath - The path to validate
 * @returns {{valid: boolean, error?: string}} Validation result
 */
export const validatePath = (requestedPath) => {
  if (!requestedPath || typeof requestedPath !== 'string') {
    return { valid: false, error: 'Path is required' };
  }

  // SECURITY: Check for path traversal attempts
  if (requestedPath.includes('..')) {
    return { valid: false, error: 'Path traversal detected' };
  }

  // SECURITY: Reject absolute paths
  if (path.isAbsolute(requestedPath)) {
    return { valid: false, error: 'Absolute paths not allowed' };
  }

  // SECURITY: Check for null bytes (can be used to bypass some checks)
  if (requestedPath.includes('\0')) {
    return { valid: false, error: 'Invalid path characters' };
  }

  return { valid: true };
};

/**
 * Validates a session ID format.
 * SECURITY: Only allows valid UUID v4 format to prevent injection.
 * 
 * @param {string} sessionId - The session ID to validate
 * @returns {boolean} True if session ID is valid UUID v4
 */
export const isValidSessionId = (sessionId) => {
  if (!sessionId || typeof sessionId !== 'string') {
    return false;
  }

  // UUID v4 pattern for legacy sessions and 8-digit pattern for share codes
  const uuidV4Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  const accessCodePattern = /^\d{8}$/;
  return uuidV4Pattern.test(sessionId) || accessCodePattern.test(sessionId);
};

/**
 * Middleware to validate session ID parameter.
 * 
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next function
 */
export const validateSessionIdMiddleware = (req, res, next) => {
  const { sessionId } = req.params;

  if (!isValidSessionId(sessionId)) {
    return res.status(400).json({
      error: true,
      message: 'Invalid session ID or 8-digit access code format',
      code: 'INVALID_SESSION_ID',
    });
  }

  next();
};

/**
 * Middleware to validate file path query parameter.
 * 
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next function
 */
export const validatePathMiddleware = (req, res, next) => {
  const filePath = req.query.path;

  if (!filePath) {
    return res.status(400).json({
      error: true,
      message: 'File path is required',
      code: 'MISSING_PATH',
    });
  }

  const validation = validatePath(filePath);
  if (!validation.valid) {
    return res.status(400).json({
      error: true,
      message: validation.error,
      code: 'INVALID_PATH',
    });
  }

  next();
};

/**
 * Middleware to validate uploaded files.
 * Checks file existence, extension, and magic bytes.
 * Supports both single and multiple file uploads.
 * 
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next function
 */
export const validateUploadedFile = async (req, res, next) => {
  try {
    // Support both single file (req.file) and multiple files (req.files)
    const files = req.files || (req.file ? [req.file] : []);
    
    if (files.length === 0) {
      return res.status(400).json({
        error: true,
        message: 'No file uploaded',
        code: 'NO_FILE',
      });
    }

    // Validate each file
    for (const file of files) {
      const { originalname, path: filePath } = file;

      // Only archives need strict magic-byte validation before extraction.
      if (!isArchiveExtension(originalname)) {
        continue;
      }

      // Determine expected archive type from extension
      const ext = path.extname(originalname).toLowerCase().slice(1);

      // Validate magic bytes
      const isValidMagic = await validateMagicBytes(filePath, ext);
      if (!isValidMagic) {
        // Clean up all uploaded files
        for (const f of files) {
          await fs.remove(f.path).catch(() => {});
        }
        return res.status(400).json({
          error: true,
          message: `Archive content does not match file extension: ${originalname}`,
          code: 'INVALID_MAGIC_BYTES',
        });
      }
    }

    next();
  } catch (error) {
    console.error('File validation error:', error);
    // Clean up on error
    const files = req.files || (req.file ? [req.file] : []);
    for (const file of files) {
      await fs.remove(file.path).catch(() => {});
    }
    return res.status(500).json({
      error: true,
      message: 'File validation failed',
      code: 'VALIDATION_ERROR',
    });
  }
};