2026-06-21 23:28:31 +08:00
|
|
|
const CACHE = 'v1';
|
2026-06-22 14:59:24 +08:00
|
|
|
const LOGIN = '/login';
|
|
|
|
|
const EXPIRE_MS = 3 * 60 * 60 * 1000;
|
2026-06-21 23:28:31 +08:00
|
|
|
|
|
|
|
|
self.addEventListener('install', () => self.skipWaiting());
|
|
|
|
|
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
|
|
|
|
|
|
|
|
|
|
self.addEventListener('fetch', e => {
|
|
|
|
|
const req = e.request;
|
2026-06-22 14:59:24 +08:00
|
|
|
const url = new URL(req.url);
|
|
|
|
|
|
|
|
|
|
// 登录页、静态资源不拦截
|
|
|
|
|
if (url.pathname === '/login' || url.pathname.startsWith('/_next/') ||
|
|
|
|
|
url.pathname.endsWith('.js') || url.pathname.endsWith('.css') ||
|
|
|
|
|
url.pathname.endsWith('.ico') || url.pathname.endsWith('.woff2')) {
|
2026-06-21 23:28:31 +08:00
|
|
|
e.respondWith(fetch(req));
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
e.respondWith((async () => {
|
|
|
|
|
const token = self.__auth_token;
|
2026-06-22 13:01:37 +08:00
|
|
|
const tokenTime = self.__auth_time || 0;
|
|
|
|
|
|
|
|
|
|
if (!token || (Date.now() - tokenTime > EXPIRE_MS)) {
|
2026-06-22 14:59:24 +08:00
|
|
|
self.__auth_token = null;
|
|
|
|
|
self.__auth_time = 0;
|
2026-06-22 13:01:37 +08:00
|
|
|
return Response.redirect(LOGIN, 302);
|
2026-06-21 23:28:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const headers = new Headers(req.headers);
|
2026-06-22 14:59:24 +08:00
|
|
|
headers.set('X-Auth-User', token);
|
2026-06-21 23:28:31 +08:00
|
|
|
const res = await fetch(new Request(req, { headers }));
|
|
|
|
|
|
|
|
|
|
if (res.status === 401) {
|
2026-06-22 13:01:37 +08:00
|
|
|
self.__auth_token = null;
|
|
|
|
|
self.__auth_time = 0;
|
2026-06-21 23:28:31 +08:00
|
|
|
return Response.redirect(LOGIN, 302);
|
|
|
|
|
}
|
2026-06-22 14:59:24 +08:00
|
|
|
|
2026-06-21 23:28:31 +08:00
|
|
|
return res;
|
|
|
|
|
})());
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
self.addEventListener('message', e => {
|
|
|
|
|
if (e.data && e.data.type === 'SET_TOKEN') {
|
|
|
|
|
self.__auth_token = e.data.token;
|
2026-06-22 13:01:37 +08:00
|
|
|
self.__auth_time = Date.now();
|
2026-06-21 23:28:31 +08:00
|
|
|
}
|
|
|
|
|
if (e.data && e.data.type === 'CLEAR_TOKEN') {
|
|
|
|
|
self.__auth_token = null;
|
2026-06-22 13:01:37 +08:00
|
|
|
self.__auth_time = 0;
|
2026-06-21 23:28:31 +08:00
|
|
|
}
|
|
|
|
|
});
|