mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-01 14:22:31 -08:00
Fix file downloads not always being the right files (#1086)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Fixes #1084 Centralizes the download file name generation and adds some related safety and hardening #### Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
8 files changed
+75
-13
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Use attachment filenames instead of captions when downloading files and harden unsafe download names.
|
||||
@@ -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<HTMLFormElement> = (evt) => {
|
||||
|
||||
@@ -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<HTMLInputElement>(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<RectCords>();
|
||||
|
||||
@@ -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])
|
||||
);
|
||||
|
||||
@@ -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 (
|
||||
<Attachment
|
||||
@@ -468,6 +470,7 @@ export function MImage({ content, renderImageContent, outlined, fitParent }: MIm
|
||||
>
|
||||
{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 (
|
||||
<Attachment
|
||||
@@ -611,7 +614,7 @@ export function MAudio({
|
||||
return <BrokenContent body={content.body ?? content.filename} />;
|
||||
}
|
||||
|
||||
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 <BrokenContent body={content.body ?? content.filename} />;
|
||||
}
|
||||
|
||||
const filename = getAttachmentFilename(content.filename, content.body, 'File');
|
||||
|
||||
return (
|
||||
<Attachment outlined={outlined} style={{ width: toRem(400), height: 'auto' }}>
|
||||
<AttachmentHeader>
|
||||
<FileHeader
|
||||
body={content.filename ?? content.body ?? 'Unnamed File'}
|
||||
mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE}
|
||||
/>
|
||||
<FileHeader body={filename} mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE} />
|
||||
</AttachmentHeader>
|
||||
<AttachmentBox>
|
||||
<AttachmentContent>
|
||||
{renderFileContent({
|
||||
body: content.body ?? content.filename ?? 'File',
|
||||
body: filename,
|
||||
info: fileInfo ?? {},
|
||||
mimeType: fileInfo?.mimetype ?? FALLBACK_MIMETYPE,
|
||||
url: mxcUrl,
|
||||
|
||||
@@ -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) => (
|
||||
<TooltipProvider
|
||||
@@ -257,7 +258,7 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
|
||||
: await downloadMedia(mediaUrl);
|
||||
|
||||
const fileURL = URL.createObjectURL(fileContent);
|
||||
FileSaver.saveAs(fileURL, body);
|
||||
FileSaver.saveAs(fileURL, getDownloadFilename(body));
|
||||
return fileURL;
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo, body])
|
||||
);
|
||||
@@ -272,7 +273,7 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
|
||||
size="400"
|
||||
onClick={() =>
|
||||
downloadState.status === AsyncStatus.Success
|
||||
? FileSaver.saveAs(downloadState.data, body)
|
||||
? FileSaver.saveAs(downloadState.data, getDownloadFilename(body))
|
||||
: download()
|
||||
}
|
||||
disabled={downloadState.status === AsyncStatus.Loading}
|
||||
|
||||
@@ -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,
|
||||
})}
|
||||
|
||||
@@ -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);
|
||||
Reference in new issue
Block a user