Open History to see the last commit
1import { previewUnlock } from "./previewUnlock";
2import type { Database } from "sql.js";
3
4import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
5import {
6 ARCHIVE_ENTRY_MAX_BYTES,
7 ARCHIVE_MAX_ENTRIES,
8 ARCHIVE_MAX_RATIO,
9 BINARY_PREVIEW_MAX_BYTES,
10 SQLITE_PAGE_SIZE,
11 type ArchiveEntry,
12 type BinaryWorkerRequest,
13 type BinaryWorkerResult,
14} from "./binaryPreviewProtocol";
15import { isPreviewError, PreviewError } from "./previewFailure";
16
17let database: Database | null = null;
18let tables: string[] = [];
19// Entries over the preview limit keep only their size, so their payload is never copied.
20let files = new Map<string, Uint8Array<ArrayBuffer> | number>();
21const reply = (result: BinaryWorkerResult) => self.postMessage(result, { transfer: [] });
22const quote = (name: string) => `"${name.replaceAll('"', '""')}"`;
23
24async function gunzipMember(bytes: Uint8Array<ArrayBuffer>, limit: number) {
25 // A stream over the view, not a Blob, so each attempt does not copy the rest of the file.
26 const reader = new ReadableStream<Uint8Array<ArrayBuffer>>({
27 start(controller) {
28 controller.enqueue(bytes);
29 controller.close();
30 },
31 })
32 .pipeThrough(new DecompressionStream("gzip"))
33 .getReader();
34 const chunks: Uint8Array<ArrayBuffer>[] = [];
35 let length = 0;
36 try {
37 while (true) {
38 const { value, done } = await reader.read();
39 if (done) break;
40 length += value.length;
41 if (length > limit) throw new PreviewError({ code: "archive-expanded-too-large" });
42 chunks.push(value);
43 }
44 } finally {
45 await reader.cancel();
46 }
47 return new Uint8Array(await new Blob(chunks).arrayBuffer());
48}
49
50// DecompressionStream rejects a second member (`cat a.gz b.gz`) as junk, so a rest that does not
51// decode whole is cut at each gzip header. A header-like run in the data fails as truncated and
52// costs a re-decode; a single member (a .tar.gz of .gz files stores many) is tried whole first,
53// and a crafted file gets a few false cuts before it fails.
54const GZIP_MAX_FALSE_CUTS = 16;
55
56async function gunzip(bytes: ArrayBuffer) {
57 const data = new Uint8Array(bytes);
58 const limit = Math.min(BINARY_PREVIEW_MAX_BYTES, data.length * ARCHIVE_MAX_RATIO);
59 const isHeader = (at: number) => data[at] === 0x1f && data[at + 1] === 0x8b && data[at + 2] === 8;
60 const members: Uint8Array<ArrayBuffer>[] = [];
61 let length = 0;
62 let falseCuts = 0;
63 let start = 0;
64 do {
65 const decode = (end: number) =>
66 gunzipMember(data.subarray(start, end), limit - length).then(
67 (bytes) => ({ bytes, cause: null }),
68 (cause: unknown) => ({ bytes: null, cause }),
69 );
70 const whole = await decode(data.length);
71 let member = whole;
72 let end = data.length;
73 for (let cut = start; member.bytes === null;) {
74 if (isPreviewError(member.cause)) throw member.cause;
75 if (cut > start && ++falseCuts > GZIP_MAX_FALSE_CUTS) throw whole.cause;
76 do cut++;
77 while (cut < data.length && !isHeader(cut));
78 if (cut >= data.length) throw whole.cause;
79 end = cut;
80 member = await decode(end);
81 }
82 members.push(member.bytes);
83 length += member.bytes.length;
84 start = end;
85 } while (start < data.length);
86 return new Uint8Array(await new Blob(members).arrayBuffer());
87}
88
89function tarEntries(bytes: Uint8Array<ArrayBuffer>) {
90 const entries: ArchiveEntry[] = [];
91 // EF BB BF at the start of a TAR field is part of the name, not a stream BOM.
92 const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
93 const text = (offset: number, length: number) =>
94 utf8.decode(bytes.subarray(offset, offset + length)).split("\0", 1)[0] ?? "";
95 const number = (offset: number, length: number) => {
96 const value = text(offset, length).trim();
97 if (!/^[0-7]*$/.test(value)) throw new PreviewError({ code: "tar-numeric-format" });
98 return Number.parseInt(value || "0", 8);
99 };
100 const gnuNumber = (offset: number, length: number) => {
101 const first = bytes[offset]!;
102 if ((first & 0x80) === 0) return number(offset, length);
103 let value = BigInt(first & 0x40 ? first - 0x100 : first & 0x7f);
104 for (let index = 1; index < length; index++)
105 value = (value << 8n) | BigInt(bytes[offset + index]!);
106 return Number(value);
107 };
108 let longPath: string | null = null;
109 let longLink: string | null = null;
110 const globalPax: Record<string, string> = {};
111 let localPax: Record<string, string> = {};
112 let offset = 0;
113 while (offset + 512 <= bytes.length) {
114 if (bytes.subarray(offset, offset + 512).every((byte) => byte === 0)) break;
115 if (entries.length >= ARCHIVE_MAX_ENTRIES)
116 throw new PreviewError({ code: "archive-too-many-entries" });
117 // Historic SunOS/BSD tar summed header bytes as signed chars, so accept either sum. A blank
118 // field reads as 0, which high-bit bytes can bring the signed sum to, so 0 never matches it.
119 let checksum = 0;
120 let signedChecksum = 0;
121 for (let index = 0; index < 512; index++) {
122 const byte = index >= 148 && index < 156 ? 32 : bytes[offset + index]!;
123 checksum += byte;
124 signedChecksum += byte < 128 ? byte : byte - 256;
125 }
126 const storedChecksum = number(offset + 148, 8);
127 if (storedChecksum !== checksum && (storedChecksum === 0 || storedChecksum !== signedChecksum))
128 throw new PreviewError({ code: "tar-header-damaged" });
129 const type = text(offset + 156, 1);
130 const metadata = type === "L" || type === "K" || type === "x" || type === "g";
131 const attributes: Record<string, string> = metadata ? {} : { ...globalPax, ...localPax };
132 const size = attributes.size ? Number(attributes.size) : gnuNumber(offset + 124, 12);
133 if (attributes.size && !/^\d+$/.test(attributes.size))
134 throw new PreviewError({ code: "archive-entry-damaged" });
135 const prefix =
136 text(offset + 257, 6) === "ustar" && text(offset + 263, 2) === "00"
137 ? text(offset + 345, 155)
138 : "";
139 const path =
140 attributes.path || longPath || [prefix, text(offset, 100)].filter(Boolean).join("/");
141 const linkpath = attributes.linkpath ?? longLink ?? text(offset + 157, 100);
142 if (!metadata) {
143 longLink = null;
144 longPath = null;
145 localPax = {};
146 }
147 if (
148 path.length > 1024 ||
149 !Number.isSafeInteger(size) ||
150 size < 0 ||
151 size > BINARY_PREVIEW_MAX_BYTES ||
152 offset + 512 + size > bytes.length
153 )
154 throw new PreviewError({ code: "archive-entry-damaged" });
155 const content = bytes.subarray(offset + 512, offset + 512 + size);
156 if (type === "L") longPath = utf8.decode(content).replace(/\0.*$/s, "");
157 else if (type === "K") longLink = utf8.decode(content).replace(/\0.*$/s, "");
158 else if (type === "x" || type === "g") {
159 if (size > 65536) throw new PreviewError({ code: "archive-metadata-too-large" });
160 for (let cursor = 0; cursor < content.length;) {
161 const separator = content.indexOf(32, cursor);
162 if (separator < cursor || separator - cursor > 10)
163 throw new PreviewError({ code: "tar-metadata-damaged" });
164 const lengthText = new TextDecoder().decode(content.subarray(cursor, separator));
165 const length = Number(lengthText);
166 const end = cursor + length;
167 if (
168 !/^[1-9]\d*$/.test(lengthText) ||
169 !Number.isSafeInteger(length) ||
170 end > content.length ||
171 end <= separator + 1 ||
172 content[end - 1] !== 10
173 )
174 throw new PreviewError({ code: "tar-metadata-damaged" });
175 const record = new TextDecoder().decode(content.subarray(separator + 1, end - 1));
176 const equals = record.indexOf("=");
177 if (equals < 1) throw new PreviewError({ code: "tar-metadata-damaged" });
178 const key = record.slice(0, equals);
179 const value = record.slice(equals + 1);
180 if (["path", "linkpath", "size", "mtime"].includes(key)) {
181 if (type === "x") localPax[key] = value;
182 else if (value || key === "linkpath") globalPax[key] = value;
183 else delete globalPax[key];
184 }
185 cursor = end;
186 }
187 } else if (
188 type === "" ||
189 type === "0" ||
190 // Contiguous files are regular files to every extractor.
191 type === "7" ||
192 type === "5" ||
193 // A hard link shares an earlier member's bytes; one without that member is skipped.
194 (type === "1" && linkpath && files.has(linkpath))
195 ) {
196 if (attributes.mtime && !/^[+-]?\d+(?:\.\d+)?$/.test(attributes.mtime))
197 throw new PreviewError({ code: "tar-metadata-damaged" });
198 const modified =
199 (attributes.mtime ? Number(attributes.mtime) : gnuNumber(offset + 136, 12)) * 1000;
200 const date = new Date(modified);
201 const linked = type === "1" ? files.get(linkpath) : undefined;
202 // Old (v7) archives mark a folder only by a trailing slash on a plain member.
203 const directory = type === "5" || (type !== "1" && path.endsWith("/"));
204 entries.push({
205 path,
206 size: typeof linked === "number" ? linked : (linked?.length ?? size),
207 directory,
208 modified: Number.isNaN(date.getTime()) ? null : date.toISOString(),
209 });
210 if (directory) {
211 files.delete(path);
212 files.delete(path.replace(/\/+$/, ""));
213 } else files.set(path, linked ?? (size > ARCHIVE_ENTRY_MAX_BYTES ? size : content.slice()));
214 } else {
215 files.delete(path);
216 }
217 offset += 512 + Math.ceil(size / 512) * 512;
218 }
219 // Appended members (`tar -r`/`-u`) replace earlier ones with the same path, as extraction does.
220 const last = new Map(entries.map((entry, index) => [entry.path, index] as const));
221 const listed = entries.filter(
222 (entry, index) => last.get(entry.path) === index && (entry.directory || files.has(entry.path)),
223 );
224 if (listed.length === 0) throw new PreviewError({ code: "archive-empty" });
225 return listed;
226}
227
228async function handle(input: Exclude<BinaryWorkerRequest, { type: "unlock" }>, password?: string) {
229 if (input.type === "entry") {
230 const bytes = files.get(input.path);
231 if (bytes === undefined) throw new PreviewError({ code: "archive-entry-unavailable" });
232 if (typeof bytes === "number" || bytes.length > ARCHIVE_ENTRY_MAX_BYTES)
233 throw new PreviewError({ code: "archive-entry-too-large" });
234 reply({ type: "entry", path: input.path, bytes });
235 return;
236 }
237 if (input.type === "rows") {
238 if (
239 !database ||
240 !tables.includes(input.table) ||
241 !Number.isSafeInteger(input.page) ||
242 input.page < 0
243 )
244 throw new PreviewError({ code: "table-unavailable" });
245 const columns =
246 database
247 .exec(`PRAGMA table_xinfo(${quote(input.table)})`)[0]
248 ?.values.filter((row) => row[6] !== 1)
249 .map((row) => String(row[1]))
250 .slice(0, 50) ?? [];
251 const fields = columns.map((name) => {
252 const field = quote(name);
253 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`;
254 });
255 const result = database.exec(
256 `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`,
257 )[0];
258 reply({
259 type: "rows",
260 table: input.table,
261 page: input.page,
262 columns,
263 rows:
264 result?.values.map((row) => row.map((cell) => (cell === null ? "NULL" : String(cell)))) ??
265 [],
266 });
267 return;
268 }
269 if (input.bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
270 throw new PreviewError({ code: "file-too-large" });
271 if (input.kind === "sqlite") {
272 const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([
273 import("sql.js"),
274 import("sql.js/dist/sql-wasm.wasm?url"),
275 ]);
276 const SQL = await initSqlJs({ locateFile: () => wasmUrl });
277 database = new SQL.Database(new Uint8Array(input.bytes));
278 database.run("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;");
279 tables =
280 database
281 .exec(
282 "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",
283 )[0]
284 ?.values.map((row) => String(row[0])) ?? [];
285 if (tables.length > 100) throw new PreviewError({ code: "database-too-many-tables" });
286 reply({
287 type: "sqlite",
288 tables: tables.map((name) => ({
289 name,
290 count: Number(
291 database!.exec(`SELECT count(*) FROM ${quote(name)}`)[0]?.values[0]?.[0] ?? 0,
292 ),
293 })),
294 });
295 } else {
296 files = new Map();
297 let entries: ArchiveEntry[];
298 if (
299 /\.(zip|jar)$/i.test(input.name) ||
300 (input.bytes.byteLength >= 4 &&
301 [0x04034b50, 0x06054b50].includes(new DataView(input.bytes).getUint32(0, true)))
302 ) {
303 const archive = await boundedZip(input.bytes, BINARY_PREVIEW_MAX_BYTES, { password });
304 entries = [...archive].map(([path, file]) => {
305 files.set(path, file.bytes);
306 return {
307 path,
308 size: file.bytes.length,
309 directory: file.directory,
310 // ZIP stores wall-clock time without a zone, while JSZip reads those fields as UTC.
311 // Omitting "Z" marks the timestamp as wall-clock so the viewer formats its calendar date.
312 // DOS dates start in 1980; an unset (all zero) field reads as 30 Nov 1979, so it has none.
313 modified:
314 Number.isNaN(file.date.getTime()) || file.date.getUTCFullYear() < 1980
315 ? null
316 : file.date.toISOString().slice(0, -1),
317 };
318 });
319 } else if (
320 /\.(gz|tgz)$/i.test(input.name) ||
321 (input.bytes.byteLength >= 2 && new DataView(input.bytes).getUint16(0) === 0x1f8b)
322 ) {
323 const bytes = await gunzip(input.bytes);
324 if (/\.(tar\.gz|tgz)$/i.test(input.name)) entries = tarEntries(bytes);
325 else {
326 const path = input.name.replace(/\.gz$/i, "") || "contents";
327 if (/\.tar$/i.test(path)) entries = tarEntries(bytes);
328 else {
329 files.set(path, bytes);
330 entries = [{ path, size: bytes.length, directory: false, modified: null }];
331 }
332 }
333 } else entries = tarEntries(new Uint8Array(input.bytes));
334 reply({ type: "archive", entries });
335 }
336}
337
338const receive = previewUnlock(handle, reply, "preview-failed");
339self.addEventListener("message", (event: MessageEvent<BinaryWorkerRequest>) => {
340 void receive(event.data);
341});