Stop Trusting File Extensions: Sniff File Signatures in the Browser
A file named invoice.pdf is not necessarily a PDF. Rename a PNG, and most apps still trust the extension first. In a browser-only tool that mistake is not just cosmetic: it sends the wrong bytes to the wrong decoder and
A file named invoice.pdf is not necessarily a PDF. Rename a PNG, and most apps still trust the extension first. In a browser-only tool that mistake is not just cosmetic: it sends the wrong bytes to the wrong decoder and the user gets a confusing error.
I hit this while routing files across Toolcin, a set of client-side utilities. The fix is smaller than it sounds. Read the first 16 bytes, look for a known signature, then choose the tool. No upload, no server, no MIME sniffing library.
Why extensions are the wrong router
The operating system uses extensions for convenience. Browsers expose file.type, but it comes from the OS and can be empty or wrong. Trusting either one means:
- a renamed ZIP opens in the PDF tool
- a HEIC photo reaches the JPEG decoder
- a truncated download fails deep inside a library instead of at the input
A signature check is not a security boundary, but it is a much better user-experience boundary.
Read only the bytes you need
A File is a Blob. Blob.slice() returns a small Blob without loading the whole file, and arrayBuffer() resolves with its bytes. MDN documents this in Blob.slice(). For signatures, 16 bytes are enough.
async function firstBytes(file, length = 16) {
return new Uint8Array(await file.slice(0, length).arrayBuffer());
}
Nothing has been uploaded. The bytes came from the local file the user selected.
Match known prefixes
I keep the signature table explicit so every format has a name and a source. Prefixes are easier to audit than a pile of regexes.
const startsWith = (bytes, prefix) =>
prefix.every((byte, i) => bytes[i] === byte);
const ascii = (bytes, start, length) =>
String.fromCharCode(...bytes.slice(start, start + length));
export async function detectFileType(file) {
const b = await firstBytes(file);
if (startsWith(b, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";
if (startsWith(b, [0xff, 0xd8, 0xff])) return "image/jpeg";
if (ascii(b, 0, 4) === "%PDF") return "application/pdf";
if (ascii(b, 0, 4) === "GIF8") return "image/gif";
if (startsWith(b, [0x50, 0x4b, 0x03, 0x04])) return "application/zip";
if (ascii(b, 0, 4) === "RIFF" && ascii(b, 8, 4) === "WEBP") {
return "image/webp";
}
// HEIC and MP4 share the ISO base media "ftyp" box.
if (ascii(b, 4, 4) === "ftyp") {
const brand = ascii(b, 8, 4);
if (["heic", "heix", "hevc", "hevx", "mif1"].includes(brand)) {
return "image/heic";
}
if (["isom", "iso2", "mp41", "mp42", "avc1"].includes(brand)) {
return "video/mp4";
}
}
return "application/octet-stream";
}
HEIC brands vary by vendor, so keep that list small and extend it when a real file fails. Do not guess from the file name to fill the gap.
Route the file, do not pass it through the URL
Once the type is known, show the matching tool and ask the user to pick the file there. A local File object cannot be handed to another page through a URL.
const routes = {
"application/pdf": "PDF tools",
"image/heic": "HEIC to JPG",
"image/png": "PNG to JPG",
"image/jpeg": "JPG to PNG",
};
const input = document.querySelector("#file");
input.addEventListener("change", async (event) => {
const file = event.target.files[0];
if (!file) return;
const type = await detectFileType(file);
const label = routes[type];
document.querySelector("#result").textContent = label
? "Detected: " + type + ". Use " + label + " below."
: "Could not identify this file. Try the file format list.";
});
The message is actionable. The user is never left staring at a library stack trace.
Test the awkward cases
A few checks catch most regressions:
- rename a PNG to .pdf and confirm it still detects as PNG
- select an empty file and confirm you get the unknown-format message
- use a truncated PDF and confirm the prefix check succeeds before the decoder runs
- try a HEIC from a phone and check the brand list
I run these as small fixtures, not against random downloads from the internet.
What this does not solve
Signatures can be forged. Polyglot files exist. Some formats need deeper parsing than 16 bytes. Treat this as routing and early feedback, never as a sandbox or a substitute for validating inside the decoder.
For a client-side tool, that boundary is still valuable: the file stays on disk, the first bytes are read locally, and the wrong decoder never sees it.
Toolcin uses this pattern across its browser-only tools. You can try one here: https://toolcin.pages.dev/
AI disclosure: this article was drafted with AI assistance and checked against the File API behavior and the Toolcin source before saving.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.