A lightweight NodeJS library for strict mime-type validation on streams

Overview

Typective

A lightweight NodeJS library for strict mime-type validation on streams. It gets a ReadableStream and decets the mime-type using its Magic number and validates it using the provided allowed and forbidden lists; If it's allowed it will pass it to the created WritableStreams and if it's not it will throw an error.

Table of contents

Installation

npm i typective

Quick start

[fs.createWriteStream(`image-2.${payload.extensions[0]}`)] ); } catch(error){ console.error(error); }">
const typective = require("typective");

try{
	const { type } = await typective(
		fs.createReadStream("image-1.jpeg"),
		{ allowed: ["image/*"] },
		payload => [fs.createWriteStream(`image-2.${payload.extensions[0]}`)]
	);
} catch(error){ console.error(error); }

Examples

Upload example

Save the file if it is an image

Note: We are using Busboy in this example for handling file uploads.

{ if (request.method === "POST") { const uploader = busboy({ headers: request.headers }); uploader.on("file", async (name, file, info) => { /** * Note: info.mimeType is just based on the file extension * and not the actual mime-type of the file. * For example if we have a video file named "video.mp4" * And rename it to "video.jpeg" then upload it to the server; * The file.mimeType would be "image/jpeg" which it is clearly * Not the mime-type of our file! */ try { const { type } = await typective( file, { allowed: ["image/*"] }, payload => [ fs.createWriteStream( `./upload.${payload.extensions[0]}` ) ] ); response.writeHead(200, { "Content-Type": "application/json", Connection: "close" }); response.end(JSON.stringify({ type })); } catch (error) { response.writeHead(400, { "Content-Type": "application/json", Connection: "close" }); response.end(JSON.stringify({ error: error.message })); } }); request.pipe(uploader); } }).listen(3000, () => { console.log("Server running on port 3000"); });">
const http = require("http"),
    busboy = require("busboy"),
    fs = require("fs"),
    typective = require("typective");

http.createServer((request, response) => {
    if (request.method === "POST") {
        const uploader = busboy({ headers: request.headers });
        
        uploader.on("file", async (name, file, info) => {
            /**
             * Note: info.mimeType is just based on the file extension
             * and not the actual mime-type of the file.
             * For example if we have a video file named "video.mp4"
             * And rename it to "video.jpeg" then upload it to the server;
             * The file.mimeType would be "image/jpeg" which it is clearly
             * Not the mime-type of our file!
             */

            try {
                const { type } = await typective(
                    file,
                    {
                        allowed: ["image/*"]
                    },
                    payload => [
                        fs.createWriteStream(
                            `./upload.${payload.extensions[0]}`
                        )
                    ]
                );

                response.writeHead(200, {
                    "Content-Type": "application/json",
                    Connection: "close"
                });

                response.end(JSON.stringify({ type }));
            } catch (error) {
                response.writeHead(400, {
                    "Content-Type": "application/json",
                    Connection: "close"
                });
                response.end(JSON.stringify({ error: error.message }));
            }
        });

        request.pipe(uploader);
    }
}).listen(3000, () => {
    console.log("Server running on port 3000");
});

Download example

Save the file if it is an image and not a PNG

{ try { await typective( response, { allowed: ["image/*"], forbidden: ["image/png"] }, payload => [ fs.createWriteStream(`./download.${payload.extensions[0]}`) ] ); } catch (error) { console.error(error); } });">
const https = require("https"),
    fs = require("fs"),
    typective = require("typective");

const URL =
    "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png";

https.get(URL, async response => {
    try {
        await typective(
            response,
            {
                allowed: ["image/*"],
                forbidden: ["image/png"]
            },
            payload => [
                fs.createWriteStream(`./download.${payload.extensions[0]}`)
            ]
        );
    } catch (error) {
        console.error(error);
    }
});

API

Exports

typective exports a single function.

( function )(< ReadableStream >sourceStream, < object >config, < function >contextCreator) - Detects mime-type of a given readable stream and passes it to given streams if the detected mime-type is allowed

  • Valid options properties:

    • allowed - Array of allowed mime-types

    • forbidden - Array of forbidden mime-types

    • bufferSize - Buffer size of each chunk in the pipeline

  • contextCreator(< Object >payload) - A function that will be called with an payload object when the mime-type has been detected. You can use it to create and pass your WritableStreams to the typective. (It should always return an array of WritableStreams otherwisethe process would stuck)

    • payload properties:

      • extensions - Array of detected extensions

      • category - Detected file category

This function will throw exceptions if given stream is not a readable stream or if the detected mime-type is not allowed.

You might also like...

Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Nov 1, 2022

jQuery form validation plugin

jQuery form validation plugin

jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t

Dec 23, 2022

Dead simple Object schema validation

Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin

Jan 2, 2023

Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit

Oct 3, 2022

:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator ✅ Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Dec 14, 2022

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Dec 26, 2022

📫 Offline email validation - JS or TS

email-seems-valid An offline check to see if an email seems valid. Contains TS or JS packages for browser or Node.js emailSeemsValid('[email protected]')

Dec 25, 2022

TypeScript-first schema validation for h3 and Nuxt applications

h3-zod Validate h3 and Nuxt 3 requests using zod schema's. Install npm install h3-zod Usage import { createServer } from 'http' import { createApp } f

Dec 28, 2022

Schema validation utilities for h3, using typebox & ajv

h3-typebox JSON schema validation for h3, using typebox & ajv. Install # Using npm npm install h3-typebox # Using yarn yarn install h3-typebox # Usi

Dec 10, 2022
Releases(v1.2.1)
Owner
CEO of Death Star
Guess I Code
CEO of Death Star
Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Rick Harrison 2.6k Dec 15, 2022
Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

Illia 49 May 13, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
The most powerful data validation library for JS

joi The most powerful schema description language and data validator for JavaScript. Installation npm install joi Visit the joi.dev Developer Portal f

Sideway Inc. 19.6k Jan 4, 2023
A simple credit cards validation library in JavaScript

creditcard.js A simple credit cards validation library in JavaScript. Project website: https://contaazul.github.io/creditcard.js Install creditcard.js

ContaAzul 323 Jan 7, 2023
v8n ☑️ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Bruno C. Couto 4.1k Dec 30, 2022
Themis is a validation and processing library that helps you always make sure your data is correct.

Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. ·

Dataffy 14 Oct 27, 2022
String validation

validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your

null 20.7k Jan 5, 2023