"use strict"; const path = require("path"); // Canonical JS mirror of the node daemon's sanitizeUploadFilename (main.go). // Shared by the panel upload endpoints, the rename paths (utils/daemon-protocol.js) // and the nodes.js relay (injected via setUploadPolicyHooks) so every side // agrees on the final on-disk name and the extension policy always sees the // true extension. // // Semantics: backslashes, control characters and unpaired surrogates become // "_"; leading dots and valid non-ASCII are preserved (dotfiles like .env are // legitimate); unusable names ("", ".", "..", "/") return null so callers // answer 400. The cap is 200 bytes on a code-point boundary — the same cap // the daemon applies. // // The trims deliberately include U+0085 (NEL): Go's strings.TrimSpace strips // it, JS String.trim() does not. Without this, a multipart filename // "evil.bat\u0085" passes the extension blocklist (extname sees ".bat\u0085") // and the daemon then trims it to "evil.bat" on disk. JS also strips U+FEFF, // which Go keeps — the panel being stricter is always the safe direction. function sanitizeUploadFilename(name) { const goTrim = s => s.replace(/^[\s\u0085]+/, "").replace(/[\s\u0085]+$/, ""); const raw = goTrim(String(name ?? "")); if (!raw) return null; const base = path.posix.basename(raw); const cleaned = goTrim(Array.from(base).map(ch => { if (ch === "\\" || (ch >= "\u0000" && ch <= "\u001f") || ch === "\u007f") return "_"; if (ch.length === 1 && ch >= "\ud800" && ch <= "\udfff") return "_"; return ch; }).join("")); const isInvalid = s => !s || s === "." || s === ".." || s === "/"; if (isInvalid(cleaned)) return null; let capped = cleaned; while (Buffer.byteLength(capped) > 200 && capped.length > 0) { capped = Array.from(capped).slice(0, -1).join(""); } if (isInvalid(capped)) return null; return capped; } module.exports = { sanitizeUploadFilename };