Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: harden browser downloads after #12832 (#12943)

Daniel Hana70b2a8f7b88
diff --git a/studio/frontend/src/features/browser/address.ts b/studio/frontend/src/features/browser/address.ts
index 5d0c210f78f..02b7a34c399 100644
--- a/studio/frontend/src/features/browser/address.ts
+++ b/studio/frontend/src/features/browser/address.ts
@@ -76,6 +76,11 @@ export function fileNameFromUrl(url: string): string {
}
}
+/** Bidi controls out, so `x\u202efdp.exe` can't read as `xexe.pdf` where it is shown or saved. */
+export function safeDownloadName(name: string): string {
+ return name.replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "_");
+}
+
export function hostOf(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, "");
diff --git a/studio/frontend/src/features/browser/dangerous-file-types.json b/studio/frontend/src/features/browser/dangerous-file-types.json
new file mode 100644
index 00000000000..cd2daa3f994
--- /dev/null
+++ b/studio/frontend/src/features/browser/dangerous-file-types.json
@@ -0,0 +1,154 @@
+{
+ "extensions": [
+ "action",
+ "app",
+ "appimage",
+ "appinstaller",
+ "applescript",
+ "application",
+ "appref-ms",
+ "appx",
+ "appxbundle",
+ "atloc",
+ "bash",
+ "bat",
+ "bgi",
+ "caction",
+ "cdr",
+ "chm",
+ "cmd",
+ "com",
+ "command",
+ "configprofile",
+ "cpl",
+ "csh",
+ "deb",
+ "definition",
+ "desktop",
+ "diagcab",
+ "diagcfg",
+ "diagpkg",
+ "dll",
+ "dmg",
+ "dmgpart",
+ "drv",
+ "dvdr",
+ "dylib",
+ "efi",
+ "exe",
+ "fileloc",
+ "ftploc",
+ "gadget",
+ "hlp",
+ "hta",
+ "img",
+ "imgpart",
+ "inetloc",
+ "inf",
+ "ins",
+ "iso",
+ "isp",
+ "jar",
+ "jnlp",
+ "job",
+ "js",
+ "jse",
+ "kext",
+ "ksh",
+ "library-ms",
+ "lnk",
+ "mmc",
+ "mobileconfig",
+ "mof",
+ "mpkg",
+ "msc",
+ "msh",
+ "msh1",
+ "msh1xml",
+ "msh2",
+ "msh2xml",
+ "mshxml",
+ "msi",
+ "msix",
+ "msixbundle",
+ "msp",
+ "msu",
+ "py",
+ "pyc",
+ "pyo",
+ "pyz",
+ "pyzw",
+ "pyw",
+ "docm",
+ "dotm",
+ "xlsm",
+ "xltm",
+ "xla",
+ "xlam",
+ "accde",
+ "accdr",
+ "mde",
+ "ade",
+ "xlsb",
+ "pptm",
+ "potm",
+ "ppsm",
+ "ppam",
+ "sldm",
+ "mst",
+ "ndif",
+ "ocx",
+ "osas",
+ "osax",
+ "pif",
+ "pkg",
+ "prefpane",
+ "ps1",
+ "ps1xml",
+ "ps2",
+ "ps2xml",
+ "psc1",
+ "psc2",
+ "psm1",
+ "reg",
+ "rpm",
+ "run",
+ "scf",
+ "scpt",
+ "scptd",
+ "scr",
+ "sct",
+ "search-ms",
+ "seplugin",
+ "service",
+ "settingcontent-ms",
+ "sh",
+ "shb",
+ "shs",
+ "sparsebundle",
+ "sparseimage",
+ "sys",
+ "terminal",
+ "toast",
+ "tool",
+ "udif",
+ "url",
+ "vbe",
+ "vbs",
+ "vhd",
+ "vhdx",
+ "webloc",
+ "website",
+ "wflow",
+ "workflow",
+ "ws",
+ "wsc",
+ "wsf",
+ "wsh",
+ "xbap",
+ "xip",
+ "xll",
+ "xnk",
+ "zsh"
+ ]
+}
diff --git a/studio/frontend/src/features/browser/download-approval-queue.ts b/studio/frontend/src/features/browser/download-approval-queue.ts
index a9874b04bee..2d6ed54e3e5 100644
--- a/studio/frontend/src/features/browser/download-approval-queue.ts
+++ b/studio/frontend/src/features/browser/download-approval-queue.ts
@@ -5,11 +5,19 @@
import { getLocale, translate } from "@/i18n";
import { toast } from "@/lib/toast";
import { create } from "zustand";
-import { hostOf, isWebUrl } from "./address";
+import { hostOf, isWebUrl, safeDownloadName } from "./address";
+import { isDangerousDownload } from "./download-safety";
import { useDownloadSitesStore } from "./download-sites-store";
import { useBrowserPrefsStore } from "./prefs-store";
-export type DownloadRequest = { origin: string; label: string; name: string; resolve: (allow: boolean) => void };
+/** `dangerous`: the file runs code when opened (download-safety.ts), so it asks whatever was remembered. */
+export type DownloadRequest = {
+ origin: string;
+ label: string;
+ name: string;
+ dangerous: boolean;
+ resolve: (allow: boolean) => void;
+};
export const useApprovalStore = create<{ queue: DownloadRequest[] }>(() => ({ queue: [] }));
@@ -26,6 +34,8 @@ export function downloadSiteOf(site: string): string {
/** Remembered answer for `site` (default: the file's address), else ask. Only web origins count: one answer for "" would cover blob:/data: everywhere. */
export function approveDownload(url: string, name: string, site: string = url): Promise<boolean> {
+ const shown = safeDownloadName(name);
+ const dangerous = isDangerousDownload(shown);
const origin = downloadSiteOf(site);
const label = (origin && hostOf(origin)) || hostOf(url) || url.slice(0, 80);
const remembered = origin ? useDownloadSitesStore.getState().sites[origin] : undefined;
@@ -33,9 +43,14 @@ export function approveDownload(url: string, name: string, site: string = url):
toast.error(translate("browser.downloadPrompt.blocked", { host: label }, getLocale()));
return Promise.resolve(false);
}
- if (remembered === "allow" || !useBrowserPrefsStore.getState().askBeforeDownloading) return Promise.resolve(true);
+ // A file that runs code always asks: a site's Always allow, or asking turned off, doesn't cover it.
+ if (!dangerous && (remembered === "allow" || !useBrowserPrefsStore.getState().askBeforeDownloading)) {
+ return Promise.resolve(true);
+ }
return new Promise((resolve) =>
- useApprovalStore.setState((state) => ({ queue: [...state.queue, { origin, label, name, resolve }] })),
+ useApprovalStore.setState((state) => ({
+ queue: [...state.queue, { origin, label, name: shown, dangerous, resolve }],
+ })),
);
}
@@ -45,7 +60,10 @@ export function answerDownload(request: DownloadRequest, allow: boolean, remembe
if (queue[0] !== request) return;
const kept = remember && request.origin !== "";
if (kept) useDownloadSitesStore.getState().setSite(request.origin, allow ? "allow" : "block");
- const answered = kept ? queue.filter((other) => other.origin === request.origin) : [request];
+ // A remembered Allow settles the site's other waiting files, except ones that run code: each of those asks.
+ const answered = kept
+ ? queue.filter((other) => other === request || (other.origin === request.origin && !(allow && other.dangerous)))
+ : [request];
useApprovalStore.setState({ queue: queue.filter((other) => !answered.includes(other)) });
for (const other of answered) other.resolve(allow);
}
diff --git a/studio/frontend/src/features/browser/download-approval.tsx b/studio/frontend/src/features/browser/download-approval.tsx
index 900fe64653f..f631b1f2f94 100644
--- a/studio/frontend/src/features/browser/download-approval.tsx
+++ b/studio/frontend/src/features/browser/download-approval.tsx
@@ -37,6 +37,11 @@ export function DownloadApprovalDialog() {
<AlertDialogDescription className="break-words">
{request ? t("browser.downloadPrompt.description", { host: request.label, name: request.name }) : null}
</AlertDialogDescription>
+ {request?.dangerous ? (
+ <p className="text-sm font-medium text-destructive">
+ {t("browser.downloadPrompt.dangerous", { host: request.label })}
+ </p>
+ ) : null}
</AlertDialogHeader>
{request?.origin ? (
<label htmlFor={checkboxId} className="flex cursor-pointer items-center gap-2 text-sm text-foreground">
diff --git a/studio/frontend/src/features/browser/download-safety.ts b/studio/frontend/src/features/browser/download-safety.ts
new file mode 100644
index 00000000000..8d4798bf736
--- /dev/null
+++ b/studio/frontend/src/features/browser/download-safety.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Files that run code when opened always ask before downloading, whatever a site's remembered answer or
+// the Ask before downloading setting.
+
+import policy from "./dangerous-file-types.json" with { type: "json" };
+
+const DANGEROUS = new Set<string>(policy.extensions);
+
+// native_file_dialogs.rs MAX_DOWNLOAD_NAME_BYTES.
+const MAX_NAME_BYTES = 240;
+const utf8 = new TextEncoder();
+const byteLength = (text: string) => utf8.encode(text).length;
+// Saved with a leading "_" (native_file_dialogs.rs WINDOWS_DEVICE_NAMES).
+const DEVICE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
+
+/** The name the desktop app saves it under (native_file_dialogs.rs `safe_download_name`): past 240 bytes it
+ * keeps an extension of at most 32 bytes, else cuts the end, so a long tail can leave `.exe` last. */
+function savedAs(name: string): string {
+ const shift = DEVICE.test(name.split(".")[0].trimEnd()) ? 1 : 0;
+ if (byteLength(name) + shift <= MAX_NAME_BYTES) return name;
+ const dot = name.lastIndexOf(".");
+ const extension = dot > 0 && byteLength(name.slice(dot)) <= 32 ? name.slice(dot) : "";
+ const room = MAX_NAME_BYTES - shift - byteLength(extension);
+ let stem = "";
+ let used = 0;
+ for (const char of name) {
+ used += byteLength(char);
+ if (used > room) break;
+ stem += char;
+ }
+ return stem + extension;
+}
+
+function runsCode(name: string): boolean {
+ const base = name.replace(/[. ]+$/, "");
+ const dot = base.lastIndexOf(".");
+ if (dot < 0) return false;
+ // A bare `.exe` still runs as one. Windows compares names upper-cased, so `.m\u017fi` (long s) is `.MSI`.
+ const extension = base.slice(dot + 1);
+ return DANGEROUS.has(extension.toLowerCase()) || DANGEROUS.has(extension.toUpperCase().toLowerCase());
+}
+
+/** As the desktop app cleans a name before the cut: controls, bidi controls and reserved characters become
+ * one-byte "_", trailing dots and spaces go. */
+function cleaned(name: string): string {
+ return name
+ .replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069/\\:*?"<>|]/g, "_")
+ .replace(/[. ]+$/, "");
+}
+
+/** Whether `name` runs code when opened, judged as the OS will (Windows drops trailing dots and spaces),
+ * both as given and as the desktop app shortens it. Its last path part and the whole name (separators as
+ * "_") are both judged: which one the app saves depends on where the name came from. */
+export function isDangerousDownload(name: string): boolean {
+ const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1);
+ return runsCode(base) || [base, name].some((candidate) => runsCode(savedAs(cleaned(candidate))));
+}
diff --git a/studio/frontend/src/features/browser/downloads.ts b/studio/frontend/src/features/browser/downloads.ts
index 526476819d1..b127bb22922 100644
--- a/studio/frontend/src/features/browser/downloads.ts
+++ b/studio/frontend/src/features/browser/downloads.ts
@@ -5,11 +5,12 @@ import { getLocale, translate } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { DownloadCancelledError, downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
-import { fileNameFromUrl, isWebUrl, withBaseUrl } from "./address";
+import { fileNameFromUrl, isWebUrl, safeDownloadName, withBaseUrl } from "./address";
import { type BrowserPage, fetchBrowserPage } from "./api";
import { approveDownload } from "./download-approval-queue";
+import { isDangerousDownload } from "./download-safety";
import { useBrowserHistoryStore } from "./history-store";
-import { saveNativeDownload } from "./native-downloads";
+import { type SavedNativeDownload, saveNativeDownload } from "./native-downloads";
import { useBrowserPrefsStore } from "./prefs-store";
export type BrowserDownload = { blob: Blob; name: string; contentType: string; url: string | null; site?: string };
@@ -45,7 +46,7 @@ async function pickSaveTarget(name: string): Promise<SaveHandle | null> {
const picker = saveFilePicker();
if (!picker || !asksWhereToSave()) return null;
try {
- return await picker({ suggestedName: name });
+ return await picker({ suggestedName: safeDownloadName(name) });
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") throw new DownloadCancelledError();
return null;
@@ -63,7 +64,7 @@ export async function saveBrowserDownload(download: BrowserDownload, target?: Sa
// A save dialog needs a fresh click; a late approval waits for a click on Save instead.
if (saveNeedsClick()) {
const locale = getLocale();
- toast(translate("browser.downloadPrompt.ready", { name: download.name }, locale), {
+ toast(translate("browser.downloadPrompt.ready", { name: safeDownloadName(download.name) }, locale), {
action: {
label: translate("browser.downloadPrompt.save", {}, locale),
onClick: () => void writeDownload(download, undefined),
@@ -75,11 +76,10 @@ export async function saveBrowserDownload(download: BrowserDownload, target?: Sa
await writeDownload(download, target);
}
-async function writeDownload(
- { blob, name, contentType, url }: BrowserDownload,
- target: SaveHandle | null | undefined,
-): Promise<void> {
- let saved: { id: string; name: string } | null = null;
+async function writeDownload(download: BrowserDownload, target: SaveHandle | null | undefined): Promise<void> {
+ const { blob, contentType, url } = download;
+ const name = safeDownloadName(download.name);
+ let saved: SavedNativeDownload | null = null;
let picked: SaveHandle | null = null;
try {
if (isTauri) {
@@ -107,6 +107,9 @@ async function writeDownload(
contentType,
nativeId: saved?.id,
});
+ if (saved?.marked === false) {
+ toast.warning(translate("browser.native.notMarked", { name: saved.name || name }, getLocale()));
+ }
}
// Well inside the ~5 s a click lets a page open the save dialog.
@@ -133,6 +136,7 @@ export async function saveLinkAs(url: string): Promise<void> {
// The dialog needs the menu click, which a slow fetch outlasts: ask with the resolved name
// when the fetch is quick, else with the URL's.
let target: SaveHandle | null | undefined;
+ let asked: string | undefined;
if (asksWhereToSave()) {
const quick = await Promise.race([
pending.then(
@@ -144,6 +148,7 @@ export async function saveLinkAs(url: string): Promise<void> {
// A link that already failed has nothing to save: report it without asking for a name.
if (quick && "error" in quick) throw quick.error;
const name = quick?.download.name ?? fileNameFromUrl(url);
+ asked = name;
try {
if (!(await approved(url, name))) throw new DownloadCancelledError();
target = await pickSaveTarget(name);
@@ -155,5 +160,10 @@ export async function saveLinkAs(url: string): Promise<void> {
throw error;
}
}
- await saveBrowserDownload(await pending, target);
+ const download = await pending;
+ // Approved under the address's name: a file that turns out to run code asks again, by its own name.
+ if (asked !== undefined && isDangerousDownload(download.name) && !isDangerousDownload(asked)) {
+ if (!(await approved(url, download.name))) return;
+ }
+ await saveBrowserDownload(download, target);
}
diff --git a/studio/frontend/src/features/browser/native-downloads.ts b/studio/frontend/src/features/browser/native-downloads.ts
index 8197fa021dd..6e65110226c 100644
--- a/studio/frontend/src/features/browser/native-downloads.ts
+++ b/studio/frontend/src/features/browser/native-downloads.ts
@@ -13,13 +13,17 @@ async function invoke<T>(command: string, args?: Record<string, unknown>): Promi
return core.invoke<T>(command, args);
}
+/** `marked` is false when the file couldn't be marked as downloaded from the internet (FAT, exFAT, some
+ * network drives), null when nothing marks it. */
+export type SavedNativeDownload = { id: string; name: string; marked: boolean | null };
+
/** Null if cancelled. A website file (`source`) is quarantine-marked so Gatekeeper/SmartScreen check it. */
export async function saveNativeDownload(
blob: Blob,
name: string,
ask: boolean,
source: string | null,
-): Promise<{ id: string; name: string } | null> {
+): Promise<SavedNativeDownload | null> {
const core = await import("@tauri-apps/api/core");
const headers: Record<string, string> = {
[NATIVE_FILE_NAME_HEADER]: encodeNativeFilename(name),
@@ -28,7 +32,7 @@ export async function saveNativeDownload(
// href is ASCII (punycode host, escaped path), as a header value must be.
const href = source && isWebUrl(source) ? safeHref(source) : null;
if (href) headers["x-unsloth-source"] = href;
- return core.invoke<{ id: string; name: string } | null>("browser_download_save", new Uint8Array(await blob.arrayBuffer()), {
+ return core.invoke<SavedNativeDownload | null>("browser_download_save", new Uint8Array(await blob.arrayBuffer()), {
headers,
});
}
diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.ts
index 2dd30c1a905..977e05e842d 100644
--- a/studio/frontend/src/features/browser/native-view.ts
+++ b/studio/frontend/src/features/browser/native-view.ts
@@ -50,6 +50,8 @@ type NativeEvent =
done: boolean;
success: boolean;
downloadId: string | null;
+ /** False when the file couldn't be marked as downloaded from the internet; null where nothing marks. */
+ marked?: boolean | null;
}
| { kind: "downloadPrompt"; tabId: string; url: string; site: string; name: string; id: string };
@@ -58,6 +60,9 @@ type Bounds = { x: number; y: number; width: number; height: number; viewportWid
const t = (key: TranslationKey, values?: InterpolationValues) => translate(key, values, getLocale());
const views = new Map<string, number>();
+// Tabs this page has opened a view for. A download from any other tab started under the account
+// signed in before the last reload (an account switch reloads), so it isn't this account's to list.
+const openedTabs = new Set<string>();
let recency: string[] = [];
const zooms = new Map<string, number>();
const icons = new Map<string, string>();
@@ -135,6 +140,11 @@ function onNativeEvent(event: NativeEvent): void {
onDownloadPrompt(event, tab);
return;
}
+ // A download outlives its page: it often lands after the tab closed or moved on, and still belongs in history.
+ if (event.kind === "download") {
+ if (openedTabs.has(event.tabId)) onDownload(event);
+ return;
+ }
if (!tab || currentEntry(tab).kind !== "web") return;
const history = useBrowserHistoryStore.getState();
switch (event.kind) {
@@ -191,22 +201,24 @@ function onNativeEvent(event: NativeEvent): void {
onClick: () => openExternalLink(event.url),
});
break;
- case "download":
- if (!event.done) {
- toast(t("browser.native.downloading", { name: event.name }));
- } else if (event.success) {
- history.recordDownload({
- name: event.name,
- url: event.url,
- size: event.size ?? 0,
- contentType: "",
- nativeId: event.downloadId ?? undefined,
- });
- toast.success(t("browser.native.downloaded", { name: event.name }));
- } else {
- toast.error(t("browser.native.downloadFailed", { name: event.name }));
- }
- break;
+ }
+}
+
+function onDownload(event: Extract<NativeEvent, { kind: "download" }>): void {
+ if (!event.done) {
+ toast(t("browser.native.downloading", { name: event.name }));
+ } else if (event.success) {
+ useBrowserHistoryStore.getState().recordDownload({
+ name: event.name,
+ url: event.url,
+ size: event.size ?? 0,
+ contentType: "",
+ nativeId: event.downloadId ?? undefined,
+ });
+ if (event.marked === false) toast.warning(t("browser.native.notMarked", { name: event.name }));
+ else toast.success(t("browser.native.downloaded", { name: event.name }));
+ } else {
+ toast.error(t("browser.native.downloadFailed", { name: event.name }));
}
}
@@ -470,6 +482,7 @@ async function applyView(desired: Desired): Promise<void> {
return true;
};
try {
+ openedTabs.add(tabId);
await call("browser_view_show", { tabId, url: resumed?.entry === entry ? resumed.url : url, bounds });
if (stale()) return;
clearSnapshot();
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 483cddc5875..de1b8db10a2 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -181,6 +181,7 @@ export const ar = {
downloadPrompt: {
title: "هل تريد تنزيل هذا الملف؟",
description: "يريد {host} حفظ {name} على جهاز الكمبيوتر.",
+ dangerous: "يمكن لملفات كهذه تشغيل برامج على جهازك. لا تنزّله إلا إذا كنت تثق في {host}.",
remember: "تذكّر للمرة القادمة",
cancel: "إلغاء",
download: "تنزيل",
@@ -368,6 +369,7 @@ export const ar = {
downloading: "جارٍ تنزيل {name}",
downloaded: "تم حفظ {name} في التنزيلات",
downloadFailed: "تعذّر تنزيل {name}",
+ notMarked: "تم حفظ {name} لكن تعذّر وسمه كملف منزّل من الإنترنت، لذا لن يحذّرك نظامك قبل فتحه.",
blocked: "لا يمكن فتح هذا العنوان في لوحة المتصفح. تفتح اللوحة المواقع العامة فقط.",
clearDataSettingDescription: "مسح سجل التصفح وسجل التنزيلات والصفحات المخزنة مؤقتًا وملفات تعريف الارتباط وبيانات المواقع، مما يسجّل خروجك من المواقع.",
clearDataDescription: "يمسح هذا سجل التصفح وسجل التنزيلات والصفحات المخزنة مؤقتًا وملفات تعريف الارتباط وبيانات المواقع، مما يسجّل خروجك من المواقع. تبقى الملفات المنزّلة على جهازك.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 2aa3de83a4d..d5c608d312f 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -181,6 +181,7 @@ export const de = {
downloadPrompt: {
title: "Diese Datei herunterladen?",
description: "{host} möchte {name} auf deinem Computer speichern.",
+ dangerous: "Dateien wie diese können Programme auf deinem Computer ausführen. Lade sie nur herunter, wenn du {host} vertraust.",
remember: "Für das nächste Mal merken",
cancel: "Abbrechen",
download: "Herunterladen",
@@ -368,6 +369,7 @@ export const de = {
downloading: "{name} wird heruntergeladen",
downloaded: "{name} in Downloads gespeichert",
downloadFailed: "{name} konnte nicht heruntergeladen werden",
+ notMarked: "{name} wurde gespeichert, konnte aber nicht als aus dem Internet heruntergeladen markiert werden. Dein System warnt deshalb vor dem Öffnen nicht.",
blocked: "Diese Adresse kann im Browserbereich nicht geöffnet werden. Er öffnet nur öffentliche Websites.",
clearDataSettingDescription: "Browserverlauf, Downloadverlauf, zwischengespeicherte Seiten sowie Cookies und Websitedaten löschen. Du wirst dabei von Websites abgemeldet.",
clearDataDescription: "Dadurch werden Browserverlauf, Downloadverlauf, zwischengespeicherte Seiten sowie Cookies und Websitedaten gelöscht, und du wirst von Websites abgemeldet. Heruntergeladene Dateien bleiben auf deinem Computer.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e0426989356..1f1fc12ab7d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -178,6 +178,7 @@ export const en = {
downloadPrompt: {
title: "Download this file?",
description: "{host} wants to save {name} to your computer.",
+ dangerous: "Files like this can run programs on your computer. Only download it if you trust {host}.",
remember: "Remember for next time",
cancel: "Cancel",
download: "Download",
@@ -365,6 +366,7 @@ export const en = {
downloading: "Downloading {name}",
downloaded: "Saved {name} to Downloads",
downloadFailed: "Couldn't download {name}",
+ notMarked: "{name} was saved but couldn't be marked as downloaded from the internet, so your system won't warn before opening it.",
blocked: "This address can't open in the browser panel. It only opens public websites.",
clearDataSettingDescription: "Clear browsing history, download history, cached pages, and the cookies and site data pages keep, which signs you out of sites.",
clearDataDescription: "This clears your browsing history, download history, cached pages, and site cookies and data, which signs you out of sites. Downloaded files stay on your computer.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index ce11e2aa862..27d93edcd5e 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -181,6 +181,7 @@ export const es = {
downloadPrompt: {
title: "¿Descargar este archivo?",
description: "{host} quiere guardar {name} en tu equipo.",
+ dangerous: "Archivos como este pueden ejecutar programas en tu equipo. Descárgalo solo si confías en {host}.",
remember: "Recordar para la próxima vez",
cancel: "Cancelar",
download: "Descargar",
@@ -368,6 +369,7 @@ export const es = {
downloading: "Descargando {name}",
downloaded: "{name} se guardó en Descargas",
downloadFailed: "No se pudo descargar {name}",
+ notMarked: "{name} se guardó, pero no se pudo marcar como descargado de internet, así que tu sistema no avisará antes de abrirlo.",
blocked: "Esta dirección no se puede abrir en el panel del navegador. Solo abre sitios web públicos.",
clearDataSettingDescription: "Borra el historial de navegación, el historial de descargas, las páginas en caché y las cookies y datos de sitios, lo que cierra tu sesión en los sitios.",
clearDataDescription: "Esto borra el historial de navegación, el historial de descargas, las páginas en caché y las cookies y datos de sitios, lo que cierra tu sesión en los sitios. Los archivos descargados se quedan en tu equipo.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index de51c244be2..66d5b8e84ab 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -181,6 +181,7 @@ export const fr = {
downloadPrompt: {
title: "Télécharger ce fichier ?",
description: "{host} souhaite enregistrer {name} sur votre ordinateur.",
+ dangerous: "Ce type de fichier peut exécuter des programmes sur votre ordinateur. Ne le téléchargez que si vous faites confiance à {host}.",
remember: "Se souvenir pour la prochaine fois",
cancel: "Annuler",
download: "Télécharger",
@@ -368,6 +369,7 @@ export const fr = {
downloading: "Téléchargement de {name}",
downloaded: "{name} enregistré dans Téléchargements",
downloadFailed: "Impossible de télécharger {name}",
+ notMarked: "{name} a été enregistré mais n'a pas pu être marqué comme téléchargé depuis Internet ; votre système n'avertira donc pas avant de l'ouvrir.",
blocked: "Cette adresse ne peut pas s'ouvrir dans le panneau du navigateur. Il n'ouvre que les sites web publics.",
clearDataSettingDescription: "Effacer l'historique de navigation, l'historique des téléchargements, les pages en cache ainsi que les cookies et données de sites, ce qui vous déconnecte des sites.",
clearDataDescription: "Cela efface l'historique de navigation, l'historique des téléchargements, les pages en cache ainsi que les cookies et données de sites, ce qui vous déconnecte des sites. Les fichiers téléchargés restent sur votre ordinateur.",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index e2709a1a2a7..5be15ff85f4 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -190,6 +190,7 @@ export const he = {
downloadPrompt: {
title: "להוריד את הקובץ הזה?",
description: "{host} רוצה לשמור את {name} במחשב שלכם.",
+ dangerous: "קבצים כאלה יכולים להריץ תוכנות במחשב שלך. הורד אותו רק אם אתה סומך על {host}.",
remember: "לזכור לפעם הבאה",
cancel: "ביטול",
download: "הורדה",
@@ -384,6 +385,7 @@ export const he = {
downloading: "מוריד את {name}",
downloaded: "{name} נשמר בהורדות",
downloadFailed: "הורדת {name} נכשלה",
+ notMarked: "{name} נשמר, אך לא ניתן היה לסמן אותו כקובץ שהורד מהאינטרנט, ולכן המערכת לא תזהיר לפני שתפתח אותו.",
blocked:
"לא ניתן לפתוח כתובת זו בחלונית הדפדפן. היא פותחת רק אתרים ציבוריים.",
clearDataSettingDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index f2ced12e34f..9ab3604d663 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -181,6 +181,7 @@ export const hi = {
downloadPrompt: {
title: "यह फ़ाइल डाउनलोड करें?",
description: "{host} आपके कंप्यूटर पर {name} सहेजना चाहता है।",
+ dangerous: "ऐसी फ़ाइलें आपके कंप्यूटर पर प्रोग्राम चला सकती हैं। इसे तभी डाउनलोड करें जब आप {host} पर भरोसा करते हों।",
remember: "अगली बार के लिए याद रखें",
cancel: "रद्द करें",
download: "डाउनलोड करें",
@@ -368,6 +369,7 @@ export const hi = {
downloading: "{name} डाउनलोड हो रहा है",
downloaded: "{name} डाउनलोड्स में सहेजा गया",
downloadFailed: "{name} डाउनलोड नहीं हो सका",
+ notMarked: "{name} सहेजा गया, लेकिन इसे इंटरनेट से डाउनलोड की गई फ़ाइल के रूप में चिह्नित नहीं किया जा सका, इसलिए खोलने से पहले आपका सिस्टम चेतावनी नहीं देगा।",
blocked: "यह पता ब्राउज़र पैनल में नहीं खुल सकता। यह केवल सार्वजनिक वेबसाइटें खोलता है।",
clearDataSettingDescription: "ब्राउज़िंग इतिहास, डाउनलोड इतिहास, कैश किए गए पेज और साइट कुकीज़ व डेटा साफ़ करें। इससे आप साइटों से साइन आउट हो जाएंगे।",
clearDataDescription: "इससे आपका ब्राउज़िंग इतिहास, डाउनलोड इतिहास, कैश किए गए पेज और साइट कुकीज़ व डेटा साफ़ हो जाते हैं, और आप साइटों से साइन आउट हो जाते हैं। डाउनलोड की गई फ़ाइलें आपके कंप्यूटर पर रहती हैं।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 20542ac7ff0..6acaa93b9b3 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -180,6 +180,7 @@ export const it = {
downloadPrompt: {
title: "Scaricare questo file?",
description: "{host} vuole salvare {name} sul tuo computer.",
+ dangerous: "File come questo possono eseguire programmi sul tuo computer. Scaricalo solo se ti fidi di {host}.",
remember: "Ricorda per la prossima volta",
cancel: "Annulla",
download: "Scarica",
@@ -367,6 +368,7 @@ export const it = {
downloading: "Download di {name} in corso",
downloaded: "{name} salvato in Download",
downloadFailed: "Impossibile scaricare {name}",
+ notMarked: "{name} è stato salvato ma non è stato possibile contrassegnarlo come scaricato da Internet, quindi il sistema non avviserà prima di aprirlo.",
blocked: "Questo indirizzo non si può aprire nel pannello del browser. Apre solo siti web pubblici.",
clearDataSettingDescription: "Cancella cronologia di navigazione, cronologia dei download, pagine in cache e cookie e dati dei siti, disconnettendoti dai siti.",
clearDataDescription: "Questo cancella cronologia di navigazione, cronologia dei download, pagine in cache e cookie e dati dei siti, disconnettendoti dai siti. I file scaricati restano sul computer.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 8201d4f7ff7..28191cd82fe 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -182,6 +182,7 @@ export const ja = {
downloadPrompt: {
title: "このファイルをダウンロードしますか?",
description: "{host} が {name} をこのコンピュータに保存しようとしています。",
+ dangerous: "このようなファイルはコンピューター上でプログラムを実行できます。{host} を信頼できる場合のみダウンロードしてください。",
remember: "次回から記憶する",
cancel: "キャンセル",
download: "ダウンロード",
@@ -369,6 +370,7 @@ export const ja = {
downloading: "{name} をダウンロード中",
downloaded: "{name} をダウンロードに保存しました",
downloadFailed: "{name} をダウンロードできませんでした",
+ notMarked: "{name} は保存されましたが、インターネットからダウンロードしたファイルとしてマークできなかったため、開く前にシステムの警告が表示されません。",
blocked: "このアドレスはブラウザパネルでは開けません。開けるのは公開ウェブサイトのみです。",
clearDataSettingDescription: "閲覧履歴、ダウンロード履歴、キャッシュされたページ、サイトの Cookie とデータを消去します。サイトからはログアウトされます。",
clearDataDescription: "閲覧履歴、ダウンロード履歴、キャッシュされたページ、サイトの Cookie とデータを消去し、サイトからログアウトします。ダウンロードしたファイルはコンピューターに残ります。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 947a3736b01..27ec7c08dbf 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -181,6 +181,7 @@ export const ko = {
downloadPrompt: {
title: "이 파일을 다운로드할까요?",
description: "{host}에서 {name}을(를) 컴퓨터에 저장하려고 합니다.",
+ dangerous: "이런 파일은 컴퓨터에서 프로그램을 실행할 수 있습니다. {host}을(를) 신뢰하는 경우에만 다운로드하세요.",
remember: "다음에도 기억",
cancel: "취소",
download: "다운로드",
@@ -368,6 +369,7 @@ export const ko = {
downloading: "{name} 다운로드 중",
downloaded: "{name}을(를) 다운로드 폴더에 저장했습니다",
downloadFailed: "{name}을(를) 다운로드할 수 없습니다",
+ notMarked: "{name}이(가) 저장되었지만 인터넷에서 다운로드한 파일로 표시하지 못해 열기 전에 시스템이 경고하지 않습니다.",
blocked: "이 주소는 브라우저 패널에서 열 수 없습니다. 공개 웹사이트만 열 수 있습니다.",
clearDataSettingDescription: "방문 기록, 다운로드 기록, 캐시된 페이지, 사이트 쿠키와 데이터를 삭제합니다. 사이트에서 로그아웃됩니다.",
clearDataDescription: "방문 기록, 다운로드 기록, 캐시된 페이지, 사이트 쿠키와 데이터를 삭제하며 사이트에서 로그아웃됩니다. 다운로드한 파일은 컴퓨터에 남아 있습니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index ffb2e473e6d..34f48eb515c 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -181,6 +181,7 @@ export const ptBR = {
downloadPrompt: {
title: "Baixar este arquivo?",
description: "{host} quer salvar {name} no seu computador.",
+ dangerous: "Arquivos como este podem executar programas no seu computador. Baixe-o apenas se confiar em {host}.",
remember: "Lembrar na próxima vez",
cancel: "Cancelar",
download: "Baixar",
@@ -368,6 +369,7 @@ export const ptBR = {
downloading: "Baixando {name}",
downloaded: "{name} salvo em Downloads",
downloadFailed: "Não foi possível baixar {name}",
+ notMarked: "{name} foi salvo, mas não pôde ser marcado como baixado da internet, então seu sistema não avisará antes de abri-lo.",
blocked: "Este endereço não pode ser aberto no painel do navegador. Ele só abre sites públicos.",
clearDataSettingDescription: "Limpa o histórico de navegação, o histórico de downloads, as páginas em cache e os cookies e dados de sites, o que encerra sua sessão nos sites.",
clearDataDescription: "Isso limpa o histórico de navegação, o histórico de downloads, as páginas em cache e os cookies e dados de sites, o que encerra sua sessão nos sites. Os arquivos baixados continuam no seu computador.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index c50ec49c2db..c758b21c685 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -181,6 +181,7 @@ export const ru = {
downloadPrompt: {
title: "Загрузить этот файл?",
description: "{host} хочет сохранить {name} на ваш компьютер.",
+ dangerous: "Такие файлы могут запускать программы на вашем компьютере. Скачивайте его, только если доверяете {host}.",
remember: "Запомнить на будущее",
cancel: "Отмена",
download: "Загрузить",
@@ -368,6 +369,7 @@ export const ru = {
downloading: "Загрузка {name}",
downloaded: "{name} сохранён в «Загрузки»",
downloadFailed: "Не удалось загрузить {name}",
+ notMarked: "{name} сохранён, но не удалось пометить его как загруженный из интернета, поэтому система не предупредит перед открытием.",
blocked: "Этот адрес нельзя открыть в панели браузера. Она открывает только общедоступные сайты.",
clearDataSettingDescription: "Очистить историю просмотров, историю загрузок, кэшированные страницы, а также файлы cookie и данные сайтов. Вы выйдете из аккаунтов на сайтах.",
clearDataDescription: "Будут очищены история просмотров, история загрузок, кэшированные страницы, а также файлы cookie и данные сайтов, и вы выйдете из аккаунтов на сайтах. Загруженные файлы останутся на компьютере.",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 10242022fb5..fd21b9bc853 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -192,6 +192,7 @@ export const sv = {
downloadPrompt: {
title: "Hämta den här filen?",
description: "{host} vill spara {name} på din dator.",
+ dangerous: "Filer som den här kan köra program på din dator. Ladda bara ned den om du litar på {host}.",
remember: "Kom ihåg till nästa gång",
cancel: "Avbryt",
download: "Hämta",
@@ -390,6 +391,7 @@ export const sv = {
downloading: "Hämtar {name}",
downloaded: "{name} sparades i Hämtade filer",
downloadFailed: "Det gick inte att hämta {name}",
+ notMarked: "{name} sparades men kunde inte markeras som nedladdad från internet, så systemet varnar inte innan den öppnas.",
blocked:
"Den här adressen kan inte öppnas i webbläsarpanelen. Den öppnar bara offentliga webbplatser.",
clearDataSettingDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 80b042f1310..063c18a4c69 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -181,6 +181,7 @@ export const zhCN = {
downloadPrompt: {
title: "要下载此文件吗?",
description: "{host} 想要将 {name} 保存到你的电脑。",
+ dangerous: "此类文件可以在你的电脑上运行程序。仅在你信任 {host} 时下载。",
remember: "下次记住",
cancel: "取消",
download: "下载",
@@ -368,6 +369,7 @@ export const zhCN = {
downloading: "正在下载 {name}",
downloaded: "已将 {name} 保存到“下载”",
downloadFailed: "无法下载 {name}",
+ notMarked: "{name} 已保存,但无法标记为从互联网下载,因此打开前系统不会发出警告。",
blocked: "此地址无法在浏览器面板中打开。面板只打开公开网站。",
clearDataSettingDescription: "清除浏览历史、下载历史、缓存的页面以及网站 Cookie 和数据,这会让你退出各网站。",
clearDataDescription: "这会清除浏览历史、下载历史、缓存的页面以及网站 Cookie 和数据,并让你退出各网站。已下载的文件会保留在你的电脑上。",
diff --git a/studio/frontend/tests/browser-native-view-snapshot.test.ts b/studio/frontend/tests/browser-native-view-snapshot.test.ts
index 0840471edc6..a64ee1970f4 100644
--- a/studio/frontend/tests/browser-native-view-snapshot.test.ts
+++ b/studio/frontend/tests/browser-native-view-snapshot.test.ts
@@ -188,3 +188,45 @@ test("toasts move left of a page that sits beside the Run settings panel", async
pageBox = rect(500, 100, 500, 600);
}
});
+
+test("a finished download is listed and reported after its tab closed, and warns when it isn't marked", async () => {
+ const stop = startNativeViews();
+ try {
+ useBrowserStore.getState().openUrl("https://example.org/", { newTab: true });
+ await frame();
+ const tabId = useBrowserStore.getState().activeTabId as string;
+ useBrowserStore.getState().closeTab(tabId);
+ await frame();
+ const seen: { level: string; message: string }[] = [];
+ const g = globalThis as {
+ nativeViewListener?: (event: { payload: unknown }) => void;
+ nativeViewSeen?: unknown;
+ };
+ g.nativeViewSeen = seen;
+ const done = {
+ kind: "download",
+ tabId,
+ url: "https://example.com/a.zip",
+ name: "a.zip",
+ path: null,
+ size: 3,
+ done: true,
+ success: true,
+ };
+ g.nativeViewListener?.({ payload: { ...done, downloadId: "d1", marked: true } });
+ g.nativeViewListener?.({ payload: { ...done, downloadId: "d2", marked: false } });
+ g.nativeViewListener?.({ payload: { ...done, downloadId: "d3", marked: null } });
+ // A tab this page never opened: the account signed in before the last reload (an account switch) started it.
+ g.nativeViewListener?.({ payload: { ...done, tabId: "tab-before-reload", downloadId: "d4", marked: true } });
+ assert.deepEqual(seen, [
+ { level: "history", message: "d1" },
+ { level: "success", message: "browser.native.downloaded" },
+ { level: "history", message: "d2" },
+ { level: "warning", message: "browser.native.notMarked" },
+ { level: "history", message: "d3" },
+ { level: "success", message: "browser.native.downloaded" },
+ ]);
+ } finally {
+ stop();
+ }
+});
diff --git a/studio/frontend/tests/browser-settings.test.ts b/studio/frontend/tests/browser-settings.test.ts
index 5ad8042a405..a0d635c82ed 100644
--- a/studio/frontend/tests/browser-settings.test.ts
+++ b/studio/frontend/tests/browser-settings.test.ts
@@ -315,6 +315,78 @@ test("a remembered answer settles the site's other waiting downloads", async ()
useDownloadSitesStore.getState().setSite("https://a.example", null);
});
+test("a file that runs code asks whatever the site's remembered answer or the ask setting", async () => {
+ const { approveDownload, answerDownload, useApprovalStore } = await import(
+ "../src/features/browser/download-approval-queue.ts"
+ );
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ useDownloadSitesStore.getState().setSite("https://c.example", "allow");
+ assert.equal(await approveDownload("https://c.example/notes.pdf", "notes.pdf"), true);
+ const setup = approveDownload("https://c.example/setup.exe", "setup.exe");
+ assert.deepEqual(
+ useApprovalStore.getState().queue.map(({ name, dangerous }) => [name, dangerous]),
+ [["setup.exe", true]],
+ );
+ answerDownload(useApprovalStore.getState().queue[0], false, false);
+ assert.equal(await setup, false);
+ useDownloadSitesStore.getState().setSite("https://c.example", null);
+
+ useBrowserPrefsStore.getState().setAskBeforeDownloading(false);
+ try {
+ assert.equal(await approveDownload("https://d.example/a.zip", "a.zip"), true);
+ // Bidi controls are shown as "_", so the name can't read as another type.
+ const disguised = approveDownload("https://d.example/x", "invoice\u202efdp.exe");
+ assert.equal(useApprovalStore.getState().queue[0]?.name, "invoice_fdp.exe");
+ answerDownload(useApprovalStore.getState().queue[0], true, false);
+ assert.equal(await disguised, true);
+ } finally {
+ useBrowserPrefsStore.getState().setAskBeforeDownloading(true);
+ }
+
+ // Remembering Allow on one file settles the site's other waiting files, except ones that run code.
+ const first = approveDownload("https://e.example/1.zip", "1.zip");
+ const tool = approveDownload("https://e.example/tool.msi", "tool.msi");
+ const second = approveDownload("https://e.example/2.zip", "2.zip");
+ answerDownload(useApprovalStore.getState().queue[0], true, true);
+ assert.equal(await first, true);
+ assert.equal(await second, true);
+ assert.deepEqual(
+ useApprovalStore.getState().queue.map(({ name }) => name),
+ ["tool.msi"],
+ );
+ // A later one still asks.
+ const later = approveDownload("https://e.example/run.bat", "run.bat");
+ assert.equal(useApprovalStore.getState().queue.length, 2);
+ answerDownload(useApprovalStore.getState().queue[0], true, false);
+ answerDownload(useApprovalStore.getState().queue[0], false, false);
+ assert.equal(await tool, true);
+ assert.equal(await later, false);
+ useDownloadSitesStore.getState().setSite("https://e.example", null);
+});
+
+test("files that run code are recognised however the name is cased, padded or pathed", async () => {
+ const { readFileSync } = await import("node:fs");
+ const { isDangerousDownload } = await import("../src/features/browser/download-safety.ts");
+ const fixture = JSON.parse(
+ readFileSync(new URL("./fixtures/dangerous-download-names.json", import.meta.url), "utf8"),
+ ) as { cases: { name: string; dangerous: boolean }[] };
+ assert.ok(fixture.cases.length > 50);
+ for (const { name, dangerous } of fixture.cases) assert.equal(isDangerousDownload(name), dangerous, name);
+ assert.equal(isDangerousDownload("C:\\Users\\a\\setup.exe"), true);
+ assert.equal(isDangerousDownload("dir.exe/readme.txt"), false);
+ // Saved names are cut to 240 bytes: a tail too long to keep as the extension is cut off, leaving .exe last.
+ assert.equal(isDangerousDownload(`${"a".repeat(236)}.exe${"x".repeat(40)}`), true);
+ assert.equal(isDangerousDownload(`${"a".repeat(300)}.txt`), false);
+ assert.equal(isDangerousDownload(`${"a".repeat(236)}.txt${"x".repeat(40)}`), false);
+ // A Windows device name gets a leading "_", which moves the cut by one byte.
+ assert.equal(isDangerousDownload(`con.${"a".repeat(231)}.exe${"x".repeat(40)}`), true);
+ assert.equal(isDangerousDownload(`cox.${"a".repeat(231)}.exe${"x".repeat(40)}`), false);
+ // A decoded "dir/" before the name: the desktop app may save only the last part, cut to end in .exe.
+ assert.equal(isDangerousDownload(`dir/${"a".repeat(236)}.exe${"x".repeat(40)}`), true);
+ // Controls are one-byte "_" when saved, so two-byte C1 controls move the cut.
+ assert.equal(isDangerousDownload(`${"\u0085".repeat(236)}.exe${"x".repeat(40)}`), true);
+});
+
test("download answers are kept per origin, never for every site", async () => {
const { downloadSiteOf: siteOf } = await import("../src/features/browser/download-approval-queue.ts");
// A blob: URL is its creator's; an opaque one, or data: and about:, belongs to no site.
@@ -371,7 +443,8 @@ test("a download whose click has expired waits for Save rather than skip the sav
prefs.setAskBeforeDownloading(false);
(globalThis as { __toasts?: unknown[] }).__toasts = [];
const blob = new Blob(["x"]);
- await saveBrowserDownload({ blob, name: "setup.dmg", contentType: "application/octet-stream", url: "https://a.example/setup.dmg" });
+ // Not a file that runs code: those ask first whatever the setting.
+ await saveBrowserDownload({ blob, name: "data.zip", contentType: "application/zip", url: "https://a.example/data.zip" });
const toasts = (globalThis as { __toasts?: { message: string; options?: { action?: { onClick: () => void } } }[] }).__toasts!;
assert.equal(toasts.length, 1);
assert.equal(toasts[0].message, "browser.downloadPrompt.ready");
@@ -379,7 +452,7 @@ test("a download whose click has expired waits for Save rather than skip the sav
active = true;
toasts[0].options!.action!.onClick();
await new Promise((resolve) => setTimeout(resolve, 20));
- assert.deepEqual(picked, ["setup.dmg"]);
+ assert.deepEqual(picked, ["data.zip"]);
assert.equal(written.length, 1);
prefs.setAskWhereToSave(false);
prefs.setAskBeforeDownloading(true);
@@ -417,6 +490,49 @@ test("a file a page sends the tab to is asked about for that page, not the file'
store.closeTab(tabId);
});
+test("Save link as asks again when the file it named by the address turns out to run code", async () => {
+ const { saveLinkAs } = await import("../src/features/browser/downloads.ts");
+ const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");
+ const prefs = useBrowserPrefsStore.getState();
+ prefs.setAskWhereToSave(true);
+ prefs.setAskBeforeDownloading(false);
+ const g = globalThis as { showSaveFilePicker?: unknown; __authFetch?: unknown };
+ // The picker fails without a cancel, so the save falls back to a plain download by the server's name.
+ g.showSaveFilePicker = async () => {
+ throw new DOMException("no picker here", "NotAllowedError");
+ };
+ // Slower than the wait before asking, so the address's name ("download") is the one approved first.
+ g.__authFetch = () =>
+ new Promise((resolve) =>
+ setTimeout(
+ () =>
+ resolve(
+ new Response(new Blob(["MZ"]), {
+ headers: { "Content-Type": "application/octet-stream", "X-Unsloth-Browser-Filename": "setup.exe" },
+ }),
+ ),
+ 1200,
+ ),
+ );
+ try {
+ const saving = saveLinkAs("https://a.example/download");
+ for (let i = 0; i < 40 && useApprovalStore.getState().queue.length === 0; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ const asked = useApprovalStore.getState().queue[0];
+ assert.equal(asked?.name, "setup.exe");
+ assert.equal(asked?.dangerous, true);
+ answerDownload(asked, false, false);
+ await saving;
+ assert.equal(useApprovalStore.getState().queue.length, 0);
+ } finally {
+ delete g.showSaveFilePicker;
+ delete g.__authFetch;
+ prefs.setAskWhereToSave(false);
+ prefs.setAskBeforeDownloading(true);
+ }
+});
+
test("a blocked site's blob: page can't download past the block", async () => {
const { approveDownload } = await import("../src/features/browser/download-approval-queue.ts");
const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
diff --git a/studio/frontend/tests/fixtures/dangerous-download-names.json b/studio/frontend/tests/fixtures/dangerous-download-names.json
new file mode 100644
index 00000000000..c683d965efb
--- /dev/null
+++ b/studio/frontend/tests/fixtures/dangerous-download-names.json
@@ -0,0 +1,304 @@
+{
+ "cases": [
+ {
+ "name": "setup.exe",
+ "dangerous": true
+ },
+ {
+ "name": "SETUP.EXE",
+ "dangerous": true
+ },
+ {
+ "name": "report.pdf",
+ "dangerous": false
+ },
+ {
+ "name": "report.pdf.exe",
+ "dangerous": true
+ },
+ {
+ "name": "installer.exe.",
+ "dangerous": true
+ },
+ {
+ "name": "installer.exe . ",
+ "dangerous": true
+ },
+ {
+ "name": "notes.txt",
+ "dangerous": false
+ },
+ {
+ "name": "archive.zip",
+ "dangerous": false
+ },
+ {
+ "name": "Tool.dmg",
+ "dangerous": true
+ },
+ {
+ "name": "run.command",
+ "dangerous": true
+ },
+ {
+ "name": "script.PS1",
+ "dangerous": true
+ },
+ {
+ "name": "photo.jpg",
+ "dangerous": false
+ },
+ {
+ "name": "x.App",
+ "dangerous": true
+ },
+ {
+ "name": "page.html",
+ "dangerous": false
+ },
+ {
+ "name": "data.json",
+ "dangerous": false
+ },
+ {
+ "name": "noext",
+ "dangerous": false
+ },
+ {
+ "name": ".bashrc",
+ "dangerous": false
+ },
+ {
+ "name": "deploy.sh",
+ "dangerous": true
+ },
+ {
+ "name": "lib.dylib",
+ "dangerous": true
+ },
+ {
+ "name": "shortcut.lnk",
+ "dangerous": true
+ },
+ {
+ "name": "link.url",
+ "dangerous": true
+ },
+ {
+ "name": "readme",
+ "dangerous": false
+ },
+ {
+ "name": "movie.mp4",
+ "dangerous": false
+ },
+ {
+ "name": "disk.iso",
+ "dangerous": true
+ },
+ {
+ "name": "",
+ "dangerous": false
+ },
+ {
+ "name": "invoice\u202etxt.exe",
+ "dangerous": true
+ },
+ {
+ "name": "invoice\u202eexe.txt",
+ "dangerous": false
+ },
+ {
+ "name": "setup.exe.txt",
+ "dangerous": false
+ },
+ {
+ "name": "archive.tar.gz",
+ "dangerous": false
+ },
+ {
+ "name": "x.app.zip",
+ "dangerous": false
+ },
+ {
+ "name": "x.exe ",
+ "dangerous": true
+ },
+ {
+ "name": "x.exe...",
+ "dangerous": true
+ },
+ {
+ "name": "x.exe . . ",
+ "dangerous": true
+ },
+ {
+ "name": "x.exe\u00a0",
+ "dangerous": false
+ },
+ {
+ "name": "a.txt:b.exe",
+ "dangerous": true
+ },
+ {
+ "name": "../x.exe",
+ "dangerous": true
+ },
+ {
+ "name": "C:\\x.exe",
+ "dangerous": true
+ },
+ {
+ "name": "dir/sub/x.dmg",
+ "dangerous": true
+ },
+ {
+ "name": ".exe",
+ "dangerous": true
+ },
+ {
+ "name": ".sh",
+ "dangerous": true
+ },
+ {
+ "name": "...",
+ "dangerous": false
+ },
+ {
+ "name": ". .",
+ "dangerous": false
+ },
+ {
+ "name": "x.\uff45\uff58\uff45",
+ "dangerous": false
+ },
+ {
+ "name": "x.\u212aext",
+ "dangerous": true
+ },
+ {
+ "name": "SETUP.ExE",
+ "dangerous": true
+ },
+ {
+ "name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.exe",
+ "dangerous": true
+ },
+ {
+ "name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf",
+ "dangerous": false
+ },
+ {
+ "name": "x.msc",
+ "dangerous": true
+ },
+ {
+ "name": "x.webloc",
+ "dangerous": true
+ },
+ {
+ "name": "x.appinstaller",
+ "dangerous": true
+ },
+ {
+ "name": "x.library-ms",
+ "dangerous": true
+ },
+ {
+ "name": "x.AppImage",
+ "dangerous": true
+ },
+ {
+ "name": "x.mobileconfig",
+ "dangerous": true
+ },
+ {
+ "name": "x.xll",
+ "dangerous": true
+ },
+ {
+ "name": "x.scf",
+ "dangerous": true
+ },
+ {
+ "name": "model.safetensors",
+ "dangerous": false
+ },
+ {
+ "name": "weights.gguf",
+ "dangerous": false
+ },
+ {
+ "name": "train.py",
+ "dangerous": true
+ },
+ {
+ "name": "notebook.ipynb",
+ "dangerous": false
+ },
+ {
+ "name": "config.ini",
+ "dangerous": false
+ },
+ {
+ "name": "report.docx",
+ "dangerous": false
+ },
+ {
+ "name": "sheet.xlsx",
+ "dangerous": false
+ },
+ {
+ "name": "page.mhtml",
+ "dangerous": false
+ },
+ {
+ "name": "data.csv",
+ "dangerous": false
+ },
+ {
+ "name": "x.dmg.part",
+ "dangerous": false
+ },
+ {
+ "name": "windows10.0-kb5005565-x64.msu",
+ "dangerous": true
+ },
+ {
+ "name": "tool.pyw",
+ "dangerous": true
+ },
+ {
+ "name": "report.DOCM",
+ "dangerous": true
+ },
+ {
+ "name": "budget.xlsm",
+ "dangerous": true
+ },
+ {
+ "name": "deck.pptm",
+ "dangerous": true
+ },
+ {
+ "name": "addin.xlam",
+ "dangerous": true
+ },
+ {
+ "name": "book.xlsb",
+ "dangerous": true
+ },
+ {
+ "name": "payload.m\u017fi",
+ "dangerous": true
+ },
+ {
+ "name": "addin.xla",
+ "dangerous": true
+ },
+ {
+ "name": "cache.pyc",
+ "dangerous": true
+ }
+ ]
+}
diff --git a/studio/frontend/tests/helpers/browser-store-resolver.mjs b/studio/frontend/tests/helpers/browser-store-resolver.mjs
index 6ea2e5e7bab..613bb6c1cfe 100644
--- a/studio/frontend/tests/helpers/browser-store-resolver.mjs
+++ b/studio/frontend/tests/helpers/browser-store-resolver.mjs
@@ -14,12 +14,16 @@ const TOAST_STUB =
"data:text/javascript," +
encodeURIComponent(
"const toast = (message, options) => void (globalThis.__toasts ??= []).push({ message, options });" +
- " toast.error = toast.success = toast; export { toast };",
+ " toast.error = toast.success = toast.warning = toast; export { toast };",
);
const AUTH_STUB =
"data:text/javascript," +
- encodeURIComponent("export const authFetch = () => { throw new Error(\"no network in tests\"); };");
+ encodeURIComponent(
+ "export const authFetch = (...args) => {" +
+ " if (globalThis.__authFetch) return globalThis.__authFetch(...args);" +
+ " throw new Error(\"no network in tests\"); };",
+ );
export function resolve(specifier, context, next) {
if (specifier === "@/features/auth") return { url: AUTH_STUB, shortCircuit: true };
diff --git a/studio/frontend/tests/helpers/native-view-resolver.mjs b/studio/frontend/tests/helpers/native-view-resolver.mjs
index 6f61ae35491..6c12218bc15 100644
--- a/studio/frontend/tests/helpers/native-view-resolver.mjs
+++ b/studio/frontend/tests/helpers/native-view-resolver.mjs
@@ -1,18 +1,22 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// register after browser-store-resolver.mjs and route Tauri calls through globalThis.nativeViewCall
+// register after browser-store-resolver.mjs and route Tauri calls through globalThis.nativeViewCall;
+// events reach globalThis.nativeViewListener, toasts and recorded downloads land in globalThis.nativeViewSeen
const stub = (source) => `data:text/javascript,${encodeURIComponent(source)}`;
const STUBS = {
- "@tauri-apps/api/event": stub("export const listen = async () => () => {};"),
+ "@tauri-apps/api/event": stub(
+ "export const listen = async (_name, callback) => { globalThis.nativeViewListener = callback; return () => {}; };",
+ ),
"@/i18n": stub(
"export const getLocale = () => 'en'; export const translate = (key) => key;",
),
"@/lib/open-link": stub("export const openExternalLink = () => {};"),
- "@/lib/toast": stub(
- "export const toast = Object.assign(() => {}, { success() {}, error() {} });",
- ),
+ "@/lib/toast": stub(`
+ const seen = (level) => (message) => void (globalThis.nativeViewSeen ??= []).push({ level, message });
+ export const toast = Object.assign(seen("info"), { success: seen("success"), error: seen("error"), warning: seen("warning") });
+ `),
"./native-support": stub(`
export const useNativeBrowser = { getState: () => ({ enabled: true }) };
export const callNative = (command, args) => globalThis.nativeViewCall(command, args);
@@ -26,7 +30,8 @@ const STUBS = {
"export const approveDownload = async () => false; export const downloadSiteOf = () => '';",
),
"./history-store": stub(
- "export const useBrowserHistoryStore = { getState: () => ({ recordVisit() {}, recordDownload() {} }) };",
+ "export const useBrowserHistoryStore = { getState: () => ({ recordVisit() {}," +
+ " recordDownload: (item) => void (globalThis.nativeViewSeen ??= []).push({ level: 'history', message: item.nativeId }) }) };",
),
};
diff --git a/studio/src-tauri/src/browser_downloads.rs b/studio/src-tauri/src/browser_downloads.rs
index 7acec46c92d..4dfb1cb36d5 100644
--- a/studio/src-tauri/src/browser_downloads.rs
+++ b/studio/src-tauri/src/browser_downloads.rs
@@ -66,6 +66,9 @@ pub fn new_browser_downloads() -> BrowserDownloads {
pub struct SavedDownload {
id: String,
name: String,
+ /// False when the internet mark couldn't be written (FAT, exFAT, some network drives): the panel
+ /// warns. None when nothing marks it (no web source, or Linux).
+ marked: Option<bool>,
}
#[derive(Serialize)]
@@ -204,9 +207,9 @@ pub async fn browser_download_save(
return Ok(None);
};
// Quarantined like a page download, so Gatekeeper or SmartScreen checks it.
- if let Some(source) = &source {
- crate::browser_webview::mark_downloaded(&path, source);
- }
+ let marked = source
+ .as_ref()
+ .and_then(|source| crate::browser_webview::mark_downloaded(&path, source));
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
@@ -214,6 +217,7 @@ pub async fn browser_download_save(
Ok(Some(SavedDownload {
id: record(&app, path),
name,
+ marked,
}))
}
@@ -438,11 +442,51 @@ pub(crate) fn add_pending<R: Runtime>(
});
}
-pub(crate) fn finished<R: Runtime>(app: &AppHandle<R>, staged: &Path, success: bool) {
+/// Windows and macOS file systems ignore case, so `Report.pdf` and `report.pdf` are one file.
+pub(crate) fn same_path(a: &Path, b: &Path) -> bool {
+ if cfg!(any(windows, target_os = "macos")) {
+ // Compared upper-cased as Windows does (`m\u{17f}i` is `MSI`); on Windows `\\?\C:\x` is
+ // `C:\x` and `\\?\UNC\h\s` is `\\h\s`.
+ let plain = |p: &Path| {
+ let text = p.to_string_lossy().to_uppercase();
+ if !cfg!(windows) {
+ text
+ } else if let Some(share) = text.strip_prefix(r"\\?\UNC\") {
+ format!(r"\\{share}")
+ } else if let Some(local) = text.strip_prefix(r"\\?\") {
+ local.to_string()
+ } else {
+ text
+ }
+ };
+ plain(a) == plain(b)
+ } else {
+ a == b
+ }
+}
+
+fn pending_for<'a>(
+ pending: &'a mut HashMap<String, Pending>,
+ candidates: &[Option<&Path>],
+) -> Option<(&'a String, &'a mut Pending)> {
+ pending.iter_mut().find(|(_, entry)| {
+ candidates
+ .iter()
+ .flatten()
+ .any(|candidate| same_path(&entry.staged, candidate))
+ })
+}
+
+/// `candidates`: the path reserved for the download, then the one the engine reported.
+pub(crate) fn finished<R: Runtime>(
+ app: &AppHandle<R>,
+ candidates: [Option<&Path>; 2],
+ success: bool,
+) {
let id = {
let state = app.state::<BrowserDownloads>();
let mut pending = state.pending.lock().unwrap();
- let Some((id, entry)) = pending.iter_mut().find(|(_, entry)| entry.staged == staged) else {
+ let Some((id, entry)) = pending_for(&mut pending, &candidates) else {
return;
};
entry.finished = Some(success);
@@ -517,12 +561,13 @@ fn settle<R: Runtime>(app: &AppHandle<R>, id: &str) {
let _ = fs::remove_dir_all(staging);
}
match result {
- Ok(Some((path, download_id))) => crate::browser_webview::emit_download_done(
+ Ok(Some((path, download_id, marked))) => crate::browser_webview::emit_download_done(
&app,
&entry.tab_id,
&entry.url,
&path,
Some(download_id),
+ marked,
),
Ok(None) => {}
Err(_) => crate::browser_webview::emit_download_failed(
@@ -540,7 +585,7 @@ async fn deliver<R: Runtime>(
app: &AppHandle<R>,
entry: &Pending,
ask: bool,
-) -> Result<Option<(PathBuf, String)>, String> {
+) -> Result<Option<(PathBuf, String, Option<bool>)>, String> {
let folder = download_folder(app)?;
let staged = entry.staged.clone();
let target = if ask {
@@ -568,15 +613,24 @@ async fn deliver<R: Runtime>(
blocking(move || {
let state = app.state::<BrowserDownloads>();
let _naming = state.naming.lock().unwrap();
- let target = crate::native_file_dialogs::unique_destination(&folder, &name)?;
- move_file(&staged, &target)?;
- Ok(target)
+ // A name another program took since it was picked is never replaced: pick again.
+ for _ in 0..3 {
+ let target = crate::native_file_dialogs::unique_destination(&folder, &name)?;
+ match place_new(&staged, &target) {
+ Ok(()) => return Ok(target),
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(error) => {
+ return Err(format!("Failed to save {}: {error}", target.display()))
+ }
+ }
+ }
+ Err(format!("Failed to save {name}: its name keeps being taken"))
})
.await?
};
- crate::browser_webview::mark_downloaded(&target, &entry.url);
+ let marked = crate::browser_webview::mark_downloaded(&target, &entry.url);
let id = record(app, target.clone());
- Ok(Some((target, id)))
+ Ok(Some((target, id, marked)))
}
/// A cross-volume copy can take minutes; keep it off the workers IPC and timers share.
@@ -588,6 +642,31 @@ async fn blocking<T: Send + 'static>(
.map_err(|error| format!("Failed to save the download: {error}"))?
}
+/// Put a staged download at a new name without ever replacing a file there: a hard link where the
+/// volume allows it (no copy, and AlreadyExists if the name was taken), else a copy that only lands
+/// while the name is still free.
+fn place_new(from: &Path, to: &Path) -> std::io::Result<()> {
+ match fs::hard_link(from, to) {
+ Ok(()) => {
+ let _ = fs::remove_file(from);
+ return Ok(());
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(error),
+ // Another volume (a chosen folder elsewhere) or no hard links (FAT, exFAT): copy.
+ Err(_) => {}
+ }
+ // Created like any new file (0666 less the umask on Unix), not a tempfile's 0600.
+ let mut temporary =
+ crate::native_file_dialogs::staged_temp_file(to).map_err(std::io::Error::other)?;
+ let mut source = fs::File::open(from)?;
+ std::io::copy(&mut source, temporary.as_file_mut())?;
+ temporary.as_file().sync_all()?;
+ temporary
+ .persist_noclobber(to)
+ .map(|_| ())
+ .map_err(|error| error.error)
+}
+
fn move_file(from: &Path, to: &Path) -> Result<(), String> {
if fs::rename(from, to).is_ok() {
return Ok(());
@@ -700,6 +779,66 @@ mod tests {
assert!(!from.exists());
}
+ #[test]
+ fn placing_a_download_never_replaces_a_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let from = dir.path().join("staged.exe");
+ let taken = dir.path().join("setup.exe");
+ fs::write(&from, b"new").unwrap();
+ fs::write(&taken, b"mine").unwrap();
+ let error = place_new(&from, &taken).unwrap_err();
+ assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
+ assert_eq!(fs::read(&taken).unwrap(), b"mine");
+ assert!(from.exists());
+ let free = dir.path().join("setup (1).exe");
+ place_new(&from, &free).unwrap();
+ assert_eq!(fs::read(&free).unwrap(), b"new");
+ assert!(!from.exists());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn a_verbatim_path_is_the_same_file() {
+ assert!(same_path(
+ Path::new(r"\\?\C:\Users\A\x.zip"),
+ Path::new(r"c:\users\a\X.zip")
+ ));
+ assert!(same_path(
+ Path::new(r"\\?\UNC\host\share\x.zip"),
+ Path::new(r"\\HOST\share\X.zip")
+ ));
+ assert!(same_path(
+ Path::new("C:\\d\\payload.m\u{17f}i"),
+ Path::new(r"C:\d\PAYLOAD.MSI")
+ ));
+ }
+
+ #[test]
+ fn a_finished_download_is_found_by_its_reserved_path() {
+ let mut pending = HashMap::new();
+ let staged = PathBuf::from("/cache/staging/a/Report.pdf");
+ pending.insert(
+ "a".to_string(),
+ Pending {
+ tab_id: "t".into(),
+ url: Url::parse("https://example.com/Report.pdf").unwrap(),
+ name: "Report.pdf".into(),
+ staged: staged.clone(),
+ decision: None,
+ finished: None,
+ },
+ );
+ // The engine reported no path (macOS) or another one: the reserved path still finds it.
+ let other = PathBuf::from("/elsewhere/x.pdf");
+ assert!(pending_for(&mut pending, &[Some(&staged), Some(&other)]).is_some());
+ assert!(pending_for(&mut pending, &[None, Some(&other)]).is_none());
+ let respelled = PathBuf::from("/cache/staging/a/report.pdf");
+ assert_eq!(
+ pending_for(&mut pending, &[None, Some(&respelled)]).is_some(),
+ cfg!(any(windows, target_os = "macos"))
+ );
+ }
+
#[test]
fn saved_lists_load_back_and_bad_ids_are_dropped() {
let dir = tempfile::tempdir().unwrap();
diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rs
index 09264b8fd48..19a547142c5 100644
--- a/studio/src-tauri/src/browser_webview.rs
+++ b/studio/src-tauri/src/browser_webview.rs
@@ -150,6 +150,8 @@ struct ViewsState {
urls: HashMap<String, String>,
/// Download paths by URL, oldest first (macOS doesn't report it back; one URL can download twice).
downloads: HashMap<String, Vec<PathBuf>>,
+ /// By URL, finishes that couldn't tell which of several reservations they were (`take_finished`).
+ unexplained_finishes: HashMap<String, usize>,
download_starts: HashMap<String, VecDeque<Instant>>,
polling: bool,
/** Tabs the reader muted; macOS mutes each page they load, Windows the view once. */
@@ -237,6 +239,8 @@ enum BrowserEvent {
success: bool,
/// A finished download's handle for Download history (browser_downloads.rs).
download_id: Option<String>,
+ /// Marked as from the internet: false if that failed (the panel warns), None where nothing marks.
+ marked: Option<bool>,
},
DownloadPrompt {
tab_id: String,
@@ -535,6 +539,7 @@ pub(crate) fn emit_download_done<R: Runtime>(
url: &Url,
path: &Path,
download_id: Option<String>,
+ marked: Option<bool>,
) {
emit(
app,
@@ -550,6 +555,7 @@ pub(crate) fn emit_download_done<R: Runtime>(
done: true,
success: true,
download_id,
+ marked,
},
);
}
@@ -571,6 +577,7 @@ pub(crate) fn emit_download_failed<R: Runtime>(
done: true,
success: false,
download_id: None,
+ marked: None,
},
);
}
@@ -710,8 +717,24 @@ fn download_destination(dir: &Path, suggested: &Path, reserved: &HashSet<&Path>)
.unwrap_or(candidate)
}
-/// Mark a download as from the internet, so Gatekeeper or SmartScreen checks it.
-pub(crate) fn mark_downloaded(path: &Path, url: &Url) {
+/// Where a download came from, for the file's internet mark: no credentials, query or fragment,
+/// which can carry tokens. Web addresses only.
+#[cfg_attr(not(windows), allow(dead_code))]
+fn sanitized_source(url: &Url) -> Option<String> {
+ if !matches!(url.scheme(), "http" | "https") {
+ return None;
+ }
+ let mut clean = url.clone();
+ let _ = clean.set_username("");
+ let _ = clean.set_password(None);
+ clean.set_query(None);
+ clean.set_fragment(None);
+ Some(clean.to_string())
+}
+
+/// Mark a download as from the internet, so Gatekeeper or SmartScreen checks it. Whether that
+/// worked (FAT, exFAT and some network drives keep no mark); None where there is no mark.
+pub(crate) fn mark_downloaded(path: &Path, url: &Url) -> Option<bool> {
#[cfg(target_os = "macos")]
{
use std::ffi::CString;
@@ -725,9 +748,10 @@ pub(crate) fn mark_downloaded(path: &Path, url: &Url) {
CString::new(path.as_os_str().as_bytes()),
CString::new("com.apple.quarantine"),
) else {
- return;
+ return Some(false);
};
- unsafe {
+ let _ = url;
+ let result = unsafe {
libc::setxattr(
path.as_ptr(),
name.as_ptr(),
@@ -735,21 +759,24 @@ pub(crate) fn mark_downloaded(path: &Path, url: &Url) {
value.len(),
0,
0,
- );
- }
- let _ = url;
+ )
+ };
+ Some(result == 0)
}
#[cfg(windows)]
{
let mut stream = path.as_os_str().to_owned();
stream.push(":Zone.Identifier");
- let _ = std::fs::write(
- stream,
- format!("[ZoneTransfer]\r\nZoneId=3\r\nHostUrl={url}\r\n"),
- );
+ let host = sanitized_source(url)
+ .map(|source| format!("HostUrl={source}\r\n"))
+ .unwrap_or_default();
+ Some(std::fs::write(stream, format!("[ZoneTransfer]\r\nZoneId=3\r\n{host}")).is_ok())
}
#[cfg(not(any(target_os = "macos", windows)))]
- let _ = (path, url);
+ {
+ let _ = (path, url);
+ None
+ }
}
#[cfg(target_os = "macos")]
@@ -1092,22 +1119,33 @@ fn create_view<R: Runtime>(
true
}
DownloadEvent::Finished { url, path, success } => {
- let recorded = {
+ let (recorded, retired) = {
let state = app.state::<BrowserViews>();
let mut inner = state.inner.lock().unwrap();
- let pending = inner.downloads.entry(url.to_string()).or_default();
- let index = path
- .as_ref()
- .and_then(|path| pending.iter().position(|p| p == path))
- .unwrap_or(0);
- let recorded = (index < pending.len()).then(|| pending.remove(index));
+ let ViewsState {
+ downloads,
+ unexplained_finishes,
+ ..
+ } = &mut *inner;
+ let key = url.to_string();
+ let mut unexplained = unexplained_finishes.remove(&key).unwrap_or(0);
+ let pending = downloads.entry(key.clone()).or_default();
+ let taken = take_finished(pending, &mut unexplained, path.as_deref());
if pending.is_empty() {
- inner.downloads.remove(url.as_str());
+ downloads.remove(&key);
+ } else if unexplained > 0 {
+ unexplained_finishes.insert(key, unexplained);
}
- recorded
+ taken
};
- if let Some(staged) = path.or(recorded) {
- crate::browser_downloads::finished(app, &staged, success);
+ // The reserved path first: the engine may report another spelling of it.
+ crate::browser_downloads::finished(
+ app,
+ [recorded.as_deref(), path.as_deref()],
+ success,
+ );
+ for staged in retired {
+ crate::browser_downloads::finished(app, [Some(&staged), None], false);
}
true
}
@@ -1725,10 +1763,104 @@ fn platform_clear(platform: tauri::webview::PlatformWebview, finish: ClearFinish
}
}
+/// The reservation a finished download of one URL settles, and any it retires. No path: the first on
+/// macOS, which reports none and runs downloads of one URL in turn. Elsewhere a missing path (WebView2
+/// sends none for a failed download) or one matching none stands for the sole reservation only, else
+/// settling one of several would hand it another download's result. Such a finish is counted instead:
+/// once every other download has finished, the reservations left are exactly the counted ones, and
+/// they are retired as failed so none holds a download slot or waits forever.
+fn take_finished(
+ pending: &mut Vec<PathBuf>,
+ unexplained: &mut usize,
+ path: Option<&Path>,
+) -> (Option<PathBuf>, Vec<PathBuf>) {
+ let sole = (pending.len() == 1).then_some(0);
+ let index = match path {
+ None if cfg!(target_os = "macos") => Some(0),
+ None => sole,
+ Some(path) => pending
+ .iter()
+ .position(|p| crate::browser_downloads::same_path(p, path))
+ .or(sole),
+ };
+ let recorded = match index.filter(|&index| index < pending.len()) {
+ Some(index) => Some(pending.remove(index)),
+ None => {
+ if !pending.is_empty() {
+ *unexplained += 1;
+ }
+ None
+ }
+ };
+ let mut retired = Vec::new();
+ if *unexplained > 0 && pending.len() <= *unexplained {
+ retired = std::mem::take(pending);
+ *unexplained = 0;
+ }
+ (recorded, retired)
+}
+
#[cfg(test)]
mod tests {
+ #[test]
+ fn a_finished_path_matching_no_reservation_settles_only_a_sole_one() {
+ let (a, b) = (PathBuf::from("/s/a.zip"), PathBuf::from("/s/b.zip"));
+ let mut n = 0;
+ let mut two = vec![a.clone(), b.clone()];
+ let found = take_finished(&mut two, &mut n, Some(Path::new("/s/b.zip")));
+ assert_eq!(found, (Some(b.clone()), vec![]));
+ let mut two = vec![a.clone(), b.clone()];
+ assert_eq!(
+ take_finished(&mut two, &mut n, Some(Path::new("/elsewhere"))),
+ (None, vec![])
+ );
+ assert_eq!((two.len(), n), (2, 1));
+ // The other one finishes: the one left is the unexplained finish, retired as failed.
+ assert_eq!(
+ take_finished(&mut two, &mut n, Some(Path::new("/s/b.zip"))),
+ (Some(b.clone()), vec![a.clone()])
+ );
+ assert_eq!((two.len(), n), (0, 0));
+ let mut one = vec![b.clone()];
+ assert_eq!(
+ take_finished(&mut one, &mut n, Some(Path::new("/elsewhere"))),
+ (Some(b.clone()), vec![])
+ );
+ assert_eq!(take_finished(&mut Vec::new(), &mut n, None), (None, vec![]));
+ assert_eq!(n, 0);
+ }
+
+ #[test]
+ fn a_finish_without_a_path_takes_the_first_only_where_downloads_run_in_turn() {
+ let (a, b) = (PathBuf::from("/s/a.zip"), PathBuf::from("/s/b.zip"));
+ let mut n = 0;
+ let mut two = vec![a.clone(), b.clone()];
+ if cfg!(target_os = "macos") {
+ assert_eq!(take_finished(&mut two, &mut n, None), (Some(a), vec![]));
+ return;
+ }
+ // WebView2: a failed download reports no path. Which one is unknown until the other ends.
+ assert_eq!(take_finished(&mut two, &mut n, None), (None, vec![]));
+ assert_eq!(
+ take_finished(&mut two, &mut n, Some(Path::new("/s/a.zip"))),
+ (Some(a), vec![b])
+ );
+ let mut one = vec![PathBuf::from("/s/c.zip")];
+ assert!(take_finished(&mut one, &mut n, None).0.is_some());
+ }
+
use super::*;
+ #[test]
+ fn the_internet_mark_keeps_where_not_secrets() {
+ let source = |url: &str| sanitized_source(&Url::parse(url).unwrap());
+ assert_eq!(
+ source("https://user:[email protected]:8443/f/a.exe?sig=secret#x").as_deref(),
+ Some("https://example.com:8443/f/a.exe")
+ );
+ assert_eq!(source("file:///etc/passwd"), None);
+ }
+
mod url_poll {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index ff2f5ae7428..0b5d2eda405 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -582,12 +582,20 @@ const WINDOWS_DEVICE_NAMES: [&str; 22] = [
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
+fn is_bidi_control(c: char) -> bool {
+ matches!(
+ c,
+ '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
+ )
+}
+
/// A website's file name made safe everywhere: no separators, control or reserved characters, trailing dots/spaces or device names; length capped.
pub(crate) fn safe_download_name(name: &str) -> String {
let mut name: String = name
.chars()
.map(|c| {
- if c.is_control() || "/\\:*?\"<>|".contains(c) {
+ // Bidi controls too: `invoice\u{202e}fdp.exe` must not read as `invoiceexe.pdf`.
+ if c.is_control() || is_bidi_control(c) || "/\\:*?\"<>|".contains(c) {
'_'
} else {
c
@@ -1105,6 +1113,11 @@ mod tests {
"a_b_c_d_e_f_g.txt"
);
assert_eq!(safe_download_name("evil\u{7}name.sh"), "evil_name.sh");
+ assert_eq!(
+ safe_download_name("invoice\u{202e}fdp.exe"),
+ "invoice_fdp.exe"
+ );
+ assert_eq!(safe_download_name("a\u{2066}b\u{061c}.txt"), "a_b_.txt");
assert_eq!(safe_download_name("CON"), "_CON");
assert_eq!(safe_download_name("nul.tar.gz"), "_nul.tar.gz");
assert_eq!(safe_download_name("console.log"), "console.log");