🎧 Your Personal Streaming Service
Go airsonicmadsonicmedia-servermusicmusic-servernavidromeopensubsonicraspberry-piself-hostedstreamerstreaming-apistreaming-audiosubsonicsubsonic-server
fix(ui): stop precaching index.html so logins can't show the wrong user (#5882)
Deluan Quintão279ff98e0d5f
diff --git a/.gitignore b/.gitignoreindex fc8eaac69..3567a7d90 100644--- a/.gitignore+++ b/.gitignore@@ -40,3 +40,4 @@ openspec/.agentsgo.work*.worktrees/+.playwright-mcp/diff --git a/ui/public/offline.html b/ui/public/offline.htmlindex 72f2d04ae..e3c44e8d3 100644--- a/ui/public/offline.html+++ b/ui/public/offline.html@@ -5,6 +5,6 @@<p id="errorMessageDescription" style="text-align:center;font-size:21px;font-family:arial;margin-top:28px">It looks like we are having trouble connecting.<br/>-Please check your internet connection and try again.</p>+Please check your internet connection, or try again in a moment.</p></body></html>\ No newline at end of filediff --git a/ui/src/authProvider.js b/ui/src/authProvider.jsindex 813a4f5b4..18badbc9c 100644--- a/ui/src/authProvider.js+++ b/ui/src/authProvider.js@@ -1,7 +1,6 @@import { jwtDecode } from 'jwt-decode'import { baseUrl } from './utils'import config from './config'-import { removeHomeCache } from './utils/removeHomeCache'// config sent from server may contain authentication info, for example when the user is authenticated// by a reverse proxy request header@@ -49,7 +48,6 @@ const authProvider = {storeAuthenticationInfo(response)// Avoid "going to create admin" dialog after logout/login without a refreshconfig.firstTime = false- removeHomeCache()return response}).catch((error) => {diff --git a/ui/src/dataProvider/httpClient.js b/ui/src/dataProvider/httpClient.jsindex 3820f658d..706486fa6 100644--- a/ui/src/dataProvider/httpClient.js+++ b/ui/src/dataProvider/httpClient.js@@ -3,7 +3,6 @@ import { v4 as uuidv4 } from 'uuid'import { baseUrl } from '../utils'import config from '../config'import { jwtDecode } from 'jwt-decode'-import { removeHomeCache } from '../utils/removeHomeCache'const customAuthorizationHeader = 'X-ND-Authorization'export const clientUniqueIdHeader = 'X-ND-Client-Unique-Id'@@ -27,7 +26,6 @@ const httpClient = (url, options = {}) => {localStorage.setItem('userId', decoded.uid)// Avoid going to create admin dialog after logout/login without a refreshconfig.firstTime = false- removeHomeCache()}return response})diff --git a/ui/src/sw.js b/ui/src/sw.jsindex f4a5664b8..edc272850 100644--- a/ui/src/sw.js+++ b/ui/src/sw.js@@ -1,5 +1,7 @@/* eslint-disable */+import { createNavigationHandler } from './swNavigation'+// documentation: https://developers.google.com/web/tools/workbox/modules/workbox-swimportScripts('3rdparty/workbox/workbox-sw.js')@@ -36,17 +38,13 @@ self.addEventListener('install', async (event) => {})const networkOnly = new workbox.strategies.NetworkOnly()-const navigationHandler = async (params) => {- try {- // Attempt a network request.- return await networkOnly.handle(params)- } catch (error) {- // If it fails, return the cached HTML.- return caches.match(FALLBACK_HTML_URL, {- cacheName: CACHE_NAME,- })- }-}+const fallbackToCachedHtml = () =>+ caches.match(FALLBACK_HTML_URL, { cacheName: CACHE_NAME })++const navigationHandler = createNavigationHandler(+ networkOnly,+ fallbackToCachedHtml,+)// self.__WB_MANIFEST is default injection pointworkbox.precaching.precacheAndRoute(self.__WB_MANIFEST)diff --git a/ui/src/swNavigation.js b/ui/src/swNavigation.jsnew file mode 100644index 000000000..28d01eaef--- /dev/null+++ b/ui/src/swNavigation.js@@ -0,0 +1,14 @@+// Lives outside sw.js so it can be unit tested: sw.js only loads inside a+// service worker, where workbox arrives via importScripts.+export const createNavigationHandler =+ (networkOnly, offlineFallback) => async (params) => {+ try {+ // Attempt a network request.+ const response = await networkOnly.handle(params)+ // A 5xx reaches us as a normal response, but carries no usable app+ return response.status >= 500 ? offlineFallback() : response+ } catch (error) {+ // If it fails, return the cached HTML.+ return offlineFallback()+ }+ }diff --git a/ui/src/swNavigation.test.js b/ui/src/swNavigation.test.jsnew file mode 100644index 000000000..8ab749757--- /dev/null+++ b/ui/src/swNavigation.test.js@@ -0,0 +1,62 @@+import { describe, it, expect, vi } from 'vitest'+import { createNavigationHandler } from './swNavigation'++const OFFLINE = { offlinePage: true }++const setup = (networkResult) => {+ const networkOnly = {+ handle: vi.fn(() =>+ networkResult instanceof Error+ ? Promise.reject(networkResult)+ : Promise.resolve(networkResult),+ ),+ }+ const offlineFallback = vi.fn(() => Promise.resolve(OFFLINE))+ return {+ networkOnly,+ offlineFallback,+ handler: createNavigationHandler(networkOnly, offlineFallback),+ }+}++describe('createNavigationHandler', () => {+ it('serves the response from the network', async () => {+ const response = { status: 200 }+ const { handler, offlineFallback } = setup(response)++ await expect(handler({})).resolves.toBe(response)+ expect(offlineFallback).not.toHaveBeenCalled()+ })++ it('falls back to the offline page when the network fails', async () => {+ const { handler } = setup(new Error('Failed to fetch'))++ await expect(handler({})).resolves.toBe(OFFLINE)+ })++ it.each([500, 502, 503])(+ 'falls back to the offline page on %i',+ async (status) => {+ const { handler } = setup({ status })++ await expect(handler({})).resolves.toBe(OFFLINE)+ },+ )++ it.each([304, 401, 404])('passes %i through untouched', async (status) => {+ const response = { status }+ const { handler, offlineFallback } = setup(response)++ await expect(handler({})).resolves.toBe(response)+ expect(offlineFallback).not.toHaveBeenCalled()+ })++ it('passes the navigation params to the network strategy', async () => {+ const params = { request: { url: '/app/' } }+ const { handler, networkOnly } = setup({ status: 200 })++ await handler(params)++ expect(networkOnly.handle).toHaveBeenCalledWith(params)+ })+})diff --git a/ui/src/utils/removeHomeCache.js b/ui/src/utils/removeHomeCache.jsdeleted file mode 100644index 08ed720e0..000000000--- a/ui/src/utils/removeHomeCache.js+++ /dev/null@@ -1,20 +0,0 @@-export const removeHomeCache = async () => {- try {- const workboxKey = (await caches.keys()).find((key) =>- key.startsWith('workbox-precache'),- )- if (!workboxKey) return-- const workboxCache = await caches.open(workboxKey)- const indexKey = (await workboxCache.keys()).find((key) =>- key.url.includes('app/index.html'),- )-- if (indexKey) {- await workboxCache.delete(indexKey)- }- } catch (e) {- // eslint-disable-next-line no-console- console.error('error reading cache', e)- }-}diff --git a/ui/vite.config.js b/ui/vite.config.jsindex 9d9c845f1..182e825b0 100644--- a/ui/vite.config.js+++ b/ui/vite.config.js@@ -16,6 +16,9 @@ export default defineConfig({filename: 'sw.js',injectManifest: {maximumFileSizeToCacheInBytes: 3 * 1024 * 1024, // 3 MiB+ // index.html is rendered per-user by the server, so a precached copy+ // would pin one user's config (and auth payload) across logins+ globIgnores: ['index.html'],},devOptions: {enabled: true,