diff --git a/src/app/components/image-viewer/ImageViewer.test.tsx b/src/app/components/image-viewer/ImageViewer.test.tsx index 494ad229c..16fe88546 100644 --- a/src/app/components/image-viewer/ImageViewer.test.tsx +++ b/src/app/components/image-viewer/ImageViewer.test.tsx @@ -1,10 +1,13 @@ -import type { ImgHTMLAttributes, PointerEvent, SyntheticEvent, WheelEvent } from 'react'; +import type { SyntheticEvent, WheelEvent } from 'react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import FileSaver from 'file-saver'; import { ImageViewer } from './ImageViewer'; const downloadMedia = vi.fn<(src: string) => Promise>(); +const gestureMocks = vi.hoisted(() => ({ + onPointerDown: vi.fn<(event: React.PointerEvent) => void>(), +})); vi.mock('$hooks/useImageGestures', () => ({ useImageGestures: () => ({ @@ -14,7 +17,7 @@ vi.mock('$hooks/useImageGestures', () => ({ imageRef: { current: null }, containerRef: { current: null }, handleWheel: vi.fn<(event: WheelEvent) => void>(), - onPointerDown: vi.fn<(event: PointerEvent) => void>(), + onPointerDown: gestureMocks.onPointerDown, handleImageLoad: vi.fn<(event: SyntheticEvent) => void>(), setZoom: vi.fn<(next: number) => void>(), resetTransforms: vi.fn<() => void>(), @@ -61,9 +64,25 @@ describe('ImageViewer', () => { }); }); -vi.mock('$components/media', () => ({ - Image: ({ alt, ...props }: ImgHTMLAttributes) => {alt}, -})); +vi.mock('$components/media', async () => { + const { forwardRef } = await import('react'); + return { + Image: forwardRef< + HTMLImageElement | HTMLCanvasElement, + React.ImgHTMLAttributes & { info?: { mimetype?: string } } + >(({ alt, info, ...props }, ref) => + info?.mimetype === 'application/x-tgsticker' ? ( + )} + ref={ref as React.ForwardedRef} + /> + ) : ( + {alt}} /> + ) + ), + }; +}); describe('ImageViewer', () => { it('renders the fullscreen image without crashing', () => { @@ -71,4 +90,21 @@ describe('ImageViewer', () => { expect(screen.getByAltText('demo')).toBeInTheDocument(); }); + + it('starts viewer gestures from the rendered lottie canvas', () => { + gestureMocks.onPointerDown.mockClear(); + render( + {}} + /> + ); + + const canvas = screen.getByLabelText('animated sticker'); + expect(canvas.tagName).toBe('CANVAS'); + fireEvent.pointerDown(canvas); + expect(gestureMocks.onPointerDown).toHaveBeenCalled(); + }); }); diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index 33e29afe3..ac284b542 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -322,6 +322,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( onTouchCancel={menu.triggerProps.onTouchCancel} > { expect(rendered).toHaveAttribute('height', '123'); }); + it('forwards the canvas ref and pointer events for lottie images', async () => { + const gzipped = Buffer.from(gzipSync(lottieJson)).toString('base64'); + const ref = createRef(); + const onPointerDown = vi.fn<(event: React.PointerEvent) => void>(); + render( + + ); + + await waitFor(() => { + expect(screen.getByLabelText('interactive lottie').tagName).toBe('CANVAS'); + }); + const canvas = screen.getByLabelText('interactive lottie'); + fireEvent.pointerDown(canvas); + + expect(canvas.tagName).toBe('CANVAS'); + await waitFor(() => expect(ref.current).toBe(canvas)); + expect(onPointerDown).toHaveBeenCalledOnce(); + }); + + it('probes an undeclared lottie only after native image decoding fails', async () => { + const bytes = Uint8Array.from(gzipSync(lottieJson)); + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response(bytes, { headers: { 'content-length': `${bytes.length}` } })); + render(undeclared lottie); + + const image = screen.getByAltText('undeclared lottie'); + expect(fetchSpy).not.toHaveBeenCalled(); + fireEvent.error(image); + + await waitFor(() => { + expect(screen.getByLabelText('undeclared lottie').tagName).toBe('CANVAS'); + }); + expect(fetchSpy).toHaveBeenCalledOnce(); + fetchSpy.mockRestore(); + }); + + it('aborts an in-flight lottie download when unmounted', async () => { + let requestSignal: AbortSignal | undefined; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((_input, init) => { + requestSignal = init?.signal ?? undefined; + return new Promise(() => {}); + }); + const { unmount } = render( + loading lottie + ); + + await waitFor(() => expect(requestSignal).toBeDefined()); + unmount(); + + expect(requestSignal?.aborted).toBe(true); + fetchSpy.mockRestore(); + }); + + it('rejects lottie data that exceeds the decompressed size limit', async () => { + const oversizedJson = JSON.stringify({ + v: '5.11.0', + padding: 'a'.repeat(8 * 1024 * 1024), + }); + const gzipped = Buffer.from(gzipSync(oversizedJson)).toString('base64'); + render( + oversized lottie {}} + /> + ); + + const image = screen.getByAltText('oversized lottie'); + await waitFor(() => expect(image).toHaveAttribute('src')); + expect(image.tagName).toBe('IMG'); + }); + it('forwards a candidate fallback error after detection fails', async () => { let errorTarget: EventTarget | null = null; const onError = vi.fn<(event: React.SyntheticEvent) => void>((event) => { diff --git a/src/app/components/media/Image.tsx b/src/app/components/media/Image.tsx index b51f07285..059f8dd5f 100644 --- a/src/app/components/media/Image.tsx +++ b/src/app/components/media/Image.tsx @@ -1,4 +1,4 @@ -import type { ComponentProps, ImgHTMLAttributes } from 'react'; +import type { ComponentProps, ForwardedRef, ImgHTMLAttributes, PointerEventHandler } from 'react'; import { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'; import classNames from 'classnames'; import type { DotLottieReact as DotLottieReactComponent } from '@lottiefiles/dotlottie-react'; @@ -7,18 +7,19 @@ import { isPixelatedRendering, settingsAtom } from '$state/settings'; import * as css from './media.css'; import type { IImageInfo } from '$types/matrix/common'; -type ImageProps = ImgHTMLAttributes & { +type ImageProps = Omit, 'onPointerDown'> & { info?: IImageInfo; mimeType?: string; disablePixelation?: boolean; pixelated?: boolean; onLottieLoad?: (canvas?: HTMLCanvasElement) => void; onLottieError?: () => void; + onPointerDown?: PointerEventHandler; }; type LottieDotProps = Omit< ComponentProps, - 'src' | 'alt' | 'loading' + 'src' | 'alt' | 'loading' | 'onPointerDown' >; type DotLottieInstance = Parameters< NonNullable['dotLottieRefCallback']> @@ -31,6 +32,11 @@ const DotLottieReact = lazy(() => ) as typeof DotLottieReactComponent; const GZIPPED_LOTTIE_MIME = /^application\/(?:(?:x-)?gzip|x-tgsticker)(?:;|$)/i; +const MAX_COMPRESSED_LOTTIE_BYTES = 1024 * 1024; +const MAX_DECOMPRESSED_LOTTIE_BYTES = 8 * 1024 * 1024; +const MAX_LOTTIE_DIMENSION = 4096; +const MAX_LOTTIE_FRAMES = 10_000; +const MAX_LOTTIE_LAYERS = 1_000; const UNSAFE_LOTTIE_KEYS = new Set([ 'expression', 'expressions', @@ -66,28 +72,109 @@ function isGzippedLottieCandidate( ); } -async function loadBytes(src: string): Promise { +async function readBytes( + stream: ReadableStream, + limit: number, + signal: AbortSignal +): Promise { + const reader = stream.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + let completed = false; + + try { + while (true) { + if (signal.aborted) throw new DOMException('Aborted', 'AbortError'); + // Stream chunks must be consumed sequentially to enforce the running byte limit. + // eslint-disable-next-line no-await-in-loop + const { done, value } = await reader.read(); + if (done) { + completed = true; + break; + } + size += value.byteLength; + if (size > limit) throw new Error('Lottie data exceeds the size limit'); + chunks.push(value); + } + } finally { + if (!completed) await reader.cancel().catch(() => undefined); + reader.releaseLock(); + } + + const bytes = new Uint8Array(size); + let offset = 0; + chunks.forEach((chunk) => { + bytes.set(chunk, offset); + offset += chunk.byteLength; + }); + return bytes; +} + +async function loadBytes(src: string, signal: AbortSignal): Promise { const encoded = src.match(/^data:[^;,]*;base64,(.+)$/i)?.[1]; if (encoded) { + if (encoded.length > Math.ceil((MAX_COMPRESSED_LOTTIE_BYTES * 4) / 3) + 4) return null; return Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0)); } - const response = await fetch(src, { credentials: 'include' }); - return response.ok ? new Uint8Array(await response.arrayBuffer()) : null; + const response = await fetch(src, { credentials: 'include', signal }); + if (!response.ok || !response.body) return null; + const contentLength = Number(response.headers.get('content-length')); + if (Number.isFinite(contentLength) && contentLength > MAX_COMPRESSED_LOTTIE_BYTES) return null; + return readBytes(response.body, MAX_COMPRESSED_LOTTIE_BYTES, signal); } -async function resolveLottieDataUrl(src: string): Promise { +function hasSafeLottieComplexity(value: unknown): value is Record { + if (!value || typeof value !== 'object' || !('v' in value)) return false; + const lottie = value as Record; + const width = Number(lottie.w); + const height = Number(lottie.h); + const firstFrame = Number(lottie.ip); + const lastFrame = Number(lottie.op); + if ( + (Number.isFinite(width) && (width <= 0 || width > MAX_LOTTIE_DIMENSION)) || + (Number.isFinite(height) && (height <= 0 || height > MAX_LOTTIE_DIMENSION)) || + (Number.isFinite(firstFrame) && + Number.isFinite(lastFrame) && + (lastFrame <= firstFrame || lastFrame - firstFrame > MAX_LOTTIE_FRAMES)) + ) { + return false; + } + + let layerCount = 0; + const pending: unknown[] = [value]; + while (pending.length > 0) { + const current = pending.pop(); + if (!current || typeof current !== 'object') continue; + if (Array.isArray(current)) { + pending.push(...current); + continue; + } + Object.entries(current).forEach(([key, child]) => { + if (key === 'layers' && Array.isArray(child)) { + layerCount += child.length; + } + pending.push(child); + }); + if (layerCount > MAX_LOTTIE_LAYERS) return false; + } + return true; +} + +async function resolveLottieDataUrl(src: string, signal: AbortSignal): Promise { try { - const bytes = await loadBytes(src); + const bytes = await loadBytes(src, signal); if (!bytes || bytes[0] !== 0x1f || bytes[1] !== 0x8b) return null; const stream = new Blob([bytes.buffer as ArrayBuffer]) .stream() .pipeThrough(new DecompressionStream('gzip')); - const jsonText = await new Response(stream).text(); - const json = sanitizeLottieJson(JSON.parse(jsonText)); + const decompressed = await readBytes(stream, MAX_DECOMPRESSED_LOTTIE_BYTES, signal); + const parsed = JSON.parse(new TextDecoder().decode(decompressed)); + if (!hasSafeLottieComplexity(parsed)) return null; + const json = sanitizeLottieJson(parsed); const safeJsonText = JSON.stringify(json); - return json && typeof json === 'object' && 'v' in json && safeJsonText + return safeJsonText ? `data:application/json;charset=utf-8,${encodeURIComponent(safeJsonText)}` : null; } catch { @@ -101,6 +188,8 @@ type LottieImageProps = LottieDotProps & { onLottieLoad?: (canvas?: HTMLCanvasElement) => void; onLottieError?: () => void; pixelated?: boolean; + forwardedRef?: ForwardedRef; + onPointerDown?: PointerEventHandler; }; function LottieImage({ @@ -110,6 +199,8 @@ function LottieImage({ onLottieLoad, onLottieError, pixelated, + forwardedRef, + onPointerDown, ...props }: Readonly) { const wrapperRef = useRef(null); @@ -117,27 +208,52 @@ function LottieImage({ const pixelation = useRef(pixelated); callbacks.current = { onLottieLoad, onLottieError }; pixelation.current = pixelated; + const setForwardedRef = useCallback( + (canvas: HTMLCanvasElement | null) => { + if (typeof forwardedRef === 'function') forwardedRef(canvas); + else if (forwardedRef) forwardedRef.current = canvas; + }, + [forwardedRef] + ); + useEffect(() => { + const updateRef = () => { + const canvas = wrapperRef.current?.querySelector('canvas') ?? null; + if (canvas) setForwardedRef(canvas); + }; + updateRef(); + const observer = new MutationObserver(updateRef); + if (wrapperRef.current) + observer.observe(wrapperRef.current, { childList: true, subtree: true }); + return () => { + observer.disconnect(); + setForwardedRef(null); + }; + }, [setForwardedRef]); useEffect(() => { const canvas = wrapperRef.current?.querySelector('canvas'); if (canvas) canvas.style.imageRendering = pixelated ? 'pixelated' : 'auto'; }, [pixelated]); - const handlePlayer = useCallback((player: DotLottieInstance) => { - if (!player) return; - let didLoad = false; - const handleLoad = () => { - if (didLoad) return; - didLoad = true; - (player.canvas as HTMLCanvasElement).style.imageRendering = pixelation.current - ? 'pixelated' - : 'auto'; - callbacks.current.onLottieLoad?.(player.canvas as HTMLCanvasElement); - }; - const handleError = () => callbacks.current.onLottieError?.(); + const handlePlayer = useCallback( + (player: DotLottieInstance) => { + if (!player) return; + let didLoad = false; + const handleLoad = () => { + if (didLoad) return; + didLoad = true; + (player.canvas as HTMLCanvasElement).style.imageRendering = pixelation.current + ? 'pixelated' + : 'auto'; + callbacks.current.onLottieLoad?.(player.canvas as HTMLCanvasElement); + setForwardedRef(player.canvas as HTMLCanvasElement); + }; + const handleError = () => callbacks.current.onLottieError?.(); - player.addEventListener('load', handleLoad); - player.addEventListener('loadError', handleError); - if (player.isLoaded) handleLoad(); - }, []); + player.addEventListener('load', handleLoad); + player.addEventListener('loadError', handleError); + if (player.isLoaded) handleLoad(); + }, + [setForwardedRef] + ); return ( @@ -145,6 +261,7 @@ function LottieImage({ ref={wrapperRef} className={className} style={{ width: '100%', height: '100%', ...style }} + onPointerDown={onPointerDown} > ( +export const Image = forwardRef( ( { className, @@ -183,16 +300,18 @@ export const Image = forwardRef( source: string; resolved: string | null; }>(); + const [fallbackSource, setFallbackSource] = useState(); const lottieProps = props as LottieDotProps; - const isLottieCandidate = isGzippedLottieCandidate( + const declaredLottieCandidate = isGzippedLottieCandidate( src, mimeType ?? info?.mimetype, typeof props.title === 'string' ? props.title : alt ); + const isLottieCandidate = declaredLottieCandidate || fallbackSource === src; const resolvedLottieSrc = isLottieCandidate && lottieResolution?.source === src - ? lottieResolution.resolved + ? (lottieResolution?.resolved ?? null) : isLottieCandidate ? undefined : null; @@ -205,21 +324,23 @@ export const Image = forwardRef( ); useEffect(() => { - let cancelled = false; + const controller = new AbortController(); - if (isLottieCandidate) { - void resolveLottieDataUrl(src).then((result) => { - if (!cancelled) { + if (isLottieCandidate && src) { + void resolveLottieDataUrl(src, controller.signal).then((result) => { + if (!controller.signal.aborted) { setLottieResolution({ source: src, resolved: result }); } }); } - return () => { - cancelled = true; - }; + return () => controller.abort(); }, [isLottieCandidate, src]); + useEffect(() => { + setFallbackSource(undefined); + }, [src]); + const shouldRenderLottie = typeof resolvedLottieSrc === 'string'; if (shouldRenderLottie) { @@ -232,6 +353,8 @@ export const Image = forwardRef( alt={alt} onLottieLoad={onLottieLoad} onLottieError={onLottieError} + forwardedRef={ref} + onPointerDown={onPointerDown} pixelated={ !disablePixelation && (pixelated ?? isPixelatedRendering(pixelatedImageRendering, info)) } @@ -251,9 +374,15 @@ export const Image = forwardRef( style={style} onLoad={onLoad} onPointerDown={onPointerDown} - onError={onError} + onError={(event) => { + if (!declaredLottieCandidate && fallbackSource !== src) { + setFallbackSource(src); + return; + } + onError?.(event); + }} {...props} - ref={ref} + ref={ref as ForwardedRef} /> ); } diff --git a/src/app/hooks/useImageGestures.ts b/src/app/hooks/useImageGestures.ts index abf745574..44dd62087 100644 --- a/src/app/hooks/useImageGestures.ts +++ b/src/app/hooks/useImageGestures.ts @@ -33,7 +33,7 @@ export const useImageGestures = (active: boolean, step = 0.2, min = 0.1, max = 5 const shouldResizeWithWindowRef = useRef(true); const [fitRatio, setFitRatio] = useState(1); const containerRef = useRef(null); - const imageRef = useRef(null); + const imageRef = useRef(null); const setShouldResizeWithWindow = useCallback((next: boolean) => { shouldResizeWithWindowRef.current = next; @@ -229,13 +229,15 @@ export const useImageGestures = (active: boolean, step = 0.2, min = 0.1, max = 5 if ( !img || // Image not loaded !shouldResizeWithWindowRef.current || // Resizing disabled - !img.naturalWidth || - !img.naturalHeight // Invalid image dimensions + !(img instanceof HTMLCanvasElement ? img.width : img.naturalWidth) || + !(img instanceof HTMLCanvasElement ? img.height : img.naturalHeight) // Invalid dimensions ) { return; } - const heightRatio = height / img.naturalHeight; - const widthRatio = width / img.naturalWidth; + const imageHeight = img instanceof HTMLCanvasElement ? img.height : img.naturalHeight; + const imageWidth = img instanceof HTMLCanvasElement ? img.width : img.naturalWidth; + const heightRatio = height / imageHeight; + const widthRatio = width / imageWidth; const fitZoom = Math.min(heightRatio, widthRatio); img.style.transition = 'none'; diff --git a/src/app/utils/mimeTypes.test.ts b/src/app/utils/mimeTypes.test.ts index 30ca46548..599980a4d 100644 --- a/src/app/utils/mimeTypes.test.ts +++ b/src/app/utils/mimeTypes.test.ts @@ -66,6 +66,15 @@ describe('TGS uploads', () => { expect(upload.type).toBe(FALLBACK_MIMETYPE); expect(isImageMimeType(upload.type)).toBe(false); }); + + it('does not treat an ordinary gzip archive as a TGS image', async () => { + const archive = new File([tgsBytes], 'archive.tar.gz', { type: 'application/gzip' }); + const upload = await safeUploadFile(archive); + + expect(await isTgsFile(archive)).toBe(false); + expect(upload.type).toBe(FALLBACK_MIMETYPE); + expect(isImageMimeType(upload.type)).toBe(false); + }); }); describe('mimeTypeToExt', () => { diff --git a/src/app/utils/mimeTypes.ts b/src/app/utils/mimeTypes.ts index 9e85d8453..9aac4a0a3 100644 --- a/src/app/utils/mimeTypes.ts +++ b/src/app/utils/mimeTypes.ts @@ -109,8 +109,6 @@ const ALLOWED_BLOB_MIME_TYPES = new Set([ export const FALLBACK_MIMETYPE = 'application/octet-stream'; export const TGS_MIMETYPE = 'application/x-tgsticker'; -const GZIP_MIME_TYPES = new Set(['application/gzip', 'application/x-gzip', TGS_MIMETYPE]); - export const isTgsMimeType = (mimeType: string): boolean => mimeType.split(';', 1)[0]?.toLowerCase() === TGS_MIMETYPE; @@ -118,8 +116,7 @@ export const isImageMimeType = (mimeType: string): boolean => mimeType.toLowerCase().startsWith('image/') || isTgsMimeType(mimeType); const isTgsCandidate = (file: File): boolean => - file.name.toLowerCase().endsWith('.tgs') || - GZIP_MIME_TYPES.has(file.type.split(';', 1)[0]?.toLowerCase() ?? ''); + file.name.toLowerCase().endsWith('.tgs') || isTgsMimeType(file.type); export const isTgsFile = async (file: File): Promise => { if (!isTgsCandidate(file)) return false;