Files
Kelx/utils/download-headers.js
T
2026-11-30 16:32:37 +00:00

122 lines
5.5 KiB
JavaScript

"use strict";
// adpanel:download-headers-pinning - the panel (index.js /files/download) and
// the nodes.js relay used to forward node-supplied Content-Type /
// Content-Disposition headers verbatim, so a compromised or malicious node
// declaring e.g. `text/html` inline could execute HTML on the panel origin
// (X-Content-Type-Options: nosniff does not block an explicitly declared
// type). Downloads are pinned to application/octet-stream + attachment with a
// filename derived from the download route's own requested path, never from
// node-supplied headers.
//
// The embedded name is sanitized because it lands inside the quoted-string of
// a response header: control characters (CRLF would smuggle extra header
// fields; Node's setHeader would throw on them anyway), quotes and
// backslashes (they close or escape the quoted-string) and path separators
// (a client must not be talked into writing outside its download directory)
// are stripped, the result is capped, and an empty result falls back to
// "download".
//
// adpanel:download-header-latin1 - Node's res.setHeader throws
// TypeError: Invalid character in header content for any header-value
// character with code point > 0xFF (its header-value validator admits only
// \t, 0x20-0x7E and obs-text 0x80-0xFF), and both call sites (index.js
// /files/download and the nodes.js relay) run it inside the async upstream
// response callback OUTSIDE their route try/catch, so the throw surfaces as
// an uncaughtException that kills the whole panel worker. The upload filename
// sanitizer deliberately allows non-ASCII, so any files_read user could crash
// the panel by downloading a CJK/emoji-named file. The constraint enforced
// here: EVERY header value this module emits is Latin-1-safe (code point
// <= 0xFF). The quoted-string `filename=` keeps the Latin-1 projection of the
// sanitized name (chars > 0xFF become "_"); the original non-ASCII spelling
// rides alongside it in the RFC 5987 `filename*=UTF-8''...` parameter
// (percent-encoded UTF-8, pure ASCII by construction) for clients that
// support it. Pure-ASCII names keep the historical single-parameter output.
const DOWNLOAD_CONTENT_TYPE = "application/octet-stream";
const DOWNLOAD_CONTENT_DISPOSITION_PREFIX = "attachment";
const DOWNLOAD_FILENAME_MAX_LENGTH = 150;
const DOWNLOAD_FILENAME_FALLBACK = "download";
const DOWNLOAD_FILENAME_STAR_CHARSET = "UTF-8''";
// RFC 5987 mime-chars kept literal in filename*: only the unreserved set
// A-Z a-z 0-9 - . _ ~. Everything else — including the percent sign, the
// apostrophe (the ext-value delimiter) and every attribute separator — is
// percent-encoded, so the parameter can never break out of its ext-value.
const RFC5987_UNRESERVED_RE = /[A-Za-z0-9\-._~]/;
// Any character outside printable ASCII (0x20-0x7E) in the sanitized name
// switches the header to the two-parameter form. DEL (0x7F) and control
// characters are already stripped by sanitizeDownloadFilename, so this
// matches exactly the non-ASCII chars.
const NON_ASCII_RE = /[^\x20-\x7e]/;
function sanitizeDownloadFilename(raw) {
const cleaned = String(raw ?? "")
.replace(/[/\\]/g, "")
// eslint-disable-next-line no-control-regex
.replace(/[\u0000-\u001f\u007f]/g, "")
.replace(/["']/g, "")
.trim()
.slice(0, DOWNLOAD_FILENAME_MAX_LENGTH);
return cleaned || DOWNLOAD_FILENAME_FALLBACK;
}
// Latin-1 projection of an already-sanitized name: every char with code
// point > 0xFF (which setHeader rejects, e.g. CJK, emoji) becomes "_".
// Chars 0x80-0xFF (e.g. ö, ü) are header-legal obs-text and are kept, so
// legacy clients still see them. 1:1 replacement cannot empty the string,
// so no fallback is needed here.
function toLatin1SafeFilename(sanitized) {
return sanitized.replace(/[^\u0000-\u00ff]/g, "_");
}
// Percent-encode the UTF-8 bytes of the sanitized name per RFC 5987. The
// result is always pure ASCII. Iterating code points (not UTF-16 units) so
// astral characters (emoji) encode as one sequence, never as lone surrogates.
function encodeRfc5987Value(sanitized) {
let out = "";
for (const ch of sanitized) {
if (RFC5987_UNRESERVED_RE.test(ch)) {
out += ch;
continue;
}
for (const byte of Buffer.from(ch, "utf8")) {
out += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
}
}
return out;
}
function buildContentDisposition(rawFilename) {
const sanitized = sanitizeDownloadFilename(rawFilename);
if (!NON_ASCII_RE.test(sanitized)) {
// Historical shape for pure-ASCII names (pinned by tests): one
// quoted-string parameter, no filename*.
return `${DOWNLOAD_CONTENT_DISPOSITION_PREFIX}; filename="${sanitized}"`;
}
return (
`${DOWNLOAD_CONTENT_DISPOSITION_PREFIX}; filename="${toLatin1SafeFilename(sanitized)}"` +
`; filename*=${DOWNLOAD_FILENAME_STAR_CHARSET}${encodeRfc5987Value(sanitized)}`
);
}
// Pins both headers unconditionally. Content-Length is deliberately NOT
// handled here: the proxy sites keep their pass-through of the upstream
// value, which must stay byte-exact with the streamed body.
function setPinnedDownloadHeaders(res, rawFilename) {
res.setHeader("Content-Type", DOWNLOAD_CONTENT_TYPE);
res.setHeader("Content-Disposition", buildContentDisposition(rawFilename));
}
module.exports = {
DOWNLOAD_CONTENT_DISPOSITION_PREFIX,
DOWNLOAD_CONTENT_TYPE,
DOWNLOAD_FILENAME_FALLBACK,
DOWNLOAD_FILENAME_MAX_LENGTH,
DOWNLOAD_FILENAME_STAR_CHARSET,
buildContentDisposition,
encodeRfc5987Value,
sanitizeDownloadFilename,
setPinnedDownloadHeaders,
toLatin1SafeFilename,
};