Spaces:
Running

File size: 10,770 Bytes
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/**
 * @fileoverview Archive extraction service for ZIP and RAR files.
 * Handles recursive extraction with security measures including zip bomb protection.
 * @module services/extractionService
 */

import AdmZip from 'adm-zip';
import { createExtractorFromFile } from 'node-unrar-js';
import fs from 'fs-extra';
import path from 'path';
import { sanitizeFilename, validatePath } from '../middleware/security.js';

/**
 * Maximum size for individual extracted files (zip bomb protection).
 * @constant {number}
 */
const MAX_EXTRACTED_FILE_SIZE = parseInt(process.env.MAX_EXTRACTED_FILE_SIZE) || 52428800; // 50MB

/**
 * Archive extensions that should be recursively extracted.
 * @constant {Set<string>}
 */
const NESTED_ARCHIVE_EXTENSIONS = new Set(['.zip', '.rar']);

/**
 * Extracts an archive file to a destination directory.
 * Automatically detects archive type and handles nested archives.
 * 
 * @async
 * @param {string} archivePath - Path to the archive file
 * @param {string} destPath - Destination directory for extraction
 * @param {Object} options - Extraction options
 * @param {string} [options.password] - Password for encrypted archives
 * @returns {Promise<{success: boolean, error?: string, code?: string}>} Extraction result
 */
export const extractArchive = async (archivePath, destPath, options = {}) => {
  const ext = path.extname(archivePath).toLowerCase();
  const { password } = options;

  try {
    // Ensure destination directory exists with restricted permissions
    await fs.ensureDir(destPath, { mode: 0o755 });

    if (ext === '.zip') {
      return await extractZip(archivePath, destPath, password);
    } else if (ext === '.rar') {
      return await extractRar(archivePath, destPath, password);
    } else {
      return {
        success: false,
        error: 'Unsupported archive format',
        code: 'UNSUPPORTED_FORMAT',
      };
    }
  } catch (error) {
    console.error('Extraction error:', error);
    return {
      success: false,
      error: error.message || 'Extraction failed',
      code: 'EXTRACTION_FAILED',
    };
  }
};

/**
 * Extracts a ZIP archive.
 * Uses adm-zip library with security validations.
 * 
 * @async
 * @param {string} zipPath - Path to the ZIP file
 * @param {string} destPath - Destination directory
 * @param {string} [password] - Password for encrypted archives
 * @returns {Promise<{success: boolean, error?: string, code?: string}>}
 */
const extractZip = async (zipPath, destPath, password = null) => {
  try {
    const zip = new AdmZip(zipPath);
    
    // Check if archive is encrypted and we have a password
    const entries = zip.getEntries();
    const hasEncryptedEntries = entries.some(entry => entry.header.encripted);
    
    if (hasEncryptedEntries && !password) {
      return {
        success: false,
        error: 'Archive is password protected. Please provide a password.',
        code: 'PASSWORD_PROTECTED',
      };
    }

    for (const entry of entries) {
      // Skip directories, they'll be created with files
      if (entry.isDirectory) {
        continue;
      }

      // SECURITY: Validate and sanitize entry path
      const entryPath = entry.entryName;
      const pathValidation = validatePath(entryPath);
      
      if (!pathValidation.valid) {
        console.warn(`Skipping unsafe entry: ${entryPath}`);
        continue;
      }

      // SECURITY: Check for zip bomb (decompression ratio attack)
      if (entry.header.size > MAX_EXTRACTED_FILE_SIZE) {
        console.warn(`Skipping oversized entry: ${entryPath} (${entry.header.size} bytes)`);
        continue;
      }

      // Sanitize each path component
      const pathParts = entryPath.split('/').filter(Boolean);
      const sanitizedParts = pathParts.map((part, index) => {
        // Don't sanitize extension for the last part (filename)
        if (index === pathParts.length - 1) {
          return sanitizeFilename(part);
        }
        return sanitizeFilename(part);
      });

      const sanitizedPath = sanitizedParts.join(path.sep);
      const fullDestPath = path.join(destPath, sanitizedPath);

      // SECURITY: Ensure file stays within destination directory
      const normalizedDest = path.normalize(fullDestPath);
      if (!normalizedDest.startsWith(path.normalize(destPath))) {
        console.warn(`Path escape attempt blocked: ${entryPath}`);
        continue;
      }

      // Create parent directory
      await fs.ensureDir(path.dirname(fullDestPath), { mode: 0o755 });

      // Extract file (with password if provided)
      let content;
      try {
        content = password ? entry.getData(password) : entry.getData();
      } catch (decryptError) {
        if (decryptError.message?.includes('password') || decryptError.message?.includes('decrypt')) {
          return {
            success: false,
            error: 'Incorrect password for archive',
            code: 'INCORRECT_PASSWORD',
          };
        }
        throw decryptError;
      }
      
      // SECURITY: Final size check on actual extracted data
      if (content.length > MAX_EXTRACTED_FILE_SIZE) {
        console.warn(`Extracted content too large: ${entryPath}`);
        continue;
      }

      await fs.writeFile(fullDestPath, content, { mode: 0o644 });

      // Check if extracted file is a nested archive
      const ext = path.extname(fullDestPath).toLowerCase();
      if (NESTED_ARCHIVE_EXTENSIONS.has(ext)) {
        const nestedDestPath = fullDestPath.replace(/\.(zip|rar)$/i, '');
        const nestedResult = await extractArchive(fullDestPath, nestedDestPath);
        
        if (nestedResult.success) {
          // Remove the nested archive after extraction
          await fs.remove(fullDestPath);
        }
      }
    }

    return { success: true };
  } catch (error) {
    // Handle specific ZIP errors
    if (error.message?.includes('password')) {
      return {
        success: false,
        error: 'Archive is password protected',
        code: 'PASSWORD_PROTECTED',
      };
    }
    
    if (error.message?.includes('Invalid') || error.message?.includes('corrupt')) {
      return {
        success: false,
        error: 'Archive appears to be corrupted',
        code: 'CORRUPTED_ARCHIVE',
      };
    }

    throw error;
  }
};

