Skip to content

Commit

Permalink
feat: includes file extension in mimetype detection
Browse files Browse the repository at this point in the history
  • Loading branch information
mathewmeconry committed Nov 10, 2023
1 parent 9c557d3 commit 5fb034c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
38 changes: 24 additions & 14 deletions src/helpers/mimetype.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,43 @@ import Logger from "./logger";

export function isAllowedMimeType(
file: Buffer,
allowedMimeTypes: string[]
allowedMimeTypes: string[],
filename: string = ""
): Promise<boolean> {
const logger = new Logger("isAllowedMimeType");
return filetype
.fromBuffer(file)
.then((fileType) => {
logger.debug(`Got fileType ${fileType}`);
let fileTypeWithDefault = fileType || { mime: "text/plain" };
let fileTypeWithDefault: string | undefined = fileType?.mime;

if (!fileTypeWithDefault) {
const extension = filename.split(".").pop();
logger.debug(`Found file extension .${extension}`)
switch (extension) {
case "json":
try {
JSON.parse(file.toString());
fileTypeWithDefault = "application/json";
break;
} catch (e) {
// ignore
}
default:
fileTypeWithDefault = "text/plain";
}
}

if (fileTypeWithDefault) {
for (const type of allowedMimeTypes) {
const match = fileTypeWithDefault.mime.match(type);
const match = fileTypeWithDefault.match(type);
if (match) {
logger.info(`Filetype ${fileType?.mime} allowed`);
logger.info(`Filetype ${fileTypeWithDefault} allowed`);
return true;
}
}
}
if (allowedMimeTypes.includes("application/json")) {
try {
logger.info(`Filetype appcliation/json allowed`);
JSON.parse(file.toString());
return true;
} catch (e) {
// ignore
}
}
logger.info(`Filetype ${fileType?.mime} not allowed!`);
logger.info(`Filetype ${fileTypeWithDefault} not allowed!`);
return false;
})
.catch(() => false);
Expand Down
5 changes: 3 additions & 2 deletions src/middlewares/add.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Express from "express";
import Logger from "../helpers/logger";
import multiparty from "multiparty";
import {isAllowedMimeType} from "../helpers/mimetype";
import { isAllowedMimeType } from "../helpers/mimetype";

interface Error {
statusCode: number;
Expand Down Expand Up @@ -32,6 +32,7 @@ export function addRouteMiddleware(
});

form.on("part", (part) => {
const filename = part.filename;
logger.debug(`Part received with name ${part.name}`);
if (!allowDirectories) {
if (part.headers["content-type"] == "application/x-directory") {
Expand All @@ -54,7 +55,7 @@ export function addRouteMiddleware(
if (!file) {
return;
}
isAllowedMimeType(file, allowedMimeTypes).then((allowed) => {
isAllowedMimeType(file, allowedMimeTypes, filename).then((allowed) => {
if (!allowed) {
form.emit("error", {
statusCode: 400,
Expand Down

0 comments on commit 5fb034c

Please sign in to comment.