Fixed problem where auth is bypassed

This commit is contained in:
Roman Krček
2025-09-03 10:17:20 +02:00
parent 3f771bf7b0
commit 1d4cae35a5

View File

@@ -31,56 +31,51 @@ self.addEventListener('activate', (event) => {
});
self.addEventListener('fetch', (event) => {
// ignore POST requests etc
if (event.request.method !== 'GET') return;
// --- START: MODIFICATION TO PREVENT CACHING PRIVATE ROUTES ---
const url = new URL(event.request.url);
// If the request is for a private route, always fetch from the network.
// This ensures that server-side authentication checks are not bypassed by the cache.
if (url.pathname.startsWith('/private')) {
event.respondWith(fetch(event.request));
return;
}
// --- END: MODIFICATION ---
async function respond() {
const url = new URL(event.request.url);
// Skip caching for auth routes
if (url.pathname.startsWith('/auth/')) {
return fetch(event.request);
}
const cache = await self.caches.open(CACHE);
const cache = await caches.open(CACHE);
// `build`/`files` can always be served from the cache
// `build`/`prerendered` pages are cached on install.
// If the page exists in the cache, serve it directly.
if (ASSETS.includes(url.pathname)) {
const response = await cache.match(url.pathname);
if (response) {
return response;
const cachedResponse = await cache.match(url.pathname);
if (cachedResponse) {
return cachedResponse;
}
}
// for everything else, try the network first, but
// fall back to the cache if we're offline
// For everything else, try to get it from the network.
try {
const response = await fetch(event.request);
// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}
// Do not cache private pages
if (response.status === 200 && !url.pathname.startsWith('/private')) {
// If the request is for a file from the build directory, cache it.
if (response.status === 200 && url.pathname.startsWith(`/${build[0]}/`)) {
cache.put(event.request, response.clone());
}
return response;
} catch (err) {
const response = await cache.match(event.request);
if (response) {
return response;
} catch (error) {
// If the network is unavailable, fall back to the cache.
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
return cachedResponse;
}
// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
return new Response('Not found', { status: 404 });
}
event.respondWith(respond());