browser-files-sw.js
composeApp/src/wasmJsMain/resources/browser-files-sw.js
1/* Serves only same-origin, origin-private media. No remote responses or application data are cached. */2// Service workers must import their dependencies while the script initially evaluates.3importScripts('browser-archives.js', 'vendor/zipjs-2.23.0/zip-native.min.js');4self.addEventListener('install', event => event.waitUntil(self.skipWaiting()));5self.addEventListener('activate', event => event.waitUntil(self.clients.claim()));6const prefix = new URL('__yokan_files__/', self.registration.scope).pathname;7const contentTypes = {8 jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', avif: 'image/avif', gif: 'image/gif',9 html: 'text/html; charset=utf-8', txt: 'text/plain; charset=utf-8', mp4: 'video/mp4', webm: 'video/webm',10 m3u8: 'application/vnd.apple.mpegurl', ts: 'video/mp2t', m4s: 'video/iso.segment', vtt: 'text/vtt', srt: 'application/x-subrip',11};12async function serve(request, url, event) {13 if (!['GET', 'HEAD'].includes(request.method)) return new Response(null, { status: 405 });14 try {15 const parts = url.pathname.slice(prefix.length).split('/').map(decodeURIComponent);16 if (parts[0] !== 'yokan' || parts.some(p => !p || p === '.' || p === '..' || /[\\/\0]/.test(p))) return new Response(null, { status: 400 });17 let directory = await navigator.storage.getDirectory();18 for (const part of parts.slice(0, -1)) directory = await directory.getDirectoryHandle(part);19 const file = await (await directory.getFileHandle(parts.at(-1))).getFile();20 const entryName = url.searchParams.get('entry');21 if (entryName !== null) {22 if (!globalThis.yokanBrowserArchives) importScripts('browser-archives.js');23 const metadataOnly = request.method === 'HEAD' || request.headers.has('Range');24 const entry = await yokanBrowserArchives.entry(file, entryName, metadataOnly);25 const headers = { 'Content-Type': contentTypes[entryName.split('.').at(-1).toLowerCase()] || 'application/octet-stream',26 'Content-Length': String(entry.size), 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',27 'Content-Security-Policy': "default-src 'none'; sandbox" };28 if (request.headers.has('Range')) return new Response(null, { status: 416, headers: { 'Content-Range': `bytes */${entry.size}` } });29 if (request.method === 'HEAD') return new Response(null, { headers });30 event.waitUntil(entry.done);31 return new Response(entry.stream, { headers });32 }33 const headers = new Headers({ 'Content-Type': contentTypes[parts.at(-1).split('.').at(-1).toLowerCase()] || 'application/octet-stream',34 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',35 // Downloaded HTML must never run scripts under the application's origin.36 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox" });37 let start = 0, end = file.size - 1, status = 200;38 const range = request.headers.get('Range');39 if (range) {40 const match = /^bytes=(\d*)-(\d*)$/.exec(range);41 if (!match || (!match[1] && !match[2])) return new Response(null, { status: 416, headers: { 'Content-Range': `bytes */${file.size}` } });42 if (match[1]) { start = Number(match[1]); end = match[2] ? Math.min(Number(match[2]), end) : end; }43 else start = Math.max(0, file.size - Number(match[2]));44 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end || start >= file.size)45 return new Response(null, { status: 416, headers: { 'Content-Range': `bytes */${file.size}` } });46 status = 206;47 headers.set('Content-Range', `bytes ${start}-${end}/${file.size}`);48 }49 headers.set('Content-Length', String(Math.max(0, end - start + 1)));50 return new Response(request.method === 'HEAD' ? null : file.slice(start, end + 1).stream(), { status, headers });51 } catch (error) { return new Response(null, { status: error.name === 'NotFoundError' ? 404 : 500 }); }52}53self.addEventListener('fetch', event => {54 const url = new URL(event.request.url);55 if (url.origin === self.location.origin && url.pathname.startsWith(prefix)) event.respondWith(serve(event.request, url, event));56});57