misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Firefox and Waterfox: MDM takes the download before the browser's file dialog (part of #208) (#290)
Ahmed Nefzaoui29cc094aca28
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 57c19bbf..d696d692 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -962,6 +962,12 @@ choose. And Linux, checked on a real desktop with every change.#### The browser+- **Waterfox (and Firefox set to ask what to do with each file): the download stayed in the+ browser** ([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208)). Firefox's+ family hands an extension the download only after its *What should … do with this file?*+ dialog, by which time it has already downloaded the file behind the dialog. MDM now takes the+ download as the server's answer arrives, before the dialog: for a file MDM takes, the dialog+ never shows and the browser downloads nothing. Other files open the dialog as before.- A second browser download arriving while Download File Info was open replaced the first, whichwas lost (the browser had already given it up). They now wait their turn, and those stillwaiting when MDM quits are kept in the main queue (Download Later).diff --git a/ROADMAP.md b/ROADMAP.mdindex ac7c5adb..5edd51a4 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -96,6 +96,9 @@ Everything below ships together, in the next release.that decided, and the extension's button shows the last one. The extension from the Chrome WebStore needs this release (0.2.x serves only the copy in MDM's folder)([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208))+- ✅ Waterfox, and Firefox set to ask what to do with each file: MDM takes the download before+ the browser's *What should … do with this file?* dialog, which no longer shows for the files+ MDM takes ([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208))- ✅ More file types taken from the browser by default: DMG, PKG, DEB, RPM, APPIMAGE, MSIX, APPX,CAB, JAR, XZ, ZST, WEBM, FLAC, OPUS and others; a list never edited gains them([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208))diff --git a/docs/browser-integration.md b/docs/browser-integration.mdindex 67180ff6..e5d01303 100644--- a/docs/browser-integration.md+++ b/docs/browser-integration.md@@ -64,7 +64,7 @@ Both the address you clicked and the one its redirects led to are checked, so aWhen MDM takes a download, it gets the browser's file name, size and type with it, so **Download File Info** shows them at once without asking the server again. A download from a form (a button that posts and gets a file back) is posted again by MDM with the form's data; a form that sends a file stays with the browser.-When MDM takes a download, the browser's own copy is cancelled and removed from the browser's download list. **Download File Info** opens in MDM (unless you turned it off in **Options → Downloads**). Cancelling there doesn't hand the download back to the browser.+When MDM takes a download, the browser's own copy is cancelled and removed from the browser's download list. In Firefox and the browsers built on it (Waterfox, Zen, LibreWolf), MDM takes it as soon as the server answers, before the browser asks *What should … do with this file?*: for a file MDM takes, that question never shows (Waterfox asks it for every new type of file). Files MDM doesn't take get the question as before. **Download File Info** opens in MDM (unless you turned it off in **Options → Downloads**). Cancelling there doesn't hand the download back to the browser.<!-- steps -->diff --git a/extension/background.js b/extension/background.jsindex e8d6e112..f7a29350 100644--- a/extension/background.js+++ b/extension/background.js@@ -306,10 +306,6 @@ function excludedBy(r, url) {return "";}-function excluded(r, url) {- return excludedBy(r, url) !== "";-}-// ---- downloads left to the browser: why, for the popup and MDM's log (#208) ----------------// A host's refusal by Options names the rule (`declined`); one before #208 says it only in its@@ -355,6 +351,8 @@ async function noteLeft(why, name, url, incognito, told) {// app, with the same body (it can't be sent as a GET). Kept two minutes.const posts = new Map();const BODY_LIMIT = 512 * 1024;+// The Referer each page load was sent with, by request (Firefox, two minutes).+const referrers = new Map();function forget(map, ms) {const now = Date.now();@@ -402,12 +400,19 @@ if (ext.webRequest) {navigations,["requestBody"],);- // The Content-Type the form went with (a multipart boundary must stay the same).+ // The Content-Type the form went with (a multipart boundary must stay the same), and (Firefox)+ // the page a load came from, for a download caught from its answer (`headersReceived`).ext.webRequest.onBeforeSendHeaders.addListener((d) => {+ const header = (n) => (d.requestHeaders || []).find((h) => h.name.toLowerCase() === n);+ if (FIREFOX) {+ forget(referrers, 120000);+ const ref = header("referer");+ if (ref && ref.value) referrers.set(d.requestId, { url: ref.value, at: Date.now() });+ }if (d.method !== "POST") return;const p = posts.get(d.url);- const ct = (d.requestHeaders || []).find((h) => h.name.toLowerCase() === "content-type");+ const ct = header("content-type");if (p && p.id === d.requestId && ct && ct.value) p.type = ct.value;},navigations,@@ -1315,11 +1320,16 @@ if (!FIREFOX) {return true; // suggest() comes later});} else {- // Firefox names the file before the download is created and has no such pause: the download- // is paused at once when it may be the app's (the stored rules say so without asking), then- // cancelled or resumed; one that finished meanwhile (a small file) has its file removed.+ // Firefox names the file before the download is created and has no such pause. Most are+ // caught earlier, from the answer to the page load (`headersReceived`, below); the others (a+ // download started by a page's script, a type the answer didn't say) here: the download is+ // paused at once when it may be the app's, then cancelled or resumed; one that finished+ // meanwhile (a small file) has its file removed.+ // A page load decided from its answer already (`headersReceived`, #208) isn't asked again.ext.downloads.onCreated.addListener(async (item) => {const url = item.finalUrl || item.url;+ forget(decided, 120000);+ if (decided.has(url) || decided.has(firstUrl(item))) return;const c = await candidate(item, url).catch(() => null);if (!c || c.left) return leftAlone(c, item, url);const name = c.name;@@ -1340,8 +1350,8 @@ if (!FIREFOX) {// Options → General in the app: also take the listed types the browser shows or plays when a// link leads to one. Chromium: a session rule marks such answers as attachments, so they come-// down the download path above (where the rules and Alt apply). Firefox: the same by changing-// the answer's headers.+// down the download path above (where the rules and Alt apply). Firefox: taken from the answer+// as a download is (`headersReceived`), else it opens.const OPENED = {PDF: ["application/pdf"],MP3: ["audio/mpeg", "audio/mp3"],@@ -1431,28 +1441,119 @@ async function syncOpenedRule() {}}+// ---- Firefox: a download caught from its answer, before the browser's dialog (#208) ----------++// Firefox creates a download (downloads.onCreated, above) only once it has a file to save to:+// when it asks first ("What should Firefox do with this file?", which Waterfox always asks for+// a new type), only after the user answered, while it downloads the whole file behind the+// dialog. So a page load whose answer would be a download is caught as the answer arrives: the+// load waits while the app is asked, as Chromium's download does, and is cancelled when the app+// took it (no dialog, no browser download). Else it goes on as before, and the download it+// becomes is left to the browser (`decided`). A file the browser would show or play (a PDF, an+// MP3) is taken the same way when Options say so (`openedTypes`); else it opens.++// What Firefox shows or plays itself: a download only when its answer says "attachment".+const SHOWN = /^(text\/|image\/|video\/|audio\/|multipart\/|application\/(pdf|xhtml\+xml|xml|json|javascript|x-javascript|ecmascript|ogg|x-xpinstall|[\w.+-]+\+(xml|json))$)/;++// The file name a Content-Disposition gives (filename*=UTF-8''…, else filename="…"), or "".+function dispositionName(cd) {+ const star = /filename\*\s*=\s*([\w-]+)'[^']*'([^;]+)/i.exec(cd);+ if (star) {+ try {+ return decodeURIComponent(star[2].trim().replace(/^"|"$/g, ""));+ } catch {+ // Not percent-encoded as it says: the plain name below.+ }+ }+ const plain = /(?:^|;)\s*filename\s*=\s*("((?:[^"\\]|\\.)*)"|[^;]+)/i.exec(cd);+ if (!plain) return "";+ return (plain[2] !== undefined ? plain[2].replace(/\\(.)/g, "$1") : plain[1]).trim();+}++// {name, size, mime, opened} when this answer to a page load becomes a download (or is one of+// the files Options take though the browser would open them), else null: a page, a picture, a+// redirect, an error, a piece of a file.+function answerFile(d) {+ const code = d.statusCode || 0;+ if (code < 200 || code > 299 || code === 204 || code === 205 || code === 206) return null;+ const headers = d.responseHeaders || [];+ const get = (n) => ((headers.find((h) => h.name.toLowerCase() === n) || {}).value || "").trim();+ const mime = get("content-type").split(";")[0].trim().toLowerCase();+ const cd = get("content-disposition");+ const attachment = /^attachment/i.test(cd);+ const opened = !attachment && openedTypes.some((m) => mime.startsWith(m));+ // No type: the browser guesses from the bytes (a page, mostly); a download it becomes is+ // still seen by onCreated.+ if (!attachment && !opened && (!mime || SHOWN.test(mime))) return null;+ let name = dispositionName(cd);+ if (!name) {+ try {+ name = decodeURIComponent(pathOf(d.url).split("/").pop() || "");+ } catch {+ name = pathOf(d.url).split("/").pop() || "";+ }+ }+ name = name.split(/[\\/]/).pop() || "";+ // The size the file will have: the length of an answer that isn't compressed on the way.+ const size = get("content-encoding") ? 0 : Number(get("content-length")) || 0;+ return { name, size, mime, opened };+}++// The page loads decided here (by their first and last addresses, two minutes): the download+// one of them becomes after the browser's dialog is left to the browser (asked once).+const decided = new Map();++// A tab opened for the download only (a link opened in a new tab or window), closed with it.+async function closeDownloadTab(tabId, urls) {+ forget(newTabs, 10000);+ if (!(tabId >= 0) || !newTabs.has(tabId)) return;+ try {+ const tab = await ext.tabs.get(tabId);+ const at = tab.url || "";+ if (at === "about:blank" || urls.includes(at)) {+ newTabs.delete(tabId);+ await ext.tabs.remove(tabId);+ }+ } catch {+ // Closed already.+ }+}++async function headersReceived(d) {+ if (d.method !== "GET" && d.method !== "POST") return {};+ const file = answerFile(d);+ if (!file) return {};+ const ref = referrers.get(d.requestId);+ const item = {+ url: d.url,+ filename: file.name,+ totalBytes: file.size,+ fileSize: file.size,+ mime: file.mime,+ referrer: (ref && ref.url) || "",+ incognito: Boolean(d.incognito),+ cookieStoreId: d.cookieStoreId,+ };+ const first = firstUrl(item);+ forget(decided, 120000);+ decided.set(d.url, { at: Date.now() });+ decided.set(first, { at: Date.now() });+ const c = await candidate(item, d.url).catch(() => null);+ if (!c || c.left) {+ // A file the browser opens stays a page: there is no download to say anything about.+ if (!file.opened) leftAlone(c, item, d.url);+ return {};+ }+ const taken = await offer(item, d.url, c.name).catch(() => false);+ if (!taken) return {};+ closeDownloadTab(d.tabId, [first, d.url]).catch(() => {});+ return { cancel: true };+}+if (FIREFOX && ext.webRequest && ext.webRequest.onHeadersReceived) {ext.webRequest.onHeadersReceived.addListener(- (d) => {- const first = (redirected.get(d.url) || {}).from || d.url;- if (!openedTypes.length || bypass.has(d.url) || bypass.has(first)) return {};- if (rules && (excluded(rules, d.url) || excluded(rules, first))) return {};- const headers = d.responseHeaders || [];- const get = (n) => headers.find((h) => h.name.toLowerCase() === n);- const type = ((get("content-type") || {}).value || "").toLowerCase();- const cd = get("content-disposition");- if (!openedTypes.some((m) => type.startsWith(m)) || (cd && /^\s*attachment/i.test(cd.value))) return {};- // Under Options' minimum it would only go back to the browser as a download: it opens.- const size = Number((get("content-length") || {}).value) || 0;- if (rules && rules.minKb > 0 && size > 0 && size < rules.minKb * 1024) return {};- return {- responseHeaders: [- ...headers.filter((h) => h.name.toLowerCase() !== "content-disposition"),- { name: "Content-Disposition", value: "attachment" },- ],- };- },- { urls: ["<all_urls>"], types: ["main_frame"] },+ (d) => headersReceived(d).catch(() => ({})),+ { urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] },["blocking", "responseHeaders"],);}diff --git a/tools/extension/e2e.mjs b/tools/extension/e2e.mjsindex c2f00c81..9cc1e042 100644--- a/tools/extension/e2e.mjs+++ b/tools/extension/e2e.mjs@@ -9,7 +9,8 @@// cargo build --release -p mdm-app -p mdm-nmhost -p mdm-labserver; tools\extension\pack.ps1// node tools/extension/e2e.mjs [chrome] [brave] [edge] [firefox] [--only=case,case]//-// The cases (per browser): link (a .zip link, throttled and not), cookie (cookies and referrer+// The cases (per browser): link (a .zip link, throttled and not), ask (Firefox set to ask what to+// do with each new type, as Waterfox is: caught before its dialog, #208), cookie (cookies and referrer// forwarded), names (Content-Disposition), redirect, form (POST, 303), alt (Alt+click leaves it// to the browser), opened (a PDF or MP3 the browser would show or play), csp (the video button// under a strict CSP), hls (the stream a player loaded), streams (HLS and DASH players handed over@@ -1287,6 +1288,34 @@ const CASES = {return done.join(", ");},+ // #208: Firefox set to ask what to do with each new type (Waterfox's default): the download is+ // caught from the answer before the browser's "What should … do with this file?" dialog, which+ // never opens, and the browser doesn't download the file behind it. Firefox's family only.+ async ask(t) {+ if (!t.session.inBrowser) throw new Skip("Firefox's family only");+ const s = t.session;+ const always = JSON.stringify("browser.download.always_ask_before_handling_new_types");+ await s.inBrowser(`(Services.prefs.setBoolPref(${always}, true), "set")`);+ try {+ const file = `e2e-ask-${t.name}.zip`;+ const url = `/gen/2M/${file}?rate=512K`;+ const size = await sizeOf(LAB + url);+ await clickLink(t, url);+ await arrived(file, size);+ const dialog = await s.inBrowser(+ `[...Services.wm.getEnumerator(null)].some((w) => Boolean(w.document.getElementById("unknownContentTypeWindow")))`,+ );+ if (dialog) throw new Error("the browser's dialog opened");+ await keptNothing(t.dl);+ // The browser's own request (the first) was stopped before it had the file.+ const [own] = (await requests(`/gen/2M/${file}`)).filter((e) => e.method === "GET");+ if (!own || own.bytes_sent >= size) throw new Error(`the browser downloaded the file itself: ${own ? brief(own) : "no request"}`);+ return `no dialog, MDM has it, the browser's request stopped after ${own.bytes_sent} bytes`;+ } finally {+ await s.inBrowser(`(Services.prefs.clearUserPref(${always}), "set")`).catch(() => {});+ }+ },+// Cookies and referrer: a file behind a session cookie and hotlink protection.async cookie(t) {await t.session.navigate(`${LAB}/cookie?set=sid=1`);diff --git a/tools/extension/test.mjs b/tools/extension/test.mjsindex 866bbb56..0c6b4c0d 100644--- a/tools/extension/test.mjs+++ b/tools/extension/test.mjs@@ -1333,6 +1333,152 @@ const popupState = (listeners) =>ok("#208: refusal codes, the app's and the popup's, agree");}+// #208: Firefox (and Waterfox, which always asks first) creates a download only after its "What+// should … do with this file?" dialog, having downloaded the whole file behind it. The answer to+// the page load is caught before that instead: offered with its name (Content-Disposition), size,+// type and the page that linked it, then cancelled (no dialog, no browser download); the+// download it would still become is left alone, never asked twice.+const answer = (url, headers, more = {}) => ({+ requestId: "r1",+ url,+ method: "GET",+ type: "main_frame",+ tabId: 3,+ statusCode: 200,+ responseHeaders: Object.entries(headers).map(([name, value]) => ({ name, value })),+ ...more,+});+// The listener's answer, as a plain object (it is made in the sandbox).+const held = async (listeners, d) => JSON.parse(JSON.stringify(await listeners.headersReceived(d)));+const ask = (listeners) => (m, sender) => new Promise((r) => listeners.message(m, sender, r));+{+ const { api, calls, listeners } = fakeApi({ firefox: true });+ load(api, true);+ await settle();+ listeners.beforeSendHeaders({ requestId: "r1", method: "GET", url: "https://dl.test/get?id=1", requestHeaders: [{ name: "Referer", value: "https://site.test/page" }] });+ const res = await held(listeners,+ answer(+ "https://dl.test/get?id=1",+ {+ "Content-Type": "application/octet-stream",+ "Content-Disposition": "attachment; filename=\"fallback.zip\"; filename*=UTF-8''r%C3%A9sum%C3%A9%20v2.zip",+ "Content-Length": "4096",+ },+ { cookieStoreId: "firefox-container-3" },+ ),+ );+ assert.deepEqual(res, { cancel: true });+ const m = natives(calls)[0];+ assert.deepEqual(+ [m.url, m.filename, m.size, m.mime, m.referrer, m.cookies],+ ["https://dl.test/get?id=1", "résumé v2.zip", 4096, "application/octet-stream", "https://site.test/page", "sid=1"],+ );+ assert.deepEqual(calls.find((c) => c[0] === "cookies")[1], { url: "https://dl.test/get?id=1", storeId: "firefox-container-3" });+ // Were the browser to create the download all the same: left alone, not asked twice.+ listeners.created({ id: 30, url: "https://dl.test/get?id=1", filename: "C:\\dl\\résumé v2.zip" });+ await settle();+ assert.equal(natives(calls).length, 1);+ assert.deepEqual(steps(calls), []);+ ok("#208 Firefox: a download caught from its answer, before the browser's dialog");+}+// A type the app doesn't take: the browser goes on (its dialog shows), MDM's log hears why once,+// and the download after the dialog isn't paused or asked again.+{+ const { api, calls, listeners } = fakeApi({ firefox: true });+ load(api, true);+ await settle();+ const res = await held(listeners, answer("https://dl.test/data.xyz", { "Content-Type": "application/octet-stream", "Content-Disposition": "attachment" }));+ assert.deepEqual(res, {});+ listeners.created({ id: 31, url: "https://dl.test/data.xyz", filename: "C:\\dl\\data.xyz" });+ await settle();+ assert.deepEqual(natives(calls), []);+ assert.deepEqual(notices(calls), [{ why: "file-type", name: "data.xyz", site: "dl.test" }]);+ assert.deepEqual(steps(calls), []);+ ok("#208 Firefox: a type not taken goes on to the browser, said once");+}+// Pages, pictures, feeds, add-ons, redirects, pieces and errors are never held; an inline PDF+// opens when Options don't take the files the browser would open; a type the browser can't show+// is a download even without "attachment".+{+ const { api, calls, listeners } = fakeApi({ firefox: true, rules: { opened: false } });+ load(api, true);+ await settle();+ for (const [url, headers, more] of [+ ["https://x.test/", { "Content-Type": "text/html; charset=utf-8" }],+ ["https://x.test/p.png", { "Content-Type": "image/png" }],+ ["https://x.test/doc.pdf", { "Content-Type": "application/pdf" }],+ ["https://x.test/a.json", { "Content-Type": "application/json" }],+ ["https://x.test/feed", { "Content-Type": "application/rss+xml" }],+ ["https://x.test/addon.xpi", { "Content-Type": "application/x-xpinstall" }],+ ["https://x.test/old.zip", { "Content-Type": "application/zip", Location: "https://x.test/new.zip" }, { statusCode: 302 }],+ ["https://x.test/part.zip", { "Content-Type": "application/zip" }, { statusCode: 206 }],+ ["https://x.test/gone.zip", { "Content-Type": "application/zip" }, { statusCode: 404 }],+ ["https://x.test/untyped", {}],+ ]) {+ assert.deepEqual(await held(listeners, answer(url, headers, more)), {}, url);+ }+ assert.deepEqual(natives(calls), []);+ assert.deepEqual(notices(calls), []);+ assert.deepEqual(await held(listeners, answer("https://x.test/dl/setup.exe", { "Content-Type": "application/x-msdownload", "Content-Length": "10" })), { cancel: true });+ assert.equal(natives(calls)[0].filename, "setup.exe");+ ok("#208 Firefox: pages, pictures, redirects, inline PDFs untouched; an unshowable type taken");+}+// A PDF the browser would show is taken when Options say so; the app saying no lets the browser+// go on.+{+ const taken = fakeApi({ firefox: true });+ load(taken.api, true);+ await settle();+ assert.deepEqual(await held(taken.listeners, answer("https://x.test/doc.pdf", { "Content-Type": "application/pdf" })), { cancel: true });+ const refused = fakeApi({ firefox: true, reply: { ok: false } });+ load(refused.api, true);+ await settle();+ assert.deepEqual(await held(refused.listeners, answer("https://x.test/a.zip", { "Content-Type": "application/zip" })), {});+ assert.equal(natives(refused.calls).length, 1);+ ok("#208 Firefox: a PDF taken when Options say so; the app's no lets the browser go on");+}+// Alt held, Options' excluded sites, a file under the minimum size, a form that can't be posted+// again, paused: the browser keeps it, nothing asked.+{+ const { api, calls, listeners } = fakeApi({ firefox: true, rules: { excludedSites: "*.skip.test", minKb: 100 } });+ load(api, true);+ await settle();+ const send = ask(listeners);+ const zip = { "Content-Type": "application/zip" };+ await send({ type: "bypass", url: "https://x.test/alt.zip" }, { id: "ours", url: "https://x.test/", tab: { url: "https://x.test/" } });+ assert.deepEqual(await held(listeners, answer("https://x.test/alt.zip", zip)), {});+ assert.deepEqual(await held(listeners, answer("https://dl.skip.test/a.zip", zip)), {});+ assert.deepEqual(await held(listeners, answer("https://x.test/small.zip", { ...zip, "Content-Length": "2048" })), {});+ listeners.beforeRequest({ method: "POST", url: "https://x.test/upload", requestId: "p1", requestBody: { raw: [{ file: "C:\\f" }] } });+ const upload = answer("https://x.test/upload", { ...zip, "Content-Disposition": "attachment; filename=r.zip" }, { method: "POST", requestId: "p1" });+ assert.deepEqual(await held(listeners, upload), {});+ assert.deepEqual(natives(calls), []);+ await send({ type: "pause", paused: true }, { id: "ours", url: "chrome-extension://ours/popup.html" });+ assert.deepEqual(await held(listeners, answer("https://x.test/paused.zip", zip)), {});+ assert.deepEqual(natives(calls), []);+ ok("#208 Firefox: Alt, excluded sites, small files, file uploads and pause stay the browser's");+}+// A private window's download goes as one; a tab opened only for it closes with it.+{+ const { api, calls, listeners } = fakeApi({ firefox: true });+ load(api, true);+ await settle();+ listeners.tabCreated({ id: 12 });+ const res = await held(listeners, answer("https://x.test/p.zip", { "Content-Type": "application/zip" }, { incognito: true, tabId: 12 }));+ assert.deepEqual(res, { cancel: true });+ await settle();+ assert.equal(natives(calls)[0].private, true);+ assert.ok(calls.some((c) => c[0] === "closeTab" && c[1] === 12));+ ok("#208 Firefox: private stays private; a tab opened for the download closes");+}+// Chromium has its own pause (onDeterminingFilename): no answer is held there.+{+ const { api, listeners } = fakeApi({ firefox: false });+ load(api, false);+ await settle();+ assert.equal(listeners.headersReceived, undefined);+ ok("#208 Chromium: answers aren't held");+}// The manifests (#42): "proxy" optional in Firefox's, required in Chrome's (it can't be optional// there); the popup's switch: the permission in Firefox, the extension's own setting in Chrome.{