Parse Content-Disposition Header Safely
Parse attachment and inline headers, including RFC 5987 filename*, while stripping directory components from untrusted names.
Code
export function parseContentDisposition(header) {
if (typeof header !== "string" || header.trim() === "") {
throw new TypeError("header must be a non-empty string");
}
const segments = splitParameters(header);
const type = segments.shift().trim().toLowerCase();
if (type !== "inline" && type !== "attachment") {
throw new Error(`unsupported disposition type "${type}"`);
}
const parameters = new Map();
for (const segment of segments) {
const equals = segment.indexOf("=");
if (equals === -1) continue;
const name = segment.slice(0, equals).trim().toLowerCase();
if (name === "") continue;
parameters.set(name, unquote(segment.slice(equals + 1).trim()));
}
return { type, filename: resolveFilename(parameters), parameters };
}
function splitParameters(header) {
const segments = [];
let current = "";
let quoted = false;
for (const character of header) {
if (character === '"') quoted = !quoted;
if (character === ";" && !quoted) {
segments.push(current);
current = "";
continue;
}
current += character;
}
segments.push(current);
return segments;
}
function unquote(value) {
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
return value.slice(1, -1).replace(/\\(.)/g, "$1");
}
return value;
}
function resolveFilename(parameters) {
const extended = parameters.get("filename*");
if (extended !== undefined) {
const match = /^([\w-]+)'([\w-]*)'(.+)$/.exec(extended);
if (match !== null) {
try {
return sanitize(decodeURIComponent(match[3]));
} catch {
return sanitize(extended);
}
}
}
const plain = parameters.get("filename");
return plain === undefined ? null : sanitize(plain);
}
function sanitize(filename) {
return filename.split(/[\\/]/).pop() || null;
}
console.log(parseContentDisposition('attachment; filename="report.pdf"'));
console.log(parseContentDisposition("attachment; filename*=UTF-8''%E4%B8%AD%E6%96%87.pdf"));
console.log(parseContentDisposition('inline; filename="../../etc/passwd"'));How the snippet works
Parse Content-Disposition Header Safely keeps everything in the functions parseContentDisposition, splitParameters, unquote and resolveFilename.
The core work runs in nested loops — outer for (const segment of segments), inner for (const character of header). When the guard condition holds, TypeError and Error is thrown rather than a bogus value returned.
The result comes back as an object carrying type.
Points of care
- The guard
type !== "inline" && type !== "attachment"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The entry-point signature is export function parseContentDisposition(header)
The surface worth importing is parseContentDisposition; the helpers around it are private to the snippet.
The call returns type.
Key statements
return { type, filename: resolveFilename(parameters), parameters };
throw new Error(`unsupported disposition type "${type}"`);
throw new TypeError("header must be a non-empty string");
Interactive Tools for This Topic
FAQ
- Does `parseContentDisposition` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- What happens if the preconditions do not hold?
- The code refuses to continue: `TypeError` and `Error` is thrown while the state is still recoverable.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `parseContentDisposition`, `splitParameters`, `unquote` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.