npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

secure-file-validator

v1.0.2

Published

Secure file validation library with signature checking and content validation

Downloads

201

Readme

secure-file-validator

npm version License: MIT Node.js Version

A secure file validation library for Node.js that performs signature checking and content validation. It hardenings app from malicious file uploads by validating file types, checking file signatures, and scanning for suspicious patterns.

This library is built following industry-standard security guidelines:

Features

  • 🔒 Secure file signature validation
  • 📝 Content pattern scanning for malicious code
  • 🎯 Support for multiple file types (JPEG, PNG, GIF, PDF, SVG)
  • ⚡ Promise-based async/await API
  • 🛡️ Built-in security checks for PDF and SVG files
  • 📦 Zero dependencies
  • 🌟 TypeScript support
  • ⚙️ Customizable file size validation

Installation

npm install secure-file-validator

Usage

Basic Usage (Default 5MB limit)

import { validateFile } from "secure-file-validator";

try {
  const result = await validateFile("path/to/your/file.pdf");

  if (result.status) {
    console.log("File is valid:", result.message);
  } else {
    console.log("File validation failed:", result.message);
  }
} catch (error) {
  console.error("Error:", error);
}

Custom File Size Limit

import { validateFile } from "secure-file-validator";

// Example: Set 10MB limit
const TEN_MB = 10 * 1024 * 1024; // 10MB in bytes

try {
  const result = await validateFile("path/to/your/file.pdf", {
    maxSizeInBytes: TEN_MB,
  });

  if (result.status) {
    console.log("File is valid:", result.message);
  } else {
    console.log("File validation failed:", result.message);
  }
} catch (error) {
  console.error("Error:", error);
}

Using Size Constants

// File size constants for convenience
const KB = 1024;
const MB = 1024 * KB;
const GB = 1024 * MB;

// Examples
const options = {
  maxSizeInBytes: 10 * MB, // 10MB
  // or
  // maxSizeInBytes: 1 * GB  // 1GB
};

const result = await validateFile("path/to/file.pdf", options);

Advanced Usage

import {
  validateFile,
  validateFileContent,
  checkFileSignature,
} from "secure-file-validator";

// Example: Custom validation pipeline with size limit
async function validateUserUpload(filePath) {
  const options = {
    maxSizeInBytes: 15 * 1024 * 1024, // 15MB limit
  };

  // First, validate the entire file
  const fileValidation = await validateFile(filePath, options);
  if (!fileValidation.status) {
    return fileValidation;
  }

  // Then, perform additional content validation if needed
  const contentValidation = await validateFileContent(filePath);
  return contentValidation;
}

Supported File Types

| Category | File Type | | --------------- | --------- | | Images | JPEG/JPG | | Images | PNG | | Images | GIF | | Documents | PDF | | Vector Graphics | SVG |

API Reference

validateFile(filePath, options)

Main validation function that performs all checks.

| Parameter | Type | Description | Default | | ------------------------ | ------ | ---------------------------- | -------- | | filePath | string | Path to the file to validate | required | | options | Object | Configuration options | {} | | options.maxSizeInBytes | number | Maximum file size in bytes | 5MB |

| Return Type | Description | | ------------------------- | ------------------------------------ | | Promise<Object> | Async result object | | Promise<Object>.status | boolean indicating validation result | | Promise<Object>.message | string containing detailed message |

validateFileContent(filePath)

Performs content-specific validation.

| Parameter | Type | Description | Default | | ---------- | ------ | ---------------------------- | -------- | | filePath | string | Path to the file to validate | required |

| Return Type | Description | | ------------------------- | ------------------------------------ | | Promise<Object> | Async result object | | Promise<Object>.status | boolean indicating validation result | | Promise<Object>.message | string containing detailed message |

checkFileSignature(buffer, signatures)

Checks file buffer against known signatures.

| Parameter | Type | Description | Default | | ------------ | ---------------------- | --------------------------------- | -------- | | buffer | Buffer | File buffer to check | required | | signatures | Array<Array<number>> | Valid signatures to check against | required |

| Return Type | Description | | ----------- | ------------------------------------------ | | boolean | True if signature matches, false otherwise |

File Size Configuration

The file size limit is configurable through the maxSizeInBytes option:

// Common file size limits
const limits = {
  small: 1 * 1024 * 1024, // 1MB
  medium: 10 * 1024 * 1024, // 10MB
  large: 100 * 1024 * 1024, // 100MB
  custom: 15.5 * 1024 * 1024, // 15.5MB
};

// Usage
const result = await validateFile("file.pdf", {
  maxSizeInBytes: limits.medium,
});

Example Results

// Successful validation
{
  status: true,
  message: "Content validation passed"
}

// Failed validation (file size)
{
  status: false,
  message: "File size exceeds limit of 5MB"
}

// Failed validation (invalid file type)
{
  status: false,
  message: "Invalid file extension"
}

// Failed validation (malicious content)
{
  status: false,
  message: "Suspicious pattern detected: /<script/i"
}

Limitations

  • Only supports specified file types
  • No stream processing support
  • Binary file content is not deeply analyzed
  • Pattern matching is done on string representation of files

Error Handling

try {
  const options = { maxSizeInBytes: 10 * 1024 * 1024 }; // 10MB
  const result = await validateFile("path/to/file.pdf", options);

  if (!result.status) {
    // Handle invalid file
    console.error("Validation failed:", result.message);
    // Take appropriate action (e.g., delete file, notify user)
  }
} catch (error) {
  // Handle system errors
  console.error("System error:", error.message);
  // Take appropriate action (e.g., log error, notify admin)
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

FAQ

Q: How can I set a custom file size limit?
A: You can pass the limit in bytes using the options parameter:

const limit = 10 * 1024 * 1024; // 10MB
const result = await validateFile("file.pdf", { maxSizeInBytes: limit });

Q: What's the default file size limit?
A: The default limit is 5MB if no custom limit is specified.

Q: Can I set unlimited file size?
A: While technically possible by setting a very large number, it's not recommended as files are read into memory during validation.

Q: How can I handle different size limits for different file types?
A: You can create a wrapper function:

async function validateWithTypeLimit(filePath) {
  const extension = path.extname(filePath).toLowerCase();
  const limits = {
    ".pdf": 10 * 1024 * 1024, // 10MB for PDFs
    ".jpg": 5 * 1024 * 1024, // 5MB for JPGs
    ".svg": 2 * 1024 * 1024, // 2MB for SVGs
  };

  return validateFile(filePath, {
    maxSizeInBytes: limits[extension] || 5 * 1024 * 1024,
  });
}

License

This project is licensed under the MIT License

Thank you 😀