browser-archives.js
composeApp/src/wasmJsMain/resources/browser-archives.js
1/* Bounded, streaming ZIP/CBZ access. zip.js is vendored and loaded only when archives are used. */2(() => {3 'use strict';4 const base = typeof document === 'undefined' ? new URL('.', self.location.href) : new URL('.', document.currentScript?.src || document.baseURI);5 const maximumEntries = 10000, maximumEntryBytes = 64 * 1024 * 1024, maximumDirectoryBytes = 4 * 1024 * 1024;6 let library;7 async function zipLibrary() {8 if (globalThis.zip) return globalThis.zip;9 if (!library) library = (async () => {10 const url = new URL('vendor/zipjs-2.23.0/zip-native.min.js', base).href;11 if (typeof importScripts === 'function') importScripts(url);12 else await new Promise((resolve, reject) => {13 const script = document.createElement('script');14 script.src = url; script.onload = resolve; script.onerror = () => reject(new Error('Archive support could not load.'));15 document.head.append(script);16 });17 return globalThis.zip;18 })().catch(error => { library = null; throw error; });19 return library;20 }21 function safeName(name) {22 return typeof name === 'string' && name.length > 0 && name.length <= 1024 &&23 !/[\\\0:]/.test(name) && !name.startsWith('/') && name.split('/').every(part => part && part !== '.' && part !== '..');24 }25 // Bound the central directory before the library allocates its index. ZIP64/split archives are explicit limits.26 async function preflight(file) {27 if (file.size < 22 || file.size >= 0xffffffff) throw new Error('Unsupported archive size.');28 const tail = new DataView(await file.slice(Math.max(0, file.size - 65557)).arrayBuffer());29 for (let i = tail.byteLength - 22; i >= 0; i--) {30 if (tail.getUint32(i, true) !== 0x06054b50 || i + 22 + tail.getUint16(i + 20, true) !== tail.byteLength) continue;31 const count = tail.getUint16(i + 10, true), size = tail.getUint32(i + 12, true), offset = tail.getUint32(i + 16, true);32 if (tail.getUint16(i + 4, true) || tail.getUint16(i + 6, true) || tail.getUint16(i + 8, true) !== count ||33 count > maximumEntries || size > maximumDirectoryBytes || offset + size > file.size - tail.byteLength + i) throw new Error('Unsupported archive index.');34 return;35 }36 throw new Error('Invalid archive directory.');37 }38 async function open(file) {39 await preflight(file);40 const zip = await zipLibrary();41 const reader = new zip.ZipReader(new zip.BlobReader(file), { useWebWorkers: false, checkCrc32: true, checkOverlappingEntry: true });42 try {43 const entries = new Map();44 for await (const entry of reader.getEntriesGenerator()) {45 if (entry.directory) continue;46 if (entries.size >= maximumEntries || !safeName(entry.filename) || entries.has(entry.filename) || entry.encrypted ||47 !Number.isSafeInteger(entry.uncompressedSize) || entry.uncompressedSize < 0 || entry.uncompressedSize > maximumEntryBytes) throw new Error('Unsupported archive entry.');48 entries.set(entry.filename, entry);49 }50 return { reader, entries };51 } catch (error) { await reader.close(); throw error; }52 }53 async function index(file) {54 const archive = await open(file);55 try { return [...archive.entries.values()].map(entry => ({ name: entry.filename, size: entry.uncompressedSize })); }56 finally { await archive.reader.close(); }57 }58 // One bounded index and File snapshot for a manifest/chapter read. No whole-book extraction.59 async function openRead(file) {60 const archive = await open(file);61 let closed = false;62 return {63 async read(name, maximum) {64 if (closed || !safeName(name) || !Number.isSafeInteger(maximum) || maximum < 0 || maximum > 16 * 1024 * 1024) throw new Error('Invalid archive read.');65 const selected = archive.entries.get(name);66 if (!selected) return null;67 if (selected.uncompressedSize > maximum) throw new Error('EPUB resource exceeds the read limit.');68 const chunks = [];69 let size = 0;70 await selected.getData(new WritableStream({ write(bytes) {71 size += bytes.byteLength;72 if (size > maximum || size > selected.uncompressedSize) throw new Error('EPUB resource exceeds its size limit.');73 chunks.push(bytes.slice());74 } }), { useWebWorkers: false, checkCrc32: true });75 if (size !== selected.uncompressedSize) throw new Error('Incomplete EPUB resource.');76 const output = new Uint8Array(size);77 let offset = 0;78 for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.byteLength; }79 return output;80 },81 async close() { if (!closed) { closed = true; await archive.reader.close(); } },82 };83 }84 async function entry(file, name, metadataOnly = false) {85 if (!safeName(name)) throw new Error('Invalid archive entry path.');86 const archive = await open(file);87 const selected = archive.entries.get(name);88 if (!selected) { await archive.reader.close(); const error = new Error('Archive entry no longer exists.'); error.name = 'NotFoundError'; throw error; }89 if (metadataOnly) { await archive.reader.close(); return { size: selected.uncompressedSize }; }90 let received = 0;91 const stream = new TransformStream({ transform(bytes, controller) {92 received += bytes.byteLength;93 if (received > maximumEntryBytes || received > selected.uncompressedSize) throw new Error('Archive entry exceeds its size limit.');94 controller.enqueue(bytes);95 } });96 const writer = stream.writable.getWriter();97 const output = new WritableStream({ write: bytes => writer.write(bytes) });98 // Close only after CRC and size validation, so corrupt archives fail the consuming fetch.99 const done = selected.getData(output, { useWebWorkers: false, checkCrc32: true, preventClose: true })100 .then(async () => { if (received !== selected.uncompressedSize) throw new Error('Incomplete archive entry.'); await writer.close(); })101 .catch(async error => { await writer.abort(error).catch(() => {}); })102 .finally(() => archive.reader.close());103 return { stream: stream.readable, size: selected.uncompressedSize, done };104 }105 async function write(files, output) {106 if (!files.length || files.length > maximumEntries || files.some(file => !safeName(file.name) || file.bytes.size > maximumEntryBytes)) throw new Error('Unsupported archive contents.');107 const zip = await zipLibrary();108 const writer = new zip.ZipWriter(output, { useWebWorkers: false, level: 0, zip64: false, preventClose: true });109 for (const file of files) await writer.add(file.name, new zip.BlobReader(file.bytes), { level: 0, zip64: false });110 await writer.close();111 }112 globalThis.yokanBrowserArchives = { index, entry, write, safeName, openRead };113})();114