From 3a000c7bfc2639a3cfdcc819536e0cad4b77c6c6 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 15 Jul 2026 11:49:28 -0500 Subject: [PATCH] make download names smarter --- .../fix-attachment-download-filenames.md | 5 ++ src/app/components/Pdf-viewer/PdfViewer.tsx | 3 +- .../components/image-viewer/ImageViewer.tsx | 6 ++- src/app/components/message/FileHeader.tsx | 3 +- .../components/message/MsgTypeRenderers.tsx | 16 ++++--- .../message/content/FileContent.tsx | 5 +- .../message/content/ImageContent.tsx | 4 ++ src/app/utils/download.ts | 46 +++++++++++++++++++ 8 files changed, 75 insertions(+), 13 deletions(-) create mode 100644 .changeset/fix-attachment-download-filenames.md create mode 100644 src/app/utils/download.ts diff --git a/.changeset/fix-attachment-download-filenames.md b/.changeset/fix-attachment-download-filenames.md new file mode 100644 index 000000000..04cc4dbe8 --- /dev/null +++ b/.changeset/fix-attachment-download-filenames.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Use attachment filenames instead of captions when downloading files and harden unsafe download names. diff --git a/src/app/components/Pdf-viewer/PdfViewer.tsx b/src/app/components/Pdf-viewer/PdfViewer.tsx index 00cba56fc..d3cddbae2 100644 --- a/src/app/components/Pdf-viewer/PdfViewer.tsx +++ b/src/app/components/Pdf-viewer/PdfViewer.tsx @@ -29,6 +29,7 @@ import { } from '$components/icons/phosphor'; import FocusTrap from 'focus-trap-react'; import FileSaver from 'file-saver'; +import { getDownloadFilename } from '$utils/download'; import { AsyncStatus } from '$hooks/useAsyncCallback'; import { useImageGestures } from '$hooks/useImageGestures'; import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '$plugins/pdfjs-dist'; @@ -90,7 +91,7 @@ export const PdfViewer = as<'div', PdfViewerProps>( }, [docState, pageNo, zoom]); const handleDownload = () => { - FileSaver.saveAs(src, name); + FileSaver.saveAs(src, getDownloadFilename(name, undefined, 'document.pdf')); }; const handleJumpSubmit: FormEventHandler = (evt) => { diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index 9e969f98b..55df2294b 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -37,16 +37,18 @@ import { CheckerboardIcon, CopyIcon, DownloadIcon } from '@phosphor-icons/react' import FocusTrap from 'focus-trap-react'; import { stopPropagation } from '$utils/keyboard'; import { copyImageToClipboard } from '$utils/dom'; +import { getDownloadFilename } from '$utils/download'; export type ImageViewerProps = { alt: string; + filename?: string; src: string; requestClose: () => void; info?: IImageInfo; }; export const ImageViewer = as<'div', ImageViewerProps>( - ({ className, alt, src, requestClose, info, ...props }, ref) => { + ({ className, alt, filename, src, requestClose, info, ...props }, ref) => { const zoomInputRef = useRef(null); const [pixelatedImageRendering] = useSetting(settingsAtom, 'pixelatedImageRendering'); @@ -98,7 +100,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( const handleDownload = async () => { const fileContent = await downloadMedia(src); - FileSaver.saveAs(fileContent, alt); + FileSaver.saveAs(fileContent, getDownloadFilename(filename, alt, 'image')); }; const [menuAnchor, setMenuAnchor] = useState(); diff --git a/src/app/components/message/FileHeader.tsx b/src/app/components/message/FileHeader.tsx index 03473b22c..b7cc7fc77 100644 --- a/src/app/components/message/FileHeader.tsx +++ b/src/app/components/message/FileHeader.tsx @@ -9,6 +9,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix'; +import { getDownloadFilename } from '$utils/download'; const badgeStyles = { maxWidth: toRem(100) }; @@ -31,7 +32,7 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow : await downloadMedia(mediaUrl); const fileURL = URL.createObjectURL(fileContent); - FileSaver.saveAs(fileURL, filename); + FileSaver.saveAs(fileURL, getDownloadFilename(filename)); return fileURL; }, [mx, url, useAuthentication, mimeType, encInfo, filename]) ); diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index eb686aa07..135aa66cd 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -37,6 +37,7 @@ import { unwrapForwardedContent } from './modals/MessageForward'; import { LINKINPUTREGEX } from '$components/editor'; import { MATRIX_TO_BASE } from '$plugins/matrix-to'; import { copyToClipboard } from '$utils/dom'; +import { getAttachmentFilename } from '$utils/download'; import { MapContainer, Marker, TileLayer } from 'react-leaflet'; import type { LatLngExpression } from 'leaflet'; import 'leaflet/dist/leaflet.css'; @@ -447,6 +448,7 @@ export function MImage({ content, renderImageContent, outlined, fitParent }: MIm // this garbage is for portrait images, we cap the width so the card doesn't exceed the bounds of the image const displayWidth = imgH > imgW ? Math.round(MAX_SIZE * (imgW / imgH)) : MAX_SIZE; const height = scaleYDimension(imgInfo?.w || 400, displayWidth, imgInfo?.h || 400); + const filename = getAttachmentFilename(content.filename, content.body, 'Image'); return ( {renderImageContent({ body: content.body || content.filename || 'Image', + filename, info: imgInfo, mimeType: imgInfo?.mimetype, url: mxcUrl, @@ -511,7 +514,7 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }: const displayWidth = Math.min(videoInfo.w || 400, 400); const height = Math.min(scaleYDimension(videoInfo.w || 400, 400, videoInfo.h || 400), 400); - const filename = content.filename ?? content.body ?? 'Video'; + const filename = getAttachmentFilename(content.filename, content.body, 'Video'); return ( ; } - const filename = content.filename ?? content.body ?? 'Audio'; + const filename = getAttachmentFilename(content.filename, content.body, 'Audio'); const durationMs = getAudioDurationMs(content, audioInfo); const resolvedInfo = durationMs !== undefined ? { ...audioInfo, duration: durationMs } : audioInfo; @@ -669,18 +672,17 @@ export function MFile({ content, renderFileContent, outlined }: MFileProps) { return ; } + const filename = getAttachmentFilename(content.filename, content.body, 'File'); + return ( - + {renderFileContent({ - body: content.body ?? content.filename ?? 'File', + body: filename, info: fileInfo ?? {}, mimeType: fileInfo?.mimetype ?? FALLBACK_MIMETYPE, url: mxcUrl, diff --git a/src/app/components/message/content/FileContent.tsx b/src/app/components/message/content/FileContent.tsx index 2e7e0daa8..eef1f7937 100644 --- a/src/app/components/message/content/FileContent.tsx +++ b/src/app/components/message/content/FileContent.tsx @@ -31,6 +31,7 @@ import { stopPropagation } from '$utils/keyboard'; import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { ModalWide } from '$styles/Modal.css'; +import { getDownloadFilename } from '$utils/download'; const renderErrorButton = (retry: () => void, text: string) => ( downloadState.status === AsyncStatus.Success - ? FileSaver.saveAs(downloadState.data, body) + ? FileSaver.saveAs(downloadState.data, getDownloadFilename(body)) : download() } disabled={downloadState.status === AsyncStatus.Loading} diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 57e7acd2e..fb2c288cf 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -70,6 +70,7 @@ function thumbnailDimsForMaxEdge( type RenderViewerProps = { src: string; alt: string; + filename?: string; requestClose: () => void; info?: IImageInfo; }; @@ -84,6 +85,7 @@ type RenderImageProps = { }; export type ImageContentProps = { body?: string; + filename?: string; mimeType?: string; url: string; info?: IImageInfo; @@ -104,6 +106,7 @@ export const ImageContent = as<'div', ImageContentProps>( className, style, body, + filename, mimeType, url, info, @@ -270,6 +273,7 @@ export const ImageContent = as<'div', ImageContentProps>( {renderViewer({ src: viewerFullSrc ?? srcState.data, alt: body ?? '', + filename, requestClose: () => setViewer(false), info: info, })} diff --git a/src/app/utils/download.ts b/src/app/utils/download.ts new file mode 100644 index 000000000..6e853e6c9 --- /dev/null +++ b/src/app/utils/download.ts @@ -0,0 +1,46 @@ +const INVALID_FILENAME_CHARS = /[<>:"/\\|?*]/g; +const CONTROL_CHARS = /\p{Cc}/gu; +const BIDI_CONTROL_CHARS = /[\u202a-\u202e\u2066-\u2069]/g; +const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i; +const MAX_FILENAME_LENGTH = 255; + +const nonEmptyString = (value: unknown): string | undefined => { + if (typeof value !== 'string') return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +}; + +export const getAttachmentFilename = ( + filename: unknown, + body: unknown, + fallback = 'download' +): string => nonEmptyString(filename) ?? nonEmptyString(body) ?? fallback; + +export const sanitizeDownloadFilename = (filename: string, fallback = 'download'): string => { + let safeName = filename + .replace(INVALID_FILENAME_CHARS, '_') + .replace(CONTROL_CHARS, '_') + .replace(BIDI_CONTROL_CHARS, '') + .trim() + .replace(/[. ]+$/g, ''); + + if (!safeName || safeName === '.' || safeName === '..') safeName = fallback; + if (WINDOWS_RESERVED_NAME.test(safeName)) safeName = `_${safeName}`; + + if (safeName.length > MAX_FILENAME_LENGTH) { + const extensionStart = safeName.lastIndexOf('.'); + const extension = extensionStart > 0 ? safeName.slice(extensionStart) : ''; + const extensionLength = Math.min(extension.length, 32); + safeName = `${safeName.slice(0, MAX_FILENAME_LENGTH - extensionLength)}${extension.slice( + -extensionLength + )}`; + } + + return safeName; +}; + +export const getDownloadFilename = ( + filename: unknown, + body?: unknown, + fallback = 'download' +): string => sanitizeDownloadFilename(getAttachmentFilename(filename, body, fallback), fallback);