Best Practices to Prevent Unrestricted File Upload in TypeScript ERP

Unrestricted file upload is a critical vulnerability that allows attackers to upload malicious files, leading to severe consequences such as data breaches, server compromise, and even complete application takeover. For ERP systems built on TypeScript, safeguarding against such vulnerabilities is paramount due to the sensitive nature of the data they manage. This blog post explores unrestricted file upload in TypeScript-based ERP, its risks, and best practices to prevent it, supported by practical coding examples.

Prevent Unrestricted File Upload in TypeScript:  Best 4 Tips

What Is Unrestricted File Upload?

Unrestricted file upload occurs when an application fails to validate or sanitize uploaded files adequately, allowing attackers to upload harmful content, including:

  • Malicious scripts that can lead to remote code execution.
  • Large files causing denial of service (DoS) attacks.
  • Phishing pages that mislead users.

For instance, a vulnerable TypeScript ERP may allow an attacker to upload a PHP file disguised as an image, which could execute malicious code on the server.


Why Is It Dangerous for ERP Systems?

ERP systems manage critical business operations like finance, inventory, and human resources. A successful attack exploiting unrestricted file upload vulnerabilities can:

  • Compromise sensitive business data.
  • Leads to unauthorized access to administrative functionalities.
  • Result in financial losses and reputational damage.

How to Prevent Unrestricted File Upload in TypeScript ERP

1. Validate File Type

One of the first steps is to strictly validate the file type using MIME types. Here’s how you can do it in TypeScript:

function validateFileType(file: File): boolean {
    const allowedMimeTypes = ["image/jpeg", "image/png", "application/pdf"];
    return allowedMimeTypes.includes(file.type);
}

// Usage
const file = new File(["sample content"], "example.pdf", { type: "application/pdf" });
if (!validateFileType(file)) {
    throw new Error("Invalid file type. Upload failed.");
}

2. Limit File Size

Restricting file size ensures the server isn’t overwhelmed by excessively large files.

function validateFileSize(file: File, maxSizeInMB: number): boolean {
    const maxSizeInBytes = maxSizeInMB * 1024 * 1024;
    return file.size <= maxSizeInBytes;
}

// Usage
if (!validateFileSize(file, 5)) {
    throw new Error("File size exceeds the allowed limit.");
}

3. Sanitize File Names

Renaming files and sanitizing file names can reduce the risk of path traversal attacks.

function sanitizeFileName(fileName: string): string {
    return fileName.replace(/[^a-zA-Z0-9.]/g, "_");
}

// Usage
const sanitizedFileName = sanitizeFileName(file.name);

4. Use Temporary Storage

Store uploaded files in a temporary directory and perform checks before moving them to permanent storage.

import * as fs from "fs";

function storeInTemporaryDirectory(file: File, tempDir: string): string {
    const tempFilePath = `${tempDir}/${sanitizeFileName(file.name)}`;
    fs.writeFileSync(tempFilePath, file);
    return tempFilePath;
}

// Usage
const tempFilePath = storeInTemporaryDirectory(file, "/tmp/uploads");

Practical Example: Secure File Upload Endpoint

Here’s a complete example of implementing a secure file upload endpoint in TypeScript using Express.js:

import express from "express";
import multer from "multer";

const app = express();
const upload = multer({ dest: "uploads/" });

app.post("/upload", upload.single("file"), (req, res) => {
    const file = req.file;

    // Validate file type
    if (!validateFileType(file.mimetype)) {
        return res.status(400).send("Invalid file type.");
    }

    // Validate file size
    if (file.size > 5 * 1024 * 1024) {
        return res.status(400).send("File size exceeds limit.");
    }

    // File is valid
    res.status(200).send("File uploaded successfully.");
});

function validateFileType(mimeType: string): boolean {
    const allowedMimeTypes = ["image/jpeg", "image/png", "application/pdf"];
    return allowedMimeTypes.includes(mimeType);
}

app.listen(3000, () => {
    console.log("Server running on http://localhost:3000");
});

Adding Photos for Better Understanding

Below are the screenshots demonstrating our free Website Security Checker tools and an example vulnerability assessment report:

Screenshot of the free tools webpage where you can access security assessment tools for different vulnerability detection
Screenshot of the free tools webpage where you can access security assessment tools for different vulnerability detection.
  • Vulnerability Assessment Report
An example of a vulnerability assessment report generated with our free tool provides insights into possible vulnerabilities.
An example of a vulnerability assessment report generated with our free tool provides insights into possible vulnerabilities.

Explore More Cybersecurity Topics

For more blogs, visit our blog page.


Conclusion

By implementing these best practices, you can effectively mitigate the risks of unrestricted file upload in TypeScript ERP systems. From validating file types to sanitizing file names, these strategies form a robust defense mechanism. Utilize our tools to test website security free for regular vulnerability assessments and ensure your ERP remains secure.


Free Consultation

If you have any questions or need expert assistance, feel free to schedule a Free consultation with one of our security engineers>>

Get a Quote

1 thought on “Best Practices to Prevent Unrestricted File Upload in TypeScript ERP”

  1. Pingback: Prevent Clickjacking in TypeScript Based ERP: Best 7 Ways

Leave a Comment

Your email address will not be published. Required fields are marked *