fix: prevent 401 errors on authenticated media after service worker restart (#516)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

The service worker (SW) loses its in-memory session on restart (e.g.
after the browser kills the SW background process). Any authenticated
media request arriving before the SW re-reads session data from cache
was returning a 401.

Two fixes:
1. **Eager pre-load on `activate`**: the SW now reads session data from
the cache during the `activate` event, so it is available immediately
when the first `fetch` event fires.
2. **Graceful fallback in fetch handler**: if session data is still
missing or stale at request time, the request is passed through to the
network without injecting a bad `Authorization` header (previously an
empty/invalid token was injected, causing the 401).

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
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [X] 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. -->

Attempts to resolve issues with the service worker not properly storing
and/or refreshing media auth tokens on load. The changes mainly serve to
ensure that a session is persisted during restarts (and then drop the
persisted session once a live one is available). Also helps with
refreshing tokens (`sw.ts` ln 651-661)
This commit is contained in:
7w1 authored and GitHub committed 2026-03-25 02:56:58 +00:00
commit ec2dcfbe3e
2 files changed
+57 -8

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix service worker authenticated media requests returning 401 errors after SW restart or when session data is missing/stale.
+52 -8
View File
@@ -118,6 +118,14 @@ type SessionInfo = {
*/
const sessions = new Map<string, SessionInfo>();
/**
* Session pre-loaded from cache on SW activation. Acts as an immediate
* fallback so media fetches don't 401 during the window between SW restart
* and the first live setSession message from the page.
* Cleared as soon as any real setSession call comes in.
*/
let preloadedSession: SessionInfo | undefined;
const clientToResolve = new Map<string, (value: SessionInfo | undefined) => void>();
const clientToSessionPromise = new Map<string, Promise<SessionInfo | undefined>>();
@@ -142,12 +150,15 @@ function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, us
userId: typeof userId === 'string' ? userId : undefined,
};
sessions.set(clientId, info);
// A real session has arrived — discard the preloaded fallback.
preloadedSession = undefined;
console.debug('[SW] setSession: stored', clientId, baseUrl);
// Persist so push-event fetches work after iOS restarts the SW.
persistSession(info).catch(() => undefined);
} else {
// Logout or invalid session
sessions.delete(clientId);
preloadedSession = undefined;
console.debug('[SW] setSession: removed', clientId);
clearPersistedSession().catch(() => undefined);
}
@@ -460,6 +471,15 @@ self.addEventListener('activate', (event: ExtendableEvent) => {
(async () => {
await self.clients.claim();
await cleanupDeadClients();
// Pre-load the persisted session into memory so that media fetches arriving
// before the first setSession message from the page are immediately
// authenticated rather than falling through to a 3-second timeout.
preloadedSession = await loadPersistedSession();
// Proactively request sessions from all window clients so the sessions Map
// is pre-populated after a SW restart, rather than waiting for the first
// media fetch to trigger requestSessionWithTimeout.
const windowClients = await self.clients.matchAll({ type: 'window' });
windowClients.forEach((client) => client.postMessage({ type: 'requestSession' }));
})()
);
});
@@ -579,7 +599,6 @@ self.addEventListener('fetch', (event: FetchEvent) => {
if (method !== 'GET' || !mediaPath(url)) return;
const { clientId } = event;
if (!clientId) return;
// For browser sub-resource loads (images, video, audio, etc.), 'follow' is
// the correct mode: the auth header is sent to the Matrix server which owns
@@ -588,11 +607,9 @@ self.addEventListener('fetch', (event: FetchEvent) => {
// the browser cannot render as an <img>/<video>/etc.
const redirect: RequestRedirect = 'follow';
const session = sessions.get(clientId);
if (session) {
if (validMediaRequest(url, session.baseUrl)) {
event.respondWith(fetch(url, { ...fetchConfig(session.accessToken), redirect }));
}
const session = clientId ? sessions.get(clientId) : undefined;
if (session && validMediaRequest(url, session.baseUrl)) {
event.respondWith(fetch(url, { ...fetchConfig(session.accessToken), redirect }));
return;
}
@@ -604,17 +621,44 @@ self.addEventListener('fetch', (event: FetchEvent) => {
// as the wrong one.
// Thus any logic in the future which cares about which user is authenticating the request
// might break this. Also, again, it is technically wrong.
const byBaseUrl = [...sessions.values()].find((s) => validMediaRequest(url, s.baseUrl));
// Also checks preloadedSession — populated from cache at SW activate — for the window
// between SW restart and the first live setSession arriving from the page.
const byBaseUrl =
[...sessions.values()].find((s) => validMediaRequest(url, s.baseUrl)) ??
(preloadedSession && validMediaRequest(url, preloadedSession.baseUrl)
? preloadedSession
: undefined);
if (byBaseUrl) {
event.respondWith(fetch(url, { ...fetchConfig(byBaseUrl.accessToken), redirect }));
return;
}
// No clientId: the fetch came from a context not associated with a specific
// window (e.g. a prerender). Fall back to the persisted session directly.
if (!clientId) {
event.respondWith(
loadPersistedSession().then((persisted) => {
if (persisted && validMediaRequest(url, persisted.baseUrl)) {
return fetch(url, { ...fetchConfig(persisted.accessToken), redirect });
}
return fetch(event.request);
})
);
return;
}
event.respondWith(
requestSessionWithTimeout(clientId).then((s) => {
requestSessionWithTimeout(clientId).then(async (s) => {
// Primary: session received from the live client window.
if (s && validMediaRequest(url, s.baseUrl)) {
return fetch(url, { ...fetchConfig(s.accessToken), redirect });
}
// Fallback: try the persisted session (helps when SW restarts on iOS and
// the client window hasn't responded to requestSession yet).
const persisted = await loadPersistedSession();
if (persisted && validMediaRequest(url, persisted.baseUrl)) {
return fetch(url, { ...fetchConfig(persisted.accessToken), redirect });
}
console.warn(
'[SW fetch] No valid session for media request',
{ url, clientId, hasSession: !!s },