fix: recover media auth after token refresh (#1450)

<!-- 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 #

#### 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
- [ ] 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:
7w1 authored and GitHub committed 2026-07-28 19:20:20 +00:00
commit 7c2d2ffbed
6 files changed
+698 -61

No files matched your search

+31
View File
@@ -65,6 +65,10 @@ describe('createSessionTokenRefresher', () => {
mocks.pushSessionToSW.mockReset().mockResolvedValue(undefined);
getAuthMetadata.mockReset().mockResolvedValue(metadata);
localStorage.setItem(MATRIX_SESSIONS_KEY, JSON.stringify([session]));
Object.defineProperty(navigator, 'locks', {
configurable: true,
value: undefined,
});
});
it('serializes concurrent same-user refreshers and reuses rotated tokens', async () => {
@@ -97,4 +101,31 @@ describe('createSessionTokenRefresher', () => {
refreshToken: 'new-refresh',
});
});
it('uses the current stored token after waiting for the cross-tab refresh lock', async () => {
const request = vi.fn<(name: string, callback: () => Promise<unknown>) => Promise<unknown>>(
async (_name, callback) => {
localStorage.setItem(
MATRIX_SESSIONS_KEY,
JSON.stringify([
{ ...session, accessToken: 'other-access', refreshToken: 'other-refresh' },
])
);
return callback();
}
);
Object.defineProperty(navigator, 'locks', {
configurable: true,
value: { request },
});
const refresher = createSessionTokenRefresher(session, mx)!;
await expect(refresher.tokenRefreshFunction('old-refresh')).resolves.toEqual({
accessToken: 'other-access',
refreshToken: 'other-refresh',
});
expect(request).toHaveBeenCalledWith('sable-oidc-refresh', expect.any(Function));
expect(mocks.refresh).not.toHaveBeenCalled();
});
});
+47 -16
View File
@@ -26,6 +26,18 @@ export const assertAuthMetadataIssuer = (
export type SessionTokenRefresher = Pick<TokenRefresher, 'tokenRefreshFunction'>;
const refreshQueues = new Map<string, Promise<unknown>>();
const inFlightRefreshes = new Map<string, Promise<unknown>>();
const OIDC_REFRESH_LOCK_NAME = 'sable-oidc-refresh';
type WebLocks = {
request<T>(name: string, callback: () => Promise<T>): Promise<T>;
};
const getWebLocks = (): WebLocks | undefined => {
if (typeof navigator === 'undefined') return undefined;
const locks = (navigator as Navigator & { locks?: WebLocks }).locks;
return locks && typeof locks.request === 'function' ? locks : undefined;
};
const getStoredSession = (userId: string): Session | undefined =>
getLocalStorageItem<Session[]>(MATRIX_SESSIONS_KEY, []).find(
@@ -43,6 +55,10 @@ const withRefreshQueue = async <T>(userId: string, operation: () => Promise<T>):
return run;
};
export const waitForSessionTokenRefresh = async (userId: string): Promise<void> => {
await inFlightRefreshes.get(userId)?.catch(() => undefined);
};
export const createSessionTokenRefresher = (
session: Session,
mx: MatrixClient
@@ -87,27 +103,42 @@ export const createSessionTokenRefresher = (
return {
tokenRefreshFunction: async (refreshToken) => {
return withRefreshQueue(session.userId, async () => {
const refresh = withRefreshQueue(session.userId, async () => {
const tokenRefresher = await getTokenRefresher();
// Another tab may have rotated the token; reusing a consumed one revokes the session.
const storedSession = getStoredSession(session.userId);
const latestRefreshToken =
storedSession?.refreshToken ??
getStoredSessionRefreshToken(session.userId) ??
refreshToken;
if (storedSession && latestRefreshToken !== refreshToken) {
const refreshWithCurrentState = async () => {
// Another tab may have rotated the token; reusing a consumed one revokes the session.
const storedSession = getStoredSession(session.userId);
const latestRefreshToken =
storedSession?.refreshToken ??
getStoredSessionRefreshToken(session.userId) ??
refreshToken;
if (storedSession && latestRefreshToken !== refreshToken) {
return {
accessToken: storedSession.accessToken,
refreshToken: latestRefreshToken,
};
}
const tokens = await tokenRefresher.tokenRefreshFunction(latestRefreshToken);
return {
accessToken: storedSession.accessToken,
refreshToken: latestRefreshToken,
...tokens,
// OAuth servers may omit a replacement refresh token, in which case the old one remains valid.
refreshToken: tokens.refreshToken ?? latestRefreshToken,
};
}
const tokens = await tokenRefresher.tokenRefreshFunction(latestRefreshToken);
return {
...tokens,
// OAuth servers may omit a replacement refresh token, in which case the old one remains valid.
refreshToken: tokens.refreshToken ?? latestRefreshToken,
};
const locks = getWebLocks();
return locks
? locks.request(OIDC_REFRESH_LOCK_NAME, refreshWithCurrentState)
: refreshWithCurrentState();
});
inFlightRefreshes.set(session.userId, refresh);
try {
return await refresh;
} finally {
if (inFlightRefreshes.get(session.userId) === refresh) {
inFlightRefreshes.delete(session.userId);
}
}
},
};
};
+52 -3
View File
@@ -7,6 +7,8 @@ const {
mockAddEventListener,
mockReady,
mockPushSessionToSW,
mockWaitForSessionTokenRefresh,
mockGetLocalStorageItem,
mockWarn,
} = vi.hoisted(() => ({
mockHasServiceWorker: vi.fn<() => boolean>(),
@@ -32,6 +34,8 @@ const {
>(),
mockReady: Promise.resolve(undefined),
mockPushSessionToSW: vi.fn<(baseUrl?: string, accessToken?: string, userId?: string) => void>(),
mockWaitForSessionTokenRefresh: vi.fn<(userId: string) => Promise<void>>(),
mockGetLocalStorageItem: vi.fn<(key: string, fallback: unknown) => unknown>(),
mockWarn: vi.fn<(...args: unknown[]) => void>(),
}));
@@ -44,6 +48,10 @@ vi.mock('./sw-session', () => ({
pushSessionToSW: mockPushSessionToSW,
}));
vi.mock('./client/oidcTokenRefresher', () => ({
waitForSessionTokenRefresh: mockWaitForSessionTokenRefresh,
}));
vi.mock('./app/state/sessions', () => ({
getFallbackSession: vi.fn<() => undefined>(() => undefined),
MATRIX_SESSIONS_KEY: 'matrix-sessions',
@@ -51,9 +59,7 @@ vi.mock('./app/state/sessions', () => ({
}));
vi.mock('./app/state/utils/atomWithLocalStorage', () => ({
getLocalStorageItem: vi.fn<(key: string, fallback: unknown) => unknown>(
(_: string, fallback: unknown) => fallback
),
getLocalStorageItem: mockGetLocalStorageItem,
}));
vi.mock('./app/utils/debug', () => ({
@@ -66,6 +72,8 @@ describe('registerAppServiceWorker', () => {
beforeEach(() => {
vi.clearAllMocks();
mockHasServiceWorker.mockReturnValue(false);
mockWaitForSessionTokenRefresh.mockReset().mockResolvedValue(undefined);
mockGetLocalStorageItem.mockImplementation((_key, fallback) => fallback);
Object.defineProperty(window, 'confirm', {
configurable: true,
value: vi.fn<(message?: string) => boolean>(() => false),
@@ -128,4 +136,45 @@ describe('registerAppServiceWorker', () => {
expect(mockPushSessionToSW).toHaveBeenCalledTimes(1);
});
it('waits for the active session refresh before replying to a session request', async () => {
let activeSession: { baseUrl: string; userId: string; accessToken: string } | undefined;
mockGetLocalStorageItem.mockImplementation((key, fallback) => {
if (key === 'matrix-sessions') return activeSession ? [activeSession] : [];
if (key === 'active-session') return activeSession?.userId;
return fallback;
});
mockHasServiceWorker.mockReturnValue(true);
registerAppServiceWorker();
await Promise.resolve();
await Promise.resolve();
mockPushSessionToSW.mockReset();
activeSession = {
baseUrl: 'https://hs.example',
userId: '@alice:hs.example',
accessToken: 'new-access',
};
let resolveRefresh!: () => void;
mockWaitForSessionTokenRefresh.mockReturnValueOnce(
new Promise<void>((resolve) => {
resolveRefresh = resolve;
})
);
const listener = mockAddEventListener.mock.calls.find(([type]) => type === 'message')?.[1] as
| ((event: MessageEvent) => void)
| undefined;
listener?.({ data: { type: 'requestSession' } } as MessageEvent);
expect(mockWaitForSessionTokenRefresh).toHaveBeenCalledWith('@alice:hs.example');
expect(mockPushSessionToSW).not.toHaveBeenCalled();
resolveRefresh();
await vi.waitFor(() =>
expect(mockPushSessionToSW).toHaveBeenCalledWith(
'https://hs.example',
'new-access',
'@alice:hs.example'
)
);
});
});
+23 -6
View File
@@ -5,8 +5,25 @@ import { getFallbackSession, MATRIX_SESSIONS_KEY, ACTIVE_SESSION_KEY } from './a
import { getLocalStorageItem } from './app/state/utils/atomWithLocalStorage';
import { hasServiceWorker } from './app/utils/platform';
import { pushSessionToSW } from './sw-session';
import { waitForSessionTokenRefresh } from './client/oidcTokenRefresher';
const log = createLogger('service-worker-bootstrap');
const REFRESH_WAIT_TIMEOUT_MS = 2500;
const waitForRefreshWithTimeout = async (userId: string): Promise<void> => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<void>((resolve) => {
timeoutId = setTimeout(resolve, REFRESH_WAIT_TIMEOUT_MS);
});
await Promise.race([waitForSessionTokenRefresh(userId), timeout]);
if (timeoutId !== undefined) clearTimeout(timeoutId);
};
const getActiveSession = () => {
const sessions = getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []);
const activeId = getLocalStorageItem<string | undefined>(ACTIVE_SESSION_KEY, undefined);
return sessions.find((s) => s.userId === activeId) ?? sessions[0] ?? getFallbackSession();
};
const showUpdateAvailablePrompt = (registration: ServiceWorkerRegistration) => {
const DONT_SHOW_PROMPT_KEY = 'cinny_dont_show_sw_update_prompt';
@@ -23,11 +40,11 @@ const showUpdateAvailablePrompt = (registration: ServiceWorkerRegistration) => {
);
};
const sendSessionToSW = () => {
const sessions = getLocalStorageItem<Sessions>(MATRIX_SESSIONS_KEY, []);
const activeId = getLocalStorageItem<string | undefined>(ACTIVE_SESSION_KEY, undefined);
const active = sessions.find((s) => s.userId === activeId) ?? sessions[0] ?? getFallbackSession();
pushSessionToSW(active?.baseUrl, active?.accessToken, active?.userId);
const sendSessionToSW = async () => {
const active = getActiveSession();
if (active) await waitForRefreshWithTimeout(active.userId);
const current = getActiveSession();
await pushSessionToSW(current?.baseUrl, current?.accessToken, current?.userId);
};
export function registerAppServiceWorker() {
@@ -76,7 +93,7 @@ export function registerAppServiceWorker() {
const { type } = data as { type?: unknown };
if (type === 'requestSession') {
sendSessionToSW();
void sendSessionToSW();
}
if (data.type === 'token' && data.id) {
+28
View File
@@ -127,4 +127,32 @@ describe('service worker media auth recovery', () => {
swTestHooks.setSession(client.id, 'new-token', 'https://matrix.example.org');
await expect(nextRequest).resolves.toMatchObject({ accessToken: 'new-token' });
});
it('does not retry when the refreshed session has the same access token', async () => {
const client = {
id: 'client-same-token',
postMessage: vi.fn(),
} as unknown as Client;
clients.set(client.id, client);
const session = { accessToken: 'same-token', baseUrl: 'https://matrix.example.org' };
vi.mocked(fetch).mockResolvedValue(
new Response(JSON.stringify({ errcode: 'M_UNKNOWN_TOKEN' }), { status: 401 })
);
const request = new Request(
'https://matrix.example.org/_matrix/client/v1/media/download/example.org/media-id'
);
const recovery = swTestHooks.respondWithMediaAuthRecovery(
request,
session,
'follow',
client.id
);
await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalledTimes(1));
swTestHooks.setSession(client.id, 'same-token', session.baseUrl);
await expect(recovery).resolves.toHaveProperty('status', 401);
expect(fetch).toHaveBeenCalledTimes(1);
});
});