import { previewUnlock } from "./previewUnlock"; import type { Database } from "sql.js"; import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip"; import { ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_MAX_ENTRIES, ARCHIVE_MAX_RATIO, BINARY_PREVIEW_MAX_BYTES, SQLITE_PAGE_SIZE, type ArchiveEntry, type BinaryWorkerRequest, type BinaryWorkerResult, } from "./binaryPreviewProtocol"; import { isPreviewError, PreviewError } from "./previewFailure"; let database: Database | null = null; let tables: string[] = []; // Entries over the preview limit keep only their size, so their payload is never copied. let files = new Map | number>(); const reply = (result: BinaryWorkerResult) => self.postMessage(result, { transfer: [] }); const quote = (name: string) => `"${name.replaceAll('"', '""')}"`; async function gunzipMember(bytes: Uint8Array, limit: number) { // A stream over the view, not a Blob, so each attempt does not copy the rest of the file. const reader = new ReadableStream>({ start(controller) { controller.enqueue(bytes); controller.close(); }, }) .pipeThrough(new DecompressionStream("gzip")) .getReader(); const chunks: Uint8Array[] = []; let length = 0; try { while (true) { const { value, done } = await reader.read(); if (done) break; length += value.length; if (length > limit) throw new PreviewError({ code: "archive-expanded-too-large" }); chunks.push(value); } } finally { await reader.cancel(); } return new Uint8Array(await new Blob(chunks).arrayBuffer()); } // DecompressionStream rejects a second member (`cat a.gz b.gz`) as junk, so a rest that does not // decode whole is cut at each gzip header. A header-like run in the data fails as truncated and // costs a re-decode; a single member (a .tar.gz of .gz files stores many) is tried whole first, // and a crafted file gets a few false cuts before it fails. const GZIP_MAX_FALSE_CUTS = 16; async function gunzip(bytes: ArrayBuffer) { const data = new Uint8Array(bytes); const limit = Math.min(BINARY_PREVIEW_MAX_BYTES, data.length * ARCHIVE_MAX_RATIO); const isHeader = (at: number) => data[at] === 0x1f && data[at + 1] === 0x8b && data[at + 2] === 8; const members: Uint8Array[] = []; let length = 0; let falseCuts = 0; let start = 0; do { const decode = (end: number) => gunzipMember(data.subarray(start, end), limit - length).then( (bytes) => ({ bytes, cause: null }), (cause: unknown) => ({ bytes: null, cause }), ); const whole = await decode(data.length); let member = whole; let end = data.length; for (let cut = start; member.bytes === null;) { if (isPreviewError(member.cause)) throw member.cause; if (cut > start && ++falseCuts > GZIP_MAX_FALSE_CUTS) throw whole.cause; do cut++; while (cut < data.length && !isHeader(cut)); if (cut >= data.length) throw whole.cause; end = cut; member = await decode(end); } members.push(member.bytes); length += member.bytes.length; start = end; } while (start < data.length); return new Uint8Array(await new Blob(members).arrayBuffer()); } function tarEntries(bytes: Uint8Array) { const entries: ArchiveEntry[] = []; // EF BB BF at the start of a TAR field is part of the name, not a stream BOM. const utf8 = new TextDecoder("utf-8", { ignoreBOM: true }); const text = (offset: number, length: number) => utf8.decode(bytes.subarray(offset, offset + length)).split("\0", 1)[0] ?? ""; const number = (offset: number, length: number) => { const value = text(offset, length).trim(); if (!/^[0-7]*$/.test(value)) throw new PreviewError({ code: "tar-numeric-format" }); return Number.parseInt(value || "0", 8); }; const gnuNumber = (offset: number, length: number) => { const first = bytes[offset]!; if ((first & 0x80) === 0) return number(offset, length); let value = BigInt(first & 0x40 ? first - 0x100 : first & 0x7f); for (let index = 1; index < length; index++) value = (value << 8n) | BigInt(bytes[offset + index]!); return Number(value); }; let longPath: string | null = null; let longLink: string | null = null; const globalPax: Record = {}; let localPax: Record = {}; let offset = 0; while (offset + 512 <= bytes.length) { if (bytes.subarray(offset, offset + 512).every((byte) => byte === 0)) break; if (entries.length >= ARCHIVE_MAX_ENTRIES) throw new PreviewError({ code: "archive-too-many-entries" }); // Historic SunOS/BSD tar summed header bytes as signed chars, so accept either sum. A blank // field reads as 0, which high-bit bytes can bring the signed sum to, so 0 never matches it. let checksum = 0; let signedChecksum = 0; for (let index = 0; index < 512; index++) { const byte = index >= 148 && index < 156 ? 32 : bytes[offset + index]!; checksum += byte; signedChecksum += byte < 128 ? byte : byte - 256; } const storedChecksum = number(offset + 148, 8); if (storedChecksum !== checksum && (storedChecksum === 0 || storedChecksum !== signedChecksum)) throw new PreviewError({ code: "tar-header-damaged" }); const type = text(offset + 156, 1); const metadata = type === "L" || type === "K" || type === "x" || type === "g"; const attributes: Record = metadata ? {} : { ...globalPax, ...localPax }; const size = attributes.size ? Number(attributes.size) : gnuNumber(offset + 124, 12); if (attributes.size && !/^\d+$/.test(attributes.size)) throw new PreviewError({ code: "archive-entry-damaged" }); const prefix = text(offset + 257, 6) === "ustar" && text(offset + 263, 2) === "00" ? text(offset + 345, 155) : ""; const path = attributes.path || longPath || [prefix, text(offset, 100)].filter(Boolean).join("/"); const linkpath = attributes.linkpath ?? longLink ?? text(offset + 157, 100); if (!metadata) { longLink = null; longPath = null; localPax = {}; } if ( path.length > 1024 || !Number.isSafeInteger(size) || size < 0 || size > BINARY_PREVIEW_MAX_BYTES || offset + 512 + size > bytes.length ) throw new PreviewError({ code: "archive-entry-damaged" }); const content = bytes.subarray(offset + 512, offset + 512 + size); if (type === "L") longPath = utf8.decode(content).replace(/\0.*$/s, ""); else if (type === "K") longLink = utf8.decode(content).replace(/\0.*$/s, ""); else if (type === "x" || type === "g") { if (size > 65536) throw new PreviewError({ code: "archive-metadata-too-large" }); for (let cursor = 0; cursor < content.length;) { const separator = content.indexOf(32, cursor); if (separator < cursor || separator - cursor > 10) throw new PreviewError({ code: "tar-metadata-damaged" }); const lengthText = new TextDecoder().decode(content.subarray(cursor, separator)); const length = Number(lengthText); const end = cursor + length; if ( !/^[1-9]\d*$/.test(lengthText) || !Number.isSafeInteger(length) || end > content.length || end <= separator + 1 || content[end - 1] !== 10 ) throw new PreviewError({ code: "tar-metadata-damaged" }); const record = new TextDecoder().decode(content.subarray(separator + 1, end - 1)); const equals = record.indexOf("="); if (equals < 1) throw new PreviewError({ code: "tar-metadata-damaged" }); const key = record.slice(0, equals); const value = record.slice(equals + 1); if (["path", "linkpath", "size", "mtime"].includes(key)) { if (type === "x") localPax[key] = value; else if (value || key === "linkpath") globalPax[key] = value; else delete globalPax[key]; } cursor = end; } } else if ( type === "" || type === "0" || // Contiguous files are regular files to every extractor. type === "7" || type === "5" || // A hard link shares an earlier member's bytes; one without that member is skipped. (type === "1" && linkpath && files.has(linkpath)) ) { if (attributes.mtime && !/^[+-]?\d+(?:\.\d+)?$/.test(attributes.mtime)) throw new PreviewError({ code: "tar-metadata-damaged" }); const modified = (attributes.mtime ? Number(attributes.mtime) : gnuNumber(offset + 136, 12)) * 1000; const date = new Date(modified); const linked = type === "1" ? files.get(linkpath) : undefined; // Old (v7) archives mark a folder only by a trailing slash on a plain member. const directory = type === "5" || (type !== "1" && path.endsWith("/")); entries.push({ path, size: typeof linked === "number" ? linked : (linked?.length ?? size), directory, modified: Number.isNaN(date.getTime()) ? null : date.toISOString(), }); if (directory) { files.delete(path); files.delete(path.replace(/\/+$/, "")); } else files.set(path, linked ?? (size > ARCHIVE_ENTRY_MAX_BYTES ? size : content.slice())); } else { files.delete(path); } offset += 512 + Math.ceil(size / 512) * 512; } // Appended members (`tar -r`/`-u`) replace earlier ones with the same path, as extraction does. const last = new Map(entries.map((entry, index) => [entry.path, index] as const)); const listed = entries.filter( (entry, index) => last.get(entry.path) === index && (entry.directory || files.has(entry.path)), ); if (listed.length === 0) throw new PreviewError({ code: "archive-empty" }); return listed; } async function handle(input: Exclude, password?: string) { if (input.type === "entry") { const bytes = files.get(input.path); if (bytes === undefined) throw new PreviewError({ code: "archive-entry-unavailable" }); if (typeof bytes === "number" || bytes.length > ARCHIVE_ENTRY_MAX_BYTES) throw new PreviewError({ code: "archive-entry-too-large" }); reply({ type: "entry", path: input.path, bytes }); return; } if (input.type === "rows") { if ( !database || !tables.includes(input.table) || !Number.isSafeInteger(input.page) || input.page < 0 ) throw new PreviewError({ code: "table-unavailable" }); const columns = database .exec(`PRAGMA table_xinfo(${quote(input.table)})`)[0] ?.values.filter((row) => row[6] !== 1) .map((row) => String(row[1])) .slice(0, 50) ?? []; const fields = columns.map((name) => { const field = quote(name); return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || CASE length(${field}) WHEN 1 THEN ' byte]' ELSE ' bytes]' END ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`; }); const result = database.exec( `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`, )[0]; reply({ type: "rows", table: input.table, page: input.page, columns, rows: result?.values.map((row) => row.map((cell) => (cell === null ? "NULL" : String(cell)))) ?? [], }); return; } if (input.bytes.byteLength > BINARY_PREVIEW_MAX_BYTES) throw new PreviewError({ code: "file-too-large" }); if (input.kind === "sqlite") { const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([ import("sql.js"), import("sql.js/dist/sql-wasm.wasm?url"), ]); const SQL = await initSqlJs({ locateFile: () => wasmUrl }); database = new SQL.Database(new Uint8Array(input.bytes)); database.run("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;"); tables = database .exec( "SELECT name FROM sqlite_schema WHERE type='table' AND substr(name, 1, 7) != 'sqlite_' AND sql NOT LIKE 'CREATE VIRTUAL TABLE%' ORDER BY name LIMIT 101", )[0] ?.values.map((row) => String(row[0])) ?? []; if (tables.length > 100) throw new PreviewError({ code: "database-too-many-tables" }); reply({ type: "sqlite", tables: tables.map((name) => ({ name, count: Number( database!.exec(`SELECT count(*) FROM ${quote(name)}`)[0]?.values[0]?.[0] ?? 0, ), })), }); } else { files = new Map(); let entries: ArchiveEntry[]; if ( /\.(zip|jar)$/i.test(input.name) || (input.bytes.byteLength >= 4 && [0x04034b50, 0x06054b50].includes(new DataView(input.bytes).getUint32(0, true))) ) { const archive = await boundedZip(input.bytes, BINARY_PREVIEW_MAX_BYTES, { password }); entries = [...archive].map(([path, file]) => { files.set(path, file.bytes); return { path, size: file.bytes.length, directory: file.directory, // ZIP stores wall-clock time without a zone, while JSZip reads those fields as UTC. // Omitting "Z" marks the timestamp as wall-clock so the viewer formats its calendar date. modified: Number.isNaN(file.date.getTime()) ? null : file.date.toISOString().slice(0, -1), }; }); } else if ( /\.(gz|tgz)$/i.test(input.name) || (input.bytes.byteLength >= 2 && new DataView(input.bytes).getUint16(0) === 0x1f8b) ) { const bytes = await gunzip(input.bytes); if (/\.(tar\.gz|tgz)$/i.test(input.name)) entries = tarEntries(bytes); else { const path = input.name.replace(/\.gz$/i, "") || "contents"; if (/\.tar$/i.test(path)) entries = tarEntries(bytes); else { files.set(path, bytes); entries = [{ path, size: bytes.length, directory: false, modified: null }]; } } } else entries = tarEntries(new Uint8Array(input.bytes)); reply({ type: "archive", entries }); } } const receive = previewUnlock(handle, reply, "preview-failed"); self.addEventListener("message", (event: MessageEvent) => { void receive(event.data); });