"use strict"; // Regression tests for the URL-uploader Esc + re-entrancy fixes (findings 7 & 8). // // Finding 7 — Esc destroyed the page underneath the dialog. The document // keydown chain in bot.js enumerated every stackable modal EXCEPT // urlUploaderModal, and the uploader opens on top of the Files page without // closing it (an .activity-modal at z-index 100000 over the .modal-overlay // pages at z-index 10000). Esc therefore matched the filesModal branch and // closed the whole Files page out from under the open dialog — whose close // button is titled "Close (Esc)" in bot.ejs and could never be discharged // with Esc. // // Finding 8 — double-submit and in-flight clobbering. startUrlUpload had no // re-entrancy guard: the input's Enter key reaches the handler directly (no // disabled button to stop it), the dialog lingers ~360 ms in the DOM during // its close animation, and nothing checked uploadBatchActive — so a second // Enter within that window re-POSTed /upload-url, a URL upload could start // over a running file batch (showProgressWheel() wiping its per-file progress // list), and the URL flow's failure path (hideProgressWheel → // closeProgressPopup → requestUploadCancel) aborted the batch's in-flight // XHR, leaving it running with no progress UI and no cancel affordance. The // reverse race existed too: a file batch started during a URL upload would // clobber the URL wheel, and the URL flow's completion path (setProgress(100) // → auto-hide → closeProgressPopup → requestUploadCancel) would abort the // batch. // // bot.js is a browser closure that cannot execute under Node, so — like the // other bot.js regression tests here — these pin the structural contract of // the fix: branch presence and ordering in the Esc chain, guard placement // inside startUrlUpload and uploadFilesSequential, the single shared flag, // and the CSS/animation mechanics the guards depend on. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const { gzipSync } = require("node:zlib"); const ROOT = path.join(__dirname, ".."); const BOT_JS = path.join(ROOT, "public", "js", "bot.js"); const BOT_EJS = path.join(ROOT, "views", "bot.ejs"); const BOT_CSS = path.join(ROOT, "public", "css", "bot.css"); const botSrc = fs.readFileSync(BOT_JS, "utf8"); const botEjs = fs.readFileSync(BOT_EJS, "utf8"); const botCss = fs.readFileSync(BOT_CSS, "utf8"); const PROGRESS_PREDICATE = "if (progressPopup && progressPopup.style.display === 'block') { closeProgressPopup(); return; }"; const ESC_UPLOADER_BRANCH = "if (urlUploaderModal && urlUploaderModal.classList.contains('show')) { closeUrlUploaderModal(); return; }"; function escapeChainWindow() { const at = botSrc.indexOf(PROGRESS_PREDICATE); assert.notStrictEqual(at, -1, "the Esc chain must still contain the progressPopup check"); const handlerStart = botSrc.lastIndexOf("if (e.key === 'Escape') {", at); assert.notStrictEqual(handlerStart, -1, "progressPopup check must live inside an Escape branch"); // Brace-match the whole Escape branch instead of slicing a fixed length: // a fixed slice would start failing spuriously once the chain grew long // enough to push its later branches past the cut. const open = botSrc.indexOf("{", handlerStart); let depth = 0; for (let i = open; i < botSrc.length; i++) { if (botSrc[i] === "{") depth++; else if (botSrc[i] === "}") { depth--; if (depth === 0) return botSrc.slice(handlerStart, i + 1); } } assert.fail("could not find the end of the Escape branch"); } function urlUploaderSection() { const start = botSrc.indexOf("// ============= URL Uploader ============="); assert.notStrictEqual(start, -1, "the URL Uploader section must still exist"); const end = botSrc.indexOf("// ============= /URL Uploader =============", start); assert.notStrictEqual(end, -1, "the URL Uploader section must still be terminated"); return botSrc.slice(start, end); } function startUrlUploadBody() { const section = urlUploaderSection(); const at = section.indexOf("async function startUrlUpload()"); assert.notStrictEqual(at, -1, "startUrlUpload must still exist"); const end = section.indexOf("if (urlUploaderBtn) {", at); assert.notStrictEqual(end, -1, "the URL-uploader bindings after startUrlUpload must still exist"); return section.slice(at, end); } function uploadFilesSequentialBody() { const at = botSrc.indexOf("async function uploadFilesSequential("); assert.notStrictEqual(at, -1, "uploadFilesSequential must still exist"); const end = botSrc.indexOf("function normalizeInput(raw)", at); assert.notStrictEqual(end, -1, "the function after uploadFilesSequential must still exist"); return botSrc.slice(at, end); } function functionBody(name, args) { const marker = `function ${name}(${args})`; const at = botSrc.indexOf(marker); assert.notStrictEqual(at, -1, `${name} must still exist`); // Brace-match the body: these functions contain nested blocks, so slicing // to the first '}' would truncate them. const open = botSrc.indexOf("{", at); let depth = 0; for (let i = open; i < botSrc.length; i++) { if (botSrc[i] === "{") depth++; else if (botSrc[i] === "}") { depth--; if (depth === 0) return botSrc.slice(at, i + 1); } } assert.fail(`could not find the end of ${name}`); } test("an upload refresh preserves a Files navigation that is still loading", async () => { assert.match(uploadFilesSequentialBody(), /\bloadExplorer\(\)/); const start = botSrc.indexOf("let explorerLoadGeneration = 0;"); const end = botSrc.indexOf("if (selectAllToggle)", start); assert.ok(start >= 0 && end > start); const requests = []; const rendered = []; const entriesEl = {}; const selected = new Set(["old/example.txt"]); let renameResets = 0; const noop = () => {}; const load = vm.runInNewContext(`let currentPath = "old"; ${botSrc.slice(start, end)}; loadExplorer;`, { apiExplore: (folder) => new Promise((resolve, reject) => requests.push({ folder, resolve, reject })), renderFileBreadcrumb: (folder) => rendered.push(folder), hasPerm: () => true, entriesEl, normalizeExplorerEntry: noop, compareExplorerEntries: noop, cancelActiveInlineRename: () => { renameResets++; }, clearSelection: () => selected.clear(), console: { error: noop }, escapeHtml: String, taskStartupSelect: null, }); const navigation = load("new"); const refresh = load(); assert.deepStrictEqual(requests.map(({ folder }) => folder), ["new", "new"]); requests[1].resolve({ path: "new" }); await refresh; assert.strictEqual(selected.size, 0); selected.add("new/example.txt"); requests[0].resolve({ path: "old" }); assert.strictEqual(await navigation, null); assert.deepStrictEqual(rendered, ["new"]); assert.strictEqual(selected.size, 1); assert.strictEqual(renameResets, 1); const unavailable = load("unavailable"); requests[2].reject(new Error("folder unavailable")); await unavailable; assert.match(entriesEl.innerHTML, /folder unavailable/); assert.strictEqual(selected.size, 0); assert.strictEqual(renameResets, 2); }); test("the browser checks per-file size but does not reject from a stale disk snapshot", () => { const validate = vm.runInNewContext(`${functionBody("validateUploadCandidate", "file")} validateUploadCandidate;`, { NODE_MAX_UPLOAD_BYTES: 1024, finiteUploadNumber: Number, formatBytes: String, SERVER_DISK_LIMIT_BYTES: 1024, SERVER_DISK_USED_BYTES: 1024, getKnownReplacementBytes: () => 0, }); assert.doesNotThrow(() => validate({ name: "same.txt", size: 1024 })); assert.throws(() => validate({ name: "same.txt", size: 1025 }), /max single-file upload size/); }); test("both mini uploaders require the latest destination listing to succeed", async () => { for (const [inputName, loadName, pathName, render] of [ ["miniFmUpload", "miniFmLatestLoad", "miniFmPath", "renderMiniFm"], ["imgViewerMiniFmUpload", "imgViewerLatestLoad", "imgViewerMiniFmPath", "renderImgViewerMiniFm"], ]) { const start = botSrc.indexOf(`if (${inputName}) {\n ${inputName}.addEventListener('change'`); const end = botSrc.indexOf("\n }", start); assert.ok(start >= 0 && end > start); const uploads = [], alerts = [], renders = []; let run; const input = { files: [{ name: "fixture.txt" }], value: "fixture.txt", addEventListener: (_, listener) => { run = listener; } }; const noop = () => {}; const context = { [inputName]: input, [loadName]: Promise.resolve(false), [pathName]: "old", [render]: (folder) => renders.push(folder), hasPerm: () => true, fileListHasDirectory: () => false, uploadBatchActive: false, urlUploadInFlight: false, popupClose: null, alert: (message) => alerts.push(message), apiUploadWithProgress: async (file, folder) => { uploads.push([file.name, folder]); }, showProgressWheel: noop, initUploadProgressList: noop, updateUploadProgressList: noop, setProgress: noop, loadExplorer: noop, scheduleProgressWheelHide: noop, flashFilesBar: noop, setTimeout: (callback) => callback(), }; vm.runInNewContext(`${uploadFilesSequentialBody()}\n${botSrc.slice(start, end + 4)}`, context); await run(); assert.deepStrictEqual(uploads, []); assert.deepStrictEqual(renders, []); assert.match(alerts[0], /Could not load the upload destination/); assert.strictEqual(input.value, ""); let finishStale; context[loadName] = new Promise((resolve) => { finishStale = resolve; }); const pending = run(); context[pathName] = "new"; context[loadName] = Promise.resolve(true); finishStale(false); await pending; assert.deepStrictEqual(uploads, [["fixture.txt", "new"]]); assert.deepStrictEqual(renders, ["new"]); } }); test("both Unarchive controls offer the daemon's supported archive suffixes", () => { const filter = botSrc.match(/const EXPLORER_ARCHIVE_EXTENSION = .*;/); assert.ok(filter); assert.strictEqual([...botSrc.matchAll(/EXPLORER_ARCHIVE_EXTENSION\.test\(/g)].length, 2); const supported = vm.runInNewContext(`${filter[0]} EXPLORER_ARCHIVE_EXTENSION;`); const daemonSrc = fs.readFileSync(path.join(ROOT, "main.go"), "utf8"); const detectArchiveType = daemonSrc.match(/^func detectArchiveType\(.*?^}/ms); assert.ok(detectArchiveType); const suffixes = [...detectArchiveType[0].matchAll(/strings\.HasSuffix\(l, "([^"]+)"\)/g)]; assert.ok(suffixes.length); for (const [, suffix] of suffixes) { assert.ok(supported.test(`example${suffix.toUpperCase()}`), suffix); } for (const suffix of [".bz2", ".gz", ".xz", ".jar", ".zip.txt"]) { assert.ok(!supported.test(`example${suffix}`), suffix); } }); test("SVG previews use an image data URL and reject oversized decoded content", async () => { const image = { removeAttribute: () => { image.src = undefined; } }; const classes = new Set(); const svg = ''; const show = vm.runInNewContext(`let imgViewerSvgRequest = null; async ${functionBody("showImgViewerImage", "rel")} showImgViewerImage;`, { imgViewerImage: image, imgViewerConfirm: null, imgViewerCanvas: { classList: { add: (name) => classes.add(name), remove: (...names) => names.forEach((name) => classes.delete(name)) }, }, IMG_VIEWER_SVG_LIMIT: 128, buildFileViewUrl: (name) => name, AbortController, Blob, TransformStream, DecompressionStream, fetch: async (name) => new Response(gzipSync(name === "valid.svgz" ? svg : " ".repeat(129))), FileReader: class { async readAsDataURL(blob) { this.result = `data:${blob.type};base64,${Buffer.from(await blob.arrayBuffer()).toString("base64")}`; this.onload(); } }, }); await show("valid.svgz"); assert.strictEqual(image.src, `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`); await show("large.svgz"); assert.strictEqual(image.src, undefined); assert.ok(classes.has("error")); }); // ---------- Finding 7: Esc must close the uploader, never the Files page ---------- test("Esc closes the URL uploader before any page it stacks above", () => { const chain = escapeChainWindow(); // The uploader is an .activity-modal (z-index 100000) opened on top of the // Files page (a .modal-overlay at z-index 10000) without closing it, so its // branch must sit after the other z-100000 overlays and before the // modal-overlay pages — editorModal and filesModal in particular. const order = [ ["progressPopup", PROGRESS_PREDICATE], ["imageViewerModal", "if (imageViewerModal && imageViewerModal.classList.contains('show')) { closeImageViewer(); return; }"], ["aiHelpModal", "if (aiHelpModal && isPageOpen(aiHelpModal)) { closeAiHelpModal(); return; }"], ["urlUploaderModal", ESC_UPLOADER_BRANCH], ["editorModal", "if (editorModal && editorModal.classList.contains('show')) { closeEditorModal(); return; }"], ["filesModal", "if (filesModal && isPageOpen(filesModal)) { closeFilesModal(); return; }"], ["taskModal", "if (taskModal && taskModal.classList.contains('show')) { closeTaskModal(); return; }"], ]; let prev = -1; for (const [name, predicate] of order) { const at = chain.indexOf(predicate); assert.notStrictEqual(at, -1, `the Esc chain must still handle ${name}`); assert.ok(at > prev, `${name} must be checked after the element before it (the uploader stacks above the pages, Esc must hit the dialog first)`); prev = at; } }); test("no pre-existing Esc handler was dropped by the insertion", () => { const chain = escapeChainWindow(); // closeInfoModal() is intentionally absent: the info modal (element, // declaration and open/close handlers) was removed from bot.ejs/bot.js, and // its leftover Esc branch referenced the now-undeclared infoModal // identifier — an uncaught ReferenceError on every Esc that reached it. for (const closer of [ "closeProgressPopup()", "closeImageViewer()", "closeAiHelpModal()", "closeUrlUploaderModal()", "closeEditorModal()", "closeFilesModal()", "closeTaskModal()", "closeModrinthPluginModal()", "closeStoreModal()", "closeActivityModal()", "closeBackupsModal()", "closeBackupCreateModal()", "closeResourceStatsPopup()", ]) { assert.ok(chain.includes(closer), `Esc chain lost a handler: ${closer}`); } }); test("the uploader's 'Close (Esc)' close button is discharged by the same closer Esc now routes to", () => { // The template promises Esc on the X button; that promise is only honest if // both the click binding and the keydown branch land on closeUrlUploaderModal. assert.ok( botEjs.includes('