diff --git a/src-tauri/src/network/media_protocol.rs b/src-tauri/src/network/media_protocol.rs index c3fe293cb..2d9f399fd 100644 --- a/src-tauri/src/network/media_protocol.rs +++ b/src-tauri/src/network/media_protocol.rs @@ -383,7 +383,9 @@ fn normalize_encryption_key(url: &str) -> String { let decoded = percent_encoding::percent_decode_str(path) .decode_utf8() .unwrap_or(std::borrow::Cow::Borrowed(path)); - if let Ok(parsed) = Url::parse(&decoded) { + if let Ok(mut parsed) = Url::parse(&decoded) { + // A retry fragment is transport metadata, never part of the params key. + parsed.set_fragment(None); return parsed.to_string(); } return decoded.into_owned(); @@ -391,7 +393,10 @@ fn normalize_encryption_key(url: &str) -> String { } // Parse bare URLs too, so both sides of the map agree on one canonical form. Url::parse(url) - .map(|parsed| parsed.to_string()) + .map(|mut parsed| { + parsed.set_fragment(None); + parsed.to_string() + }) .unwrap_or_else(|_| url.to_string()) } @@ -494,7 +499,10 @@ async fn handle_request( return Ok(session_unavailable_response()); }; - let media_url = Url::parse(&target).map_err(|_| StatusCode::BAD_REQUEST)?; + let mut media_url = Url::parse(&target).map_err(|_| StatusCode::BAD_REQUEST)?; + // A retry fragment never goes upstream and must not key encryption params, but stays + // in `target` below so the retry gets a fresh cache identity. + media_url.set_fragment(None); if media_url.scheme() != "http" && media_url.scheme() != "https" { return Err(StatusCode::FORBIDDEN); } @@ -1145,6 +1153,7 @@ fn session_unavailable_response() -> Response> { Response::builder() .status(StatusCode::SERVICE_UNAVAILABLE) .header(header::RETRY_AFTER, "1") + .header(header::CACHE_CONTROL, "no-store") .body(Vec::new()) .expect("failed to build 503 media response") } @@ -1152,6 +1161,7 @@ fn session_unavailable_response() -> Response> { fn error_response(status: StatusCode) -> Response> { Response::builder() .status(status) + .header(header::CACHE_CONTROL, "no-store") .body(Vec::new()) .expect("failed to build media error response") } @@ -1836,6 +1846,55 @@ mod tests { .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); } + #[test] + fn retry_fragment_never_keys_encryption_params() { + let bare = "https://matrix.example.org/_matrix/client/v1/media/download/matrix.org/abc123"; + for input in [ + format!("{bare}#retry=1"), + format!( + "https://sable-media.localhost/{}?__sable_media_session=%40a%3Aexample.org", + percent_encoding::utf8_percent_encode( + &format!("{bare}#retry=1"), + percent_encoding::NON_ALPHANUMERIC + ) + ), + ] { + assert_eq!(super::normalize_encryption_key(&input), bare); + } + } + + #[test] + fn retry_fragment_gives_a_distinct_cache_identity() { + let base = "https://matrix.example.org/_matrix/client/v1/media/download/matrix.org/abc123"; + let original = cache_key("@a:example.org", base); + assert_ne!( + original, + cache_key("@a:example.org", &format!("{base}#retry=1")) + ); + assert_ne!( + original, + cache_key("@a:example.org", &format!("{base}#retry=2")) + ); + assert_eq!( + cache_key("@a:example.org", &format!("{base}#retry=1")), + cache_key("@a:example.org", &format!("{base}#retry=1")) + ); + } + + #[test] + fn error_responses_are_no_store() { + for response in [ + super::error_response(StatusCode::UNAUTHORIZED), + super::error_response(StatusCode::FORBIDDEN), + super::session_unavailable_response(), + ] { + assert_eq!( + response.headers().get(header::CACHE_CONTROL).unwrap(), + "no-store" + ); + } + } + #[test] fn image_response_is_cached_immutable() { let response = super::media_response_builder(StatusCode::OK, "image/png") diff --git a/src/app/components/message/content/ImageContent.test.tsx b/src/app/components/message/content/ImageContent.test.tsx index cbd5e1da3..db41be406 100644 --- a/src/app/components/message/content/ImageContent.test.tsx +++ b/src/app/components/message/content/ImageContent.test.tsx @@ -3,12 +3,28 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { ImageContent } from './ImageContent'; -const screenMocks = vi.hoisted(() => ({ isMobile: true })); +const screenMocks = vi.hoisted(() => ({ isMobile: true, tauri: false })); vi.mock('$hooks/useScreenSize', () => ({ ScreenSize: { Desktop: 'Desktop', Tablet: 'Tablet', Mobile: 'Mobile' }, useScreenSizeOptionally: () => (screenMocks.isMobile ? 'Mobile' : 'Desktop'), })); +vi.mock('@tauri-apps/api/core', () => ({ + isTauri: () => screenMocks.tauri, + // Real convertFileSrc percent-encodes the target into the URI path. + convertFileSrc: (url: string, protocol: string) => + `${protocol}://localhost/${encodeURIComponent(url)}`, +})); + +const SABLE_MEDIA_URL = + 'sable-media://https://hs.example/_matrix/client/v1/media/download/example.org/abc123?__sable_media_cache=3'; +vi.mock('$utils/matrix', () => ({ + mxcUrlToHttp: () => SABLE_MEDIA_URL, + rewriteAuthenticatedMediaUrl: (url: string | null) => url, + downloadEncryptedMedia: vi.fn<() => Promise>(), + decryptFile: vi.fn<() => Promise>(), +})); + vi.mock('$hooks/useMatrixClient', () => ({ useMatrixClient: () => ({}), })); @@ -107,6 +123,45 @@ describe('ImageContent', () => { } }); + it('renders a distinct sable-media src on retry in Tauri', async () => { + screenMocks.tauri = true; + try { + const srcs: string[] = []; + render( + { + srcs.push(props.src); + return preview; + }} + renderViewer={() =>
viewer
} + /> + ); + + touchTap(screen.getByRole('button', { name: 'View' })); + + const img = await screen.findByAltText('preview'); + const initialSrc = srcs[srcs.length - 1]; + expect(initialSrc).toBe(SABLE_MEDIA_URL); + + fireEvent.error(img); + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })); + + await waitFor(() => { + const retriedSrc = srcs[srcs.length - 1] ?? ''; + expect(retriedSrc).not.toBe(initialSrc); + // The decoded scheme path is the `target` Rust feeds into cache_key. + const schemePath = retriedSrc.replace(/^sable-media:\/\/localhost\//, '').split('?')[0]!; + expect(decodeURIComponent(schemePath)).toMatch( + /^https:\/\/hs\.example\/_matrix\/client\/v1\/media\/download\/example\.org\/abc123#__sable_media_retry=\d+$/ + ); + expect(retriedSrc).toContain('__sable_media_cache=3'); + }); + } finally { + screenMocks.tauri = false; + } + }); + it('still allows ordinary message touches to start long press', () => { vi.useFakeTimers(); const messageLongPress = vi.fn<() => void>(); diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index d0133b701..941c1e702 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -1,5 +1,5 @@ import type { CSSProperties, ReactNode } from 'react'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Badge, Box, @@ -40,6 +40,7 @@ import { mxcUrlToHttp, rewriteAuthenticatedMediaUrl, } from '$utils/matrix'; +import { addTauriMediaRetryRevision, getTauriMediaRetryTarget } from '$utils/mediaUrl'; import { setMediaEncryption } from '$utils/tauriMediaEncryption'; import { isTauri } from '@tauri-apps/api/core'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -143,6 +144,8 @@ export const ImageContent = as<'div', ImageContentProps>( const [load, setLoad] = useState(false); const [error, setError] = useState(false); + // Tauri only: each retry gets a distinct sable-media:// src. + const retryRevisionRef = useRef(0); const [viewer, setViewer] = useState(false); const [viewerFullSrc, setViewerFullSrc] = useState(null); const [blurred, setBlurred] = useState(markedAsSpoiler ?? false); @@ -169,8 +172,11 @@ export const ImageContent = as<'div', ImageContentProps>( if (encInfo) { if (!rawMediaUrl) throw new Error('Invalid media URL'); if (isTauri()) { - await setMediaEncryption(rawMediaUrl, encInfo, mimeType ?? FALLBACK_MIMETYPE); - return rewriteAuthenticatedMediaUrl(rawMediaUrl)!; + // The registration key is the revised target; Rust strips the fragment. + const attemptedTarget = + getTauriMediaRetryTarget(rawMediaUrl, retryRevisionRef.current) ?? rawMediaUrl; + await setMediaEncryption(attemptedTarget, encInfo, mimeType ?? FALLBACK_MIMETYPE); + return rewriteAuthenticatedMediaUrl(attemptedTarget)!; } return createObjectURL( downloadEncryptedMedia(rawMediaUrl, (encBuf) => @@ -178,7 +184,10 @@ export const ImageContent = as<'div', ImageContentProps>( ) ); } - return resolvedMediaUrl ?? rawMediaUrl ?? url; + return addTauriMediaRetryRevision( + resolvedMediaUrl ?? rawMediaUrl ?? url, + retryRevisionRef.current + ); }, [rawMediaUrl, resolvedMediaUrl, url, mimeType, encInfo, createObjectURL]) ); @@ -216,6 +225,7 @@ export const ImageContent = as<'div', ImageContentProps>( const handleRetry = () => { setError(false); + retryRevisionRef.current += 1; loadSrc().catch(() => undefined); }; diff --git a/src/app/components/message/content/VideoContent.test.tsx b/src/app/components/message/content/VideoContent.test.tsx new file mode 100644 index 000000000..d445a0e5e --- /dev/null +++ b/src/app/components/message/content/VideoContent.test.tsx @@ -0,0 +1,76 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { VideoContent } from './VideoContent'; + +const mocks = vi.hoisted(() => ({ tauri: true })); +vi.mock('@tauri-apps/api/core', () => ({ + isTauri: () => mocks.tauri, + // Real convertFileSrc percent-encodes the target into the URI path. + convertFileSrc: (url: string, protocol: string) => + `${protocol}://localhost/${encodeURIComponent(url)}`, +})); + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => ({}), +})); +vi.mock('$hooks/useMediaAuthentication', () => ({ + useMediaAuthentication: () => true, +})); +vi.mock('$hooks/useObjectURL', () => ({ + useCreateObjectURL: () => (value: string) => value, +})); + +const SABLE_MEDIA_URL = + 'sable-media://https://hs.example/_matrix/client/v1/media/download/example.org/vid123?__sable_media_cache=3'; +vi.mock('$utils/matrix', () => ({ + mxcUrlToHttp: () => SABLE_MEDIA_URL, + rewriteAuthenticatedMediaUrl: (url: string | null) => url, + downloadMedia: vi.fn<() => Promise>(), + downloadEncryptedMedia: vi.fn<() => Promise>(), + decryptFile: vi.fn<() => Promise>(), +})); +vi.mock('$utils/swMediaAuth', () => ({ + probeSWMediaAuthSupport: async () => true, +})); + +describe('VideoContent', () => { + it('renders a distinct sable-media src on retry in Tauri', async () => { + const srcs: string[] = []; + render( + { + srcs.push(props.src); + return ( + + ); + }} + /> + ); + + fireEvent.click(screen.getByRole('button', { name: 'Watch' })); + + const video = await screen.findByTestId('video'); + const initialSrc = srcs[srcs.length - 1]; + expect(initialSrc).toBe(SABLE_MEDIA_URL); + + fireEvent.error(video); + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })); + + await waitFor(() => { + const retriedSrc = srcs[srcs.length - 1] ?? ''; + expect(retriedSrc).not.toBe(initialSrc); + // The decoded scheme path is the `target` Rust feeds into cache_key. + const schemePath = retriedSrc.replace(/^sable-media:\/\/localhost\//, '').split('?')[0]!; + expect(decodeURIComponent(schemePath)).toMatch( + /^https:\/\/hs\.example\/_matrix\/client\/v1\/media\/download\/example\.org\/vid123#__sable_media_retry=\d+$/ + ); + expect(retriedSrc).toContain('__sable_media_cache=3'); + }); + }); +}); diff --git a/src/app/components/message/content/VideoContent.tsx b/src/app/components/message/content/VideoContent.tsx index 3edd1e86f..5fe60bb28 100644 --- a/src/app/components/message/content/VideoContent.tsx +++ b/src/app/components/message/content/VideoContent.tsx @@ -30,6 +30,7 @@ import { mxcUrlToHttp, rewriteAuthenticatedMediaUrl, } from '$utils/matrix'; +import { addTauriMediaRetryRevision, getTauriMediaRetryTarget } from '$utils/mediaUrl'; import { setMediaEncryption } from '$utils/tauriMediaEncryption'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useCreateObjectURL } from '$hooks/useObjectURL'; @@ -83,6 +84,8 @@ export const VideoContent = as<'div', VideoContentProps>( const [load, setLoad] = useState(false); const [error, setError] = useState(false); + // Tauri only: each retry gets a distinct sable-media:// src. + const retryRevisionRef = useRef(0); const [blurred, setBlurred] = useState(markedAsSpoiler ?? false); const [isHovered, setIsHovered] = useState(false); @@ -102,7 +105,9 @@ export const VideoContent = as<'div', VideoContentProps>( const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication); if (!mediaUrl) throw new Error('Invalid media URL'); if (!encInfo) { - if (isTauri()) return mediaUrl; + if (isTauri()) { + return addTauriMediaRetryRevision(mediaUrl, retryRevisionRef.current); + } // Stream through the service worker only after it proved media-auth // support; a stale SW build would otherwise serve the bare URL to // the homeserver and the element would fail with a 4xx. @@ -110,8 +115,10 @@ export const VideoContent = as<'div', VideoContentProps>( return createObjectURL(downloadMedia(mediaUrl, { forceDirectAuth: true })); } if (isTauri()) { - await setMediaEncryption(mediaUrl, encInfo, mimeType); - return rewriteAuthenticatedMediaUrl(mediaUrl)!; + const attemptedTarget = + getTauriMediaRetryTarget(mediaUrl, retryRevisionRef.current) ?? mediaUrl; + await setMediaEncryption(attemptedTarget, encInfo, mimeType); + return rewriteAuthenticatedMediaUrl(attemptedTarget)!; } return createObjectURL( downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo)) @@ -161,6 +168,7 @@ export const VideoContent = as<'div', VideoContentProps>( const handleRetry = () => { setError(false); + retryRevisionRef.current += 1; loadSrc().catch(() => undefined); }; diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 4078f6cea..19389f1fc 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -55,7 +55,7 @@ import { composerIcon, DotsThreeOutlineVerticalIcon } from '$components/icons/ph import { getHomePath } from '$pages/pathUtils'; import { DIRECT_ROOM_PATH, HOME_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths'; import { getCanonicalAliasRoomId, isRoomAlias, isRoomId } from '$utils/matrix'; -import { pushSessionToSW } from '../../../sw-session'; +import { pushPersistedSessionToSW, pushSessionToSW } from '../../../sw-session'; import { SyncStatus } from './SyncStatus'; import { SpecVersions } from './SpecVersions'; import { AutoDiscovery } from './AutoDiscovery'; @@ -280,7 +280,9 @@ export function ClientRoot({ children }: ClientRootProps) { log.log('initClient for', activeSession.userId); const newMx = await initClient(activeSession); loadedUserIdRef.current = activeSession.userId; - await pushSessionToSW(activeSession.baseUrl, activeSession.accessToken, activeSession.userId); + // initClient may have refreshed the token; push the persisted session, not + // the stale captured one. + await pushPersistedSessionToSW(activeSession); return newMx; }, [activeSession, activeSessionId, setActiveSessionId]) ); diff --git a/src/app/state/sessions.ts b/src/app/state/sessions.ts index 1c623ea9e..aed4cb2eb 100644 --- a/src/app/state/sessions.ts +++ b/src/app/state/sessions.ts @@ -197,10 +197,13 @@ export const updateSessionTokens = ( notifySessionChanged(); }; -export const getStoredSessionRefreshToken = (userId: string): string | undefined => +export const getStoredSession = (userId: string): Session | undefined => getLocalStorageItem(MATRIX_SESSIONS_KEY, []).find( (session) => session.userId === userId - )?.refreshToken; + ); + +export const getStoredSessionRefreshToken = (userId: string): string | undefined => + getStoredSession(userId)?.refreshToken; export const ACTIVE_SESSION_KEY = 'matrixActiveSession'; const baseActiveSessionAtom = atomWithLocalStorage( diff --git a/src/app/utils/mediaUrl.test.ts b/src/app/utils/mediaUrl.test.ts index ca61def03..4ed9b9c1a 100644 --- a/src/app/utils/mediaUrl.test.ts +++ b/src/app/utils/mediaUrl.test.ts @@ -18,7 +18,11 @@ vi.mock('./mediaTransport', () => ({ getCurrentMediaSessionScope: hoistedGetSessionScope, })); -import { rewriteAuthenticatedMediaUrl } from './mediaUrl'; +import { + addTauriMediaRetryRevision, + getTauriMediaRetryTarget, + rewriteAuthenticatedMediaUrl, +} from './mediaUrl'; afterEach(() => { hoistedIsTauri.mockReset(); @@ -134,3 +138,84 @@ describe('rewriteAuthenticatedMediaUrl', () => { }); }); }); + +describe('addTauriMediaRetryRevision', () => { + const INNER = 'https://matrix.example.com/_matrix/client/v1/media/download/example.com/abc123'; + const REWRITTEN = `sable-media://${INNER}?__sable_media_cache=3&__sable_media_session=session_abc`; + + afterEach(() => { + hoistedConvertFileSrc.mockImplementation( + (url: string, protocol: string) => `${protocol}://${url}` + ); + }); + + it('is a no-op for the first attempt and outside Tauri', () => { + hoistedIsTauri.mockReturnValue(true); + expect(addTauriMediaRetryRevision(REWRITTEN, 0)).toBe(REWRITTEN); + hoistedIsTauri.mockReturnValue(false); + expect(addTauriMediaRetryRevision(REWRITTEN, 2)).toBe(REWRITTEN); + }); + + it('leaves URLs without an http(s) inner target unchanged (e.g. blob: URLs)', () => { + hoistedIsTauri.mockReturnValue(true); + const blob = 'blob:https://app.local/0000-1111'; + expect(addTauriMediaRetryRevision(blob, 1)).toBe(blob); + }); + + it('encodes the retry fragment into the wrapped URI scheme path', () => { + hoistedIsTauri.mockReturnValue(true); + // Real convertFileSrc percent-encodes the target into the URI path. + hoistedConvertFileSrc.mockImplementation( + (url, protocol) => `${protocol}://localhost/${encodeURIComponent(url)}` + ); + + const revised = addTauriMediaRetryRevision(REWRITTEN, 1)!; + + expect(revised).toContain('__sable_media_cache=3'); + expect(revised).toContain('__sable_media_session=session_abc'); + // The decoded scheme path is the `target` Rust feeds into cache_key(scope, target). + const schemePath = revised.slice('sable-media://localhost/'.length).split('?')[0]; + expect(decodeURIComponent(schemePath ?? '')).toBe(`${INNER}#__sable_media_retry=1`); + }); + + it('replaces an existing retry fragment instead of stacking', () => { + hoistedIsTauri.mockReturnValue(true); + const first = addTauriMediaRetryRevision(REWRITTEN, 1); + const second = addTauriMediaRetryRevision(first, 2); + expect(second).toBe(addTauriMediaRetryRevision(REWRITTEN, 2)); + }); + + it('keeps rewriteAuthenticatedMediaUrl idempotent over revised URLs', () => { + hoistedIsTauri.mockReturnValue(true); + const revised = addTauriMediaRetryRevision(REWRITTEN, 1); + expect(rewriteAuthenticatedMediaUrl(revised)).toBe(revised); + expect(revised).not.toBeUndefined(); + }); +}); + +describe('getTauriMediaRetryTarget', () => { + const WRAPPED = + 'sable-media://https://matrix.example.com/_matrix/client/v1/media/download/example.com/abc123?__sable_media_cache=3&__sable_media_session=session_abc'; + const INNER = 'https://matrix.example.com/_matrix/client/v1/media/download/example.com/abc123'; + const WRAPPED_TARGETS = [ + WRAPPED, + `sable-media://localhost/${encodeURIComponent(INNER)}?__sable_media_cache=3&__sable_media_session=session_abc`, + `https://sable-media.localhost/${encodeURIComponent(INNER)}?__sable_media_cache=3&__sable_media_session=session_abc`, + `http://sable-media.localhost/${encodeURIComponent(INNER)}?__sable_media_cache=3&__sable_media_session=session_abc`, + ]; + + it('returns undefined for the first attempt and outside Tauri', () => { + hoistedIsTauri.mockReturnValue(true); + expect(getTauriMediaRetryTarget(WRAPPED, 0)).toBeUndefined(); + hoistedIsTauri.mockReturnValue(false); + expect(getTauriMediaRetryTarget(WRAPPED, 1)).toBeUndefined(); + }); + + it.each(WRAPPED_TARGETS)( + 'returns the revised http target for encryption registration: %s', + (url) => { + hoistedIsTauri.mockReturnValue(true); + expect(getTauriMediaRetryTarget(url, 1)).toBe(`${INNER}#__sable_media_retry=1`); + } + ); +}); diff --git a/src/app/utils/mediaUrl.ts b/src/app/utils/mediaUrl.ts index 418becff2..d1808f76c 100644 --- a/src/app/utils/mediaUrl.ts +++ b/src/app/utils/mediaUrl.ts @@ -40,6 +40,74 @@ export const rewriteAuthenticatedMediaUrl = (httpUrl: string | null): string | n return `${mediaUrl}${separator}${TAURI_MEDIA_CACHE_VERSION}&__sable_media_session=${sessionScope}`; }; +const TAURI_MEDIA_RETRY_FRAGMENT = '__sable_media_retry'; +const TAURI_MEDIA_OUTER_QUERY_PARAMS = ['__sable_media_cache', '__sable_media_session']; +const TAURI_MEDIA_PROTOCOL = 'sable-media://'; +const TAURI_MEDIA_LOCALHOST = 'localhost'; +const TAURI_MEDIA_LOCALHOST_HOST = 'sable-media.localhost'; + +const getTauriMediaInnerTarget = (mediaUrl: string): string | undefined => { + if (mediaUrl.startsWith(TAURI_MEDIA_PROTOCOL)) { + const wrappedUrl = mediaUrl.slice(TAURI_MEDIA_PROTOCOL.length); + + if (wrappedUrl.startsWith(`${TAURI_MEDIA_LOCALHOST}/`)) { + try { + const parsedUrl = new URL(mediaUrl); + if (parsedUrl.hostname !== TAURI_MEDIA_LOCALHOST) return undefined; + return decodeURIComponent(parsedUrl.pathname.slice(1)); + } catch { + return undefined; + } + } + + return wrappedUrl; + } + + try { + const parsedUrl = new URL(mediaUrl); + if ( + (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') && + parsedUrl.hostname === TAURI_MEDIA_LOCALHOST_HOST + ) { + return decodeURIComponent(parsedUrl.pathname.slice(1)); + } + } catch { + return undefined; + } + + return mediaUrl; +}; + +// Embeds a retry revision as a fragment on the inner http(s) target (stripping the +// outer cache/session markers, which the rewrite re-adds). The fragment makes Rust's +// cache_key(scope, target) distinct but is stripped natively before the upstream +// request and the encryption lookup. Undefined for the first attempt, outside Tauri, +// or when there is no http(s) inner target (e.g. blob: URLs). +export const getTauriMediaRetryTarget = ( + mediaUrl: string, + revision: number +): string | undefined => { + if (revision <= 0 || !isTauri()) return undefined; + const innerTarget = getTauriMediaInnerTarget(mediaUrl); + if (!innerTarget) return undefined; + let parsedUrl: URL; + try { + parsedUrl = new URL(innerTarget); + } catch { + return undefined; + } + if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') return undefined; + TAURI_MEDIA_OUTER_QUERY_PARAMS.forEach((param) => parsedUrl.searchParams.delete(param)); + parsedUrl.hash = `${TAURI_MEDIA_RETRY_FRAGMENT}=${revision}`; + return parsedUrl.toString(); +}; + +export const addTauriMediaRetryRevision = (mediaUrl: string, revision: number): string => { + const target = getTauriMediaRetryTarget(mediaUrl, revision); + if (!target) return mediaUrl; + return rewriteAuthenticatedMediaUrl(target) ?? mediaUrl; +}; + export const mxcUrlToHttp = ( mx: MatrixClient, mxcUrl: string, diff --git a/src/sw-session.test.ts b/src/sw-session.test.ts new file mode 100644 index 000000000..ab0fc3949 --- /dev/null +++ b/src/sw-session.test.ts @@ -0,0 +1,57 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@tauri-apps/api/core', () => ({ isTauri: (): boolean => true })); + +const updateTauriMediaSession = vi.fn< + (baseUrl?: string, accessToken?: string, userId?: string) => Promise +>(() => Promise.resolve()); +vi.mock('./app/utils/tauriMediaAuth', () => ({ + updateTauriMediaSession: (baseUrl?: string, accessToken?: string, userId?: string) => + updateTauriMediaSession(baseUrl, accessToken, userId), +})); + +import { MATRIX_SESSIONS_KEY, updateSessionTokens, type Session } from './app/state/sessions'; +import { pushPersistedSessionToSW } from './sw-session'; + +const baseSession: Session = { + baseUrl: 'https://hs.example', + userId: '@alice:hs.example', + deviceId: 'DEV1', + accessToken: 'stale-token', + refreshToken: 'refresh-1', +}; + +describe('pushPersistedSessionToSW', () => { + beforeEach(() => { + localStorage.clear(); + updateTauriMediaSession.mockClear(); + }); + + it('pushes the refreshed persisted token, not the captured stale one', async () => { + localStorage.setItem(MATRIX_SESSIONS_KEY, JSON.stringify([baseSession])); + + // initClient's refresh writes only the persisted session before the post-init push. + updateSessionTokens(baseSession.userId, { + accessToken: 'fresh-token', + refreshToken: 'refresh-2', + }); + + await pushPersistedSessionToSW(baseSession); + + expect(updateTauriMediaSession).toHaveBeenCalledWith( + baseSession.baseUrl, + 'fresh-token', + baseSession.userId + ); + }); + + it('falls back to the given session when nothing is persisted', async () => { + await pushPersistedSessionToSW(baseSession); + + expect(updateTauriMediaSession).toHaveBeenCalledWith( + baseSession.baseUrl, + baseSession.accessToken, + baseSession.userId + ); + }); +}); diff --git a/src/sw-session.ts b/src/sw-session.ts index 11f4279c3..693f96342 100644 --- a/src/sw-session.ts +++ b/src/sw-session.ts @@ -1,4 +1,5 @@ import { isTauri } from '@tauri-apps/api/core'; +import { getStoredSession } from './app/state/sessions'; import { updateTauriMediaSession } from './app/utils/tauriMediaAuth'; export function pushSessionToSW( @@ -24,3 +25,14 @@ export function pushSessionToSW( }); return Promise.resolve(); } + +// Pushes the persisted session (which may hold a refreshed token) rather than the +// captured one; falls back to it when nothing is persisted. +export function pushPersistedSessionToSW(fallback: { + baseUrl: string; + accessToken: string; + userId: string; +}): Promise { + const session = getStoredSession(fallback.userId) ?? fallback; + return pushSessionToSW(session.baseUrl, session.accessToken, session.userId); +}