1

I have the following problem: When a client enters a certain URL it receives an .mp3 file back via sendFile() from Express. The name of the file is defined in the response header as follow:

var fileName = (JSON.stringify(data.videoTitle).replace(/["']/g, "") + fileType);

headers: {
        'x-timestamp': Date.now(),
        'x-sent': true,
        'Content-type': 'application/octet-stream',
        'Content-Disposition': 'attachment; filename="' + fileName + '"'
    }

The problem is that fileName is fetched from another website and I have no control over what the title of the file will be. So far it was no problem but it just happened to me that a file contained the character ú which lead to the following error:

throw new TypeError('The header content contains invalid characters');

This could potentially happen very often as there are many characters that the headers might not like. Is there any possibility that I only keep valid characters before setting the header? I assume a whitelist approach would be better than a blacklist approach as there are nearly infinite possibilities of invalid characters.

Thank you very much in advance

DesperateEi
  • 134
  • 3
  • 10
  • 1
    [How to encode the filename parameter of Content-Disposition header in HTTP?](https://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http) – Alex K. Jul 21 '17 at 13:43
  • @AlexK. Thank you for the link (a pointer to the right direction). I guess for now I will just remove every non-ASCII character. The mentioned post seems to be old though so I wonder if there currently is any new development (or a standard). – DesperateEi Jul 21 '17 at 13:53
  • I would suggest using an outside library to get rid of diacritics, if you do not wish to simply encode fileName. https://www.npmjs.com/package/diacritics – mjarraya Jul 21 '17 at 13:55
  • Possible duplicate of [How to encode the filename parameter of Content-Disposition header in HTTP?](https://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http) – Tom Blodget Jul 21 '17 at 16:12

1 Answers1

3

Here is an extended answer which basically tells you that only a subset of ASCII or ISO-8859-1 is allowed.

What character encoding should I use for a HTTP header?

And here is your solution: transliterate the filename into ASCII characters to make it safe for use in a header value:

https://www.npmjs.com/package/transliteration

Tudor Ilisoi
  • 2,934
  • 23
  • 25