You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中校验ZIP包文件类型 拦截违规文件上传至S3

How to Validate ZIP Files for Restricted Extensions Before Uploading to S3 in Node.js

Got it, let's walk through how to implement the validation logic in the entry event to block ZIPs containing .js, .exe, or .json files before sending them to S3. Here's a practical, step-by-step solution:

First, we'll add a few key pieces: a list of restricted file extensions, logic to check each entry's type and extension, and handling to stop processing immediately if we find a forbidden file.

Modified Code with Validation Logic

const unzip = require('unzip');
const fs = require('fs');
const path = require('path'); // Add this to handle file extensions consistently
const inputFileName = '/home/nn/Downloads/delete.zip';

// Define our restricted extensions (easy to update later)
const restrictedExtensions = ['.js', '.exe', '.json'];
let zipIsValid = true; // Flag to track if the ZIP passes validation

const zipStream = fs.createReadStream(inputFileName)
  .pipe(unzip.Parse())
  .on('entry', (entry) => {
    const entryPath = entry.path;
    const entryType = entry.type; // 'File' or 'Directory'

    // Skip directories—we only need to validate actual files
    if (entryType !== 'File') {
      entry.autodrain();
      return;
    }

    // Get the file extension (convert to lowercase to catch .JS, .EXE, etc.)
    const fileExtension = path.extname(entryPath).toLowerCase();

    // Check if the extension is in our restricted list
    if (restrictedExtensions.includes(fileExtension)) {
      console.log(`Forbidden file detected: ${entryPath} (extension ${fileExtension})`);
      zipIsValid = false;
      
      // Stop processing the ZIP right away to save resources
      zipStream.destroy(new Error('ZIP contains restricted file types'));
      entry.autodrain();
      return;
    }

    // No issues? Continue draining the entry to process remaining files
    entry.autodrain();
  })
  .on('error', (err) => {
    console.error('Validation failed:', err.message);
    // Here you would cancel any pending S3 upload attempts
  })
  .on('finish', () => {
    if (zipIsValid) {
      console.log('ZIP validation passed—proceed with S3 upload');
      // Add your S3 upload code here (e.g., using AWS SDK's putObject)
    } else {
      console.log('ZIP validation failed—do NOT upload to S3');
    }
  });

Key Details Explained

  • Restricted Extensions List: Using an array makes it simple to add/remove forbidden file types later without rewriting core validation logic.
  • Entry Type Check: We skip directories because we only care about validating actual files in the ZIP.
  • Case Insensitivity: Converting the extension to lowercase ensures we catch variations like .JS or .JSON that might slip through a case-sensitive check.
  • Immediate Stream Termination: As soon as we find a forbidden file, we mark the ZIP as invalid, destroy the stream to stop processing, and trigger an error. This avoids wasting resources on processing the rest of the ZIP.
  • Finish Event Handling: After all entries are processed, we check our zipIsValid flag. If it's true, we can safely proceed with the S3 upload; if not, we block the upload entirely.

Next Steps for S3 Integration

Make sure your S3 upload code is only executed inside the finish event's valid branch. If validation fails, you should abort any upload attempts and notify the user/system that the ZIP has been rejected.

内容的提问来源于stack exchange,提问作者user11750635

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:43:13