/**
 * Extracts a RAR archive.
 * Uses node-unrar-js library with security validations.
 * 
 * @async
 * @param {string} rarPath - Path to the RAR file
 * @param {string} destPath - Destination directory
 * @param {string} [password] - Password for encrypted archives
 * @returns {Promise<{success: boolean, error?: string, code?: string}>}
 */
const extractRar = async (rarPath, destPath, password = null) => {
  try {
    const extractorOptions = {
      filepath: rarPath,
      targetPath: destPath,
    };
    
    // Add password if provided
    if (password) {
      extractorOptions.password = password;
    }
    
    const extractor = await createExtractorFromFile(extractorOptions);

    // Get list of files first to validate
    const list = extractor.getFileList();
    const fileHeaders = [...list.fileHeaders];

    // Check for password protection
    for (const header of fileHeaders) {
      if (header.flags?.encrypted) {
        if (!password) {
          return {
            success: false,
            error: 'Archive is password protected. Please provide a password.',
            code: 'PASSWORD_PROTECTED',
          };
        }
        break; // Password provided, continue with extraction
      }
    }

    // Extract files
    const extracted = extractor.extract();
    const files = [...extracted.files];

    // Process extracted files
    for (const file of files) {
      if (file.fileHeader.flags?.directory) {
        continue;
      }

      const filePath = file.fileHeader.name;
      
      // SECURITY: Validate path
      const pathValidation = validatePath(filePath);
      if (!pathValidation.valid) {
        const fullPath = path.join(destPath, filePath);
        await fs.remove(fullPath).catch(() => {});
        console.warn(`Removed unsafe entry: ${filePath}`);
        continue;
      }

      // SECURITY: Check extracted file size
      const fullPath = path.join(destPath, filePath);
      try {
        const stats = await fs.stat(fullPath);
        if (stats.size > MAX_EXTRACTED_FILE_SIZE) {
          await fs.remove(fullPath);
          console.warn(`Removed oversized entry: ${filePath}`);
          continue;
        }
      } catch (e) {
        // File might not exist if extraction failed
      }

      // Check for nested archives
      const ext = path.extname(fullPath).toLowerCase();
      if (NESTED_ARCHIVE_EXTENSIONS.has(ext)) {
        const nestedDestPath = fullPath.replace(/\.(zip|rar)$/i, '');
        const nestedResult = await extractArchive(fullPath, nestedDestPath);
        
        if (nestedResult.success) {
          await fs.remove(fullPath);
        }
      }
    }

    return { success: true };
  } catch (error) {
    // Handle specific RAR errors
    if (error.message?.includes('password') || error.message?.includes('encrypted')) {
      if (password) {
        return {
          success: false,
          error: 'Incorrect password for archive',
          code: 'INCORRECT_PASSWORD',
        };
      }
      return {
        success: false,
        error: 'Archive is password protected. Please provide a password.',
        code: 'PASSWORD_PROTECTED',
      };
    }
    
    if (error.message?.includes('Invalid') || error.message?.includes('corrupt') || 
        error.message?.includes('Bad')) {
      return {
        success: false,
        error: 'Archive appears to be corrupted',
        code: 'CORRUPTED_ARCHIVE',
      };
    }

    throw error;
  }
};

/**
 * Checks if a file is an archive that can be extracted.
 * 
 * @param {string} filePath - Path to check
 * @returns {boolean} True if file is a supported archive
 */
export const isArchive = (filePath) => {
  const ext = path.extname(filePath).toLowerCase();
  return NESTED_ARCHIVE_EXTENSIONS.has(ext);
};

/**
 * Gets extraction statistics for a session.
 * 
 * @async
 * @param {string} sessionPath - Path to the extracted session
 * @returns {Promise<{totalFiles: number, totalSize: number}>}
 */
export const getExtractionStats = async (sessionPath) => {
  let totalFiles = 0;
  let totalSize = 0;

  const walk = async (dir) => {
    const entries = await fs.readdir(dir);
    for (const entry of entries) {
      const fullPath = path.join(dir, entry);
      const stats = await fs.stat(fullPath);
      
      if (stats.isDirectory()) {
        await walk(fullPath);
      } else {
        totalFiles++;
        totalSize += stats.size;
      }
    }
  };

  await walk(sessionPath);
  return { totalFiles, totalSize };
};