72 lines
2.6 KiB
TypeScript
72 lines
2.6 KiB
TypeScript
import fs from 'fs';
|
|
|
|
type MagicRule = {
|
|
mime: string;
|
|
match: (buf: Buffer) => boolean;
|
|
};
|
|
|
|
const RULES: MagicRule[] = [
|
|
{ mime: 'image/jpeg', match: (b) => b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
|
|
{ mime: 'image/png', match: (b) => b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) },
|
|
{ mime: 'image/gif', match: (b) => b.length >= 6 && (b.subarray(0, 6).toString('ascii') === 'GIF87a' || b.subarray(0, 6).toString('ascii') === 'GIF89a') },
|
|
{
|
|
mime: 'image/webp',
|
|
match: (b) => b.length >= 12 && b.subarray(0, 4).toString('ascii') === 'RIFF' && b.subarray(8, 12).toString('ascii') === 'WEBP',
|
|
},
|
|
{ mime: 'application/pdf', match: (b) => b.length >= 5 && b.subarray(0, 5).toString('ascii') === '%PDF-' },
|
|
{ mime: 'video/mp4', match: (b) => b.length >= 12 && b.subarray(4, 8).toString('ascii') === 'ftyp' },
|
|
{ mime: 'video/webm', match: (b) => b.length >= 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3 },
|
|
{
|
|
mime: 'text/plain',
|
|
match: (b) => {
|
|
const sample = b.subarray(0, Math.min(b.length, 512));
|
|
for (const byte of sample) {
|
|
if (byte === 0) return false;
|
|
if (byte < 9 || (byte > 13 && byte < 32 && byte !== 27)) return false;
|
|
}
|
|
return sample.length > 0;
|
|
},
|
|
},
|
|
{
|
|
mime: 'application/msword',
|
|
match: (b) => b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])),
|
|
},
|
|
{
|
|
mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
match: (b) => b.length >= 4 && b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04,
|
|
},
|
|
];
|
|
|
|
/** Detects MIME type from file header bytes. */
|
|
export function detectMimeFromBuffer(buf: Buffer): string | null {
|
|
if (!buf.length) return null;
|
|
for (const rule of RULES) {
|
|
if (rule.match(buf)) return rule.mime;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Ensures on-disk upload content matches an allowed MIME (magic bytes, not client header). */
|
|
export function assertAllowedFileMagic(filePath: string, allowedMimes: Set<string>): void {
|
|
const fd = fs.openSync(filePath, 'r');
|
|
try {
|
|
const buf = Buffer.alloc(512);
|
|
const read = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
const detected = detectMimeFromBuffer(buf.subarray(0, read));
|
|
if (!detected || !allowedMimes.has(detected)) {
|
|
throw new Error('File content does not match an allowed type');
|
|
}
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
}
|
|
|
|
/** Removes an uploaded file after failed validation. */
|
|
export function removeUploadedFile(filePath: string): void {
|
|
try {
|
|
fs.unlinkSync(filePath);
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}
|