Skip to content

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

Merged
7w1 merged 3 commits intoSableClient:devfrom
Just-Insane:fix/sw-media-auth
Mar 25, 2026
Merged

fix: prevent 401 errors on authenticated media after service worker restart#516
7w1 merged 3 commits intoSableClient:devfrom
Just-Insane:fix/sw-media-auth

Conversation

@Just-Insane
Copy link
Contributor

@Just-Insane Just-Insane commented Mar 24, 2026

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

  • 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:

  • 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).

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)

Three changes to src/sw.ts:

1. Fix early-return bug in fetch handler: when sessions.get(clientId)
   returns a session but validMediaRequest(url, session.baseUrl) fails
   (e.g. multi-account users on different homeservers, or URL format
   mismatch), the old code returned without calling event.respondWith(),
   causing the browser to make an unauthenticated request → 401.
   Now we only short-circuit if BOTH conditions are met.

2. Proactively broadcast requestSession to all window clients in the
   activate event. After a SW restart the sessions Map is empty; the
   old code relied on the first intercepted media fetch to trigger
   requestSessionWithTimeout. Now the SW pre-populates the Map right
   after claiming clients, eliminating the 3-second race window.

3. Add loadPersistedSession() as a final fallback in the fetch handler.
   If requestSessionWithTimeout returns nothing (
Three changes to src/sw.ts:

1. Fix early-return bug in fetch handler: when sessions.get(clientId)
   returns a session buo a
1. Fix early-return bug i
On SW restart the in-memory sessions Map is empty. Previously the fetch
handler fell through to requestSessionWithTimeout (3 s race window), so
all simultaneous thumbnail loads during that window 401'd.

Changes:
- Populate preloadedSession from Cache Storage in the activate handler
  so media fetches get immediate auth before the first live setSession
  arrives from the page.
- Include preloadedSession in the byBaseUrl fast path so the synchronous
  branch handles the burst of thumbnail requests without waiting at all.
- Clear preloadedSession as soon as any real setSession arrives so stale
  tokens cannot linger.
- Handle empty clientId (uncontrolled-context fetches) by falling through
  to byBaseUrl / preloadedSession / loadPersistedSession instead of doing
  a bare return that bypassed respondWith and caused an unauthenticated
  request.
@Just-Insane Just-Insane marked this pull request as ready for review March 24, 2026 16:31
@Just-Insane Just-Insane requested review from 7w1 and hazre as code owners March 24, 2026 16:31
@Just-Insane
Copy link
Contributor Author

Just-Insane commented Mar 24, 2026

This may actually cause issues with resuming from background in iOS - it seems like new messages don't show in the timeline until the PWA is closed. More testing required.

Edit:

Actually, I think the messages are just rendering out of order (which I don't think is related to this PR) - Clicking on a message notification brings me to the message, at the top of the synced message group.

Should be fixed by 1. in #529

@7w1 7w1 added this pull request to the merge queue Mar 25, 2026
Merged via the queue into SableClient:dev with commit ec2dcfb Mar 25, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants