mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-24 11:01:17 -08:00
fix: retry tauri media after token refresh (#1498)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description - Prevents refreshed OIDC tokens from being overwritten in Tauri. - Makes image and video Retry issue a fresh native media request. - Avoids caching native media errors. Fixes # #### 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: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my own code - [x] 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:
11 files changed
+451
-16
No files matched your search
@@ -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<R: Runtime>(
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
fn error_response(status: StatusCode) -> Response<Vec<u8>> {
|
||||
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")
|
||||
|
||||
@@ -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<ArrayBuffer>>(),
|
||||
decryptFile: vi.fn<() => Promise<ArrayBuffer>>(),
|
||||
}));
|
||||
|
||||
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(
|
||||
<ImageContent
|
||||
url="mxc://example.org/abc123"
|
||||
renderImage={(props) => {
|
||||
srcs.push(props.src);
|
||||
return <img alt="preview" src={props.src} onError={props.onError} />;
|
||||
}}
|
||||
renderViewer={() => <div>viewer</div>}
|
||||
/>
|
||||
);
|
||||
|
||||
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>();
|
||||
|
||||
@@ -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<string | null>(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);
|
||||
};
|
||||
|
||||
|
||||
@@ -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<ArrayBuffer>>(),
|
||||
downloadEncryptedMedia: vi.fn<() => Promise<ArrayBuffer>>(),
|
||||
decryptFile: vi.fn<() => Promise<ArrayBuffer>>(),
|
||||
}));
|
||||
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(
|
||||
<VideoContent
|
||||
body="clip"
|
||||
mimeType="video/mp4"
|
||||
url="mxc://example.org/vid123"
|
||||
info={{ w: 640, h: 360, duration: 1000 }}
|
||||
renderVideo={(props) => {
|
||||
srcs.push(props.src);
|
||||
return (
|
||||
<video data-testid="video" src={props.src} onError={props.onError}>
|
||||
<track kind="captions" />
|
||||
</video>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
|
||||
@@ -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])
|
||||
);
|
||||
|
||||
@@ -197,10 +197,13 @@ export const updateSessionTokens = (
|
||||
notifySessionChanged();
|
||||
};
|
||||
|
||||
export const getStoredSessionRefreshToken = (userId: string): string | undefined =>
|
||||
export const getStoredSession = (userId: string): Session | undefined =>
|
||||
getLocalStorageItem<Sessions>(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<string | undefined>(
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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<void>
|
||||
>(() => 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
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<void> {
|
||||
const session = getStoredSession(fallback.userId) ?? fallback;
|
||||
return pushSessionToSW(session.baseUrl, session.accessToken, session.userId);
|
||||
}
|
||||
Reference in new issue
Block a user