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 { 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 gunzip(bytes: ArrayBuffer) {
25 const reader = new Blob([bytes])
26 .stream()
27 .pipeThrough(new DecompressionStream("gzip"))
28 .getReader();
29 const chunks: Uint8Array<ArrayBuffer>[] = [];
30 let length = 0;
31 try {
32 while (true) {
33 const { value, done } = await reader.read();
34 if (done) break;
35 length += value.length;
36 if (length > BINARY_PREVIEW_MAX_BYTES || length > bytes.byteLength * ARCHIVE_MAX_RATIO)
37 throw new PreviewError({ code: "archive-expanded-too-large" });
38 chunks.push(value);
39 }
40 } finally {
41 await reader.cancel();
42 }
43 return new Uint8Array(await new Blob(chunks).arrayBuffer());
44}
45
46function tarEntries(bytes: Uint8Array<ArrayBuffer>) {
47 const entries: ArchiveEntry[] = [];
48 // EF BB BF at the start of a TAR field is part of the name, not a stream BOM.
49 const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
50 const text = (offset: number, length: number) =>
51 utf8.decode(bytes.subarray(offset, offset + length)).split("\0", 1)[0] ?? "";
52 const number = (offset: number, length: number) => {
53 const value = text(offset, length).trim();
54 if (!/^[0-7]*$/.test(value)) throw new PreviewError({ code: "tar-numeric-format" });
55 return Number.parseInt(value || "0", 8);
56 };
57 const gnuNumber = (offset: number, length: number) => {
58 const first = bytes[offset]!;
59 if ((first & 0x80) === 0) return number(offset, length);
60 let value = BigInt(first & 0x40 ? first - 0x100 : first & 0x7f);
61 for (let index = 1; index < length; index++)
62 value = (value << 8n) | BigInt(bytes[offset + index]!);
63 return Number(value);
64 };
65 let longPath: string | null = null;
66 let longLink: string | null = null;
67 const globalPax: Record<string, string> = {};
68 let localPax: Record<string, string> = {};
69 let offset = 0;
70 while (offset + 512 <= bytes.length) {
71 if (bytes.subarray(offset, offset + 512).every((byte) => byte === 0)) break;
72 if (entries.length >= ARCHIVE_MAX_ENTRIES)
73 throw new PreviewError({ code: "archive-too-many-entries" });
74 let checksum = 0;
75 for (let index = 0; index < 512; index++)
76 checksum += index >= 148 && index < 156 ? 32 : bytes[offset + index]!;
77 if (checksum !== number(offset + 148, 8))
78 throw new PreviewError({ code: "tar-header-damaged" });
79 const type = text(offset + 156, 1);
80 const metadata = type === "L" || type === "K" || type === "x" || type === "g";
81 const attributes: Record<string, string> = metadata ? {} : { ...globalPax, ...localPax };
82 const size = attributes.size ? Number(attributes.size) : gnuNumber(offset + 124, 12);
83 if (attributes.size && !/^\d+$/.test(attributes.size))
84 throw new PreviewError({ code: "archive-entry-damaged" });
85 const prefix =
86 text(offset + 257, 6) === "ustar" && text(offset + 263, 2) === "00"
87 ? text(offset + 345, 155)
88 : "";
89 const path =
90 attributes.path || longPath || [prefix, text(offset, 100)].filter(Boolean).join("/");
91 const linkpath = attributes.linkpath ?? longLink ?? text(offset + 157, 100);
92 if (!metadata) {
93 longLink = null;
94 longPath = null;
95 localPax = {};
96 }
97 if (
98 path.length > 1024 ||
99 !Number.isSafeInteger(size) ||
100 size < 0 ||
101 size > BINARY_PREVIEW_MAX_BYTES ||
102 offset + 512 + size > bytes.length
103 )
104 throw new PreviewError({ code: "archive-entry-damaged" });
105 const content = bytes.subarray(offset + 512, offset + 512 + size);
106 if (type === "L") longPath = utf8.decode(content).replace(/\0.*$/s, "");
107 else if (type === "K") longLink = utf8.decode(content).replace(/\0.*$/s, "");
108 else if (type === "x" || type === "g") {
109 if (size > 65536) throw new PreviewError({ code: "archive-metadata-too-large" });
110 for (let cursor = 0; cursor < content.length;) {
111 const separator = content.indexOf(32, cursor);
112 if (separator < cursor || separator - cursor > 10)
113 throw new PreviewError({ code: "tar-metadata-damaged" });
114 const lengthText = new TextDecoder().decode(content.subarray(cursor, separator));
115 const length = Number(lengthText);
116 const end = cursor + length;
117 if (
118 !/^[1-9]\d*$/.test(lengthText) ||
119 !Number.isSafeInteger(length) ||
120 end > content.length ||
121 end <= separator + 1 ||
122 content[end - 1] !== 10
123 )
124 throw new PreviewError({ code: "tar-metadata-damaged" });
125 const record = new TextDecoder().decode(content.subarray(separator + 1, end - 1));
126 const equals = record.indexOf("=");
127 if (equals < 1) throw new PreviewError({ code: "tar-metadata-damaged" });
128 const key = record.slice(0, equals);
129 const value = record.slice(equals + 1);
130 if (["path", "linkpath", "size", "mtime"].includes(key)) {
131 if (type === "x") localPax[key] = value;
132 else if (value || key === "linkpath") globalPax[key] = value;
133 else delete globalPax[key];
134 }
135 cursor = end;
136 }
137 } else if (
138 type === "" ||
139 type === "0" ||
140 type === "5" ||
141 // A hard link shares an earlier member's bytes; one without that member is skipped.
142 (type === "1" && linkpath && files.has(linkpath))
143 ) {
144 if (attributes.mtime && !/^[+-]?\d+(?:\.\d+)?$/.test(attributes.mtime))
145 throw new PreviewError({ code: "tar-metadata-damaged" });
146 const modified =
147 (attributes.mtime ? Number(attributes.mtime) : gnuNumber(offset + 136, 12)) * 1000;
148 const date = new Date(modified);
149 const linked = type === "1" ? files.get(linkpath) : undefined;
150 entries.push({
151 path,
152 size: typeof linked === "number" ? linked : (linked?.length ?? size),
153 directory: type === "5",
154 modified: Number.isNaN(date.getTime()) ? null : date.toISOString(),
155 });
156 if (type === "5") {
157 files.delete(path);
158 files.delete(path.replace(/\/+$/, ""));
159 } else files.set(path, linked ?? (size > ARCHIVE_ENTRY_MAX_BYTES ? size : content.slice()));
160 } else {
161 files.delete(path);
162 }
163 offset += 512 + Math.ceil(size / 512) * 512;
164 }
165 // Appended members (`tar -r`/`-u`) replace earlier ones with the same path, as extraction does.
166 const last = new Map(entries.map((entry, index) => [entry.path, index] as const));
167 const listed = entries.filter(
168 (entry, index) => last.get(entry.path) === index && (entry.directory || files.has(entry.path)),
169 );
170 if (listed.length === 0) throw new PreviewError({ code: "archive-empty" });
171 return listed;
172}
173
174async function handle(input: Exclude<BinaryWorkerRequest, { type: "unlock" }>, password?: string) {
175 if (input.type === "entry") {
176 const bytes = files.get(input.path);
177 if (bytes === undefined) throw new PreviewError({ code: "archive-entry-unavailable" });
178 if (typeof bytes === "number" || bytes.length > ARCHIVE_ENTRY_MAX_BYTES)
179 throw new PreviewError({ code: "archive-entry-too-large" });
180 reply({ type: "entry", path: input.path, bytes });
181 return;
182 }
183 if (input.type === "rows") {
184 if (
185 !database ||
186 !tables.includes(input.table) ||
187 !Number.isSafeInteger(input.page) ||
188 input.page < 0
189 )
190 throw new PreviewError({ code: "table-unavailable" });
191 const columns =
192 database
193 .exec(`PRAGMA table_xinfo(${quote(input.table)})`)[0]
194 ?.values.filter((row) => row[6] !== 1)
195 .map((row) => String(row[1]))
196 .slice(0, 50) ?? [];
197 const fields = columns.map((name) => {
198 const field = quote(name);
199 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`;
200 });
201 const result = database.exec(
202 `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`,
203 )[0];
204 reply({
205 type: "rows",
206 table: input.table,
207 page: input.page,
208 columns,
209 rows:
210 result?.values.map((row) => row.map((cell) => (cell === null ? "NULL" : String(cell)))) ??
211 [],
212 });
213 return;
214 }
215 if (input.bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
216 throw new PreviewError({ code: "file-too-large" });
217 if (input.kind === "sqlite") {
218 const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([
219 import("sql.js"),
220 import("sql.js/dist/sql-wasm.wasm?url"),
221 ]);
222 const SQL = await initSqlJs({ locateFile: () => wasmUrl });
223 database = new SQL.Database(new Uint8Array(input.bytes));
224 database.run("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;");
225 tables =
226 database
227 .exec(
228 "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",
229 )[0]
230 ?.values.map((row) => String(row[0])) ?? [];
231 if (tables.length > 100) throw new PreviewError({ code: "database-too-many-tables" });
232 reply({
233 type: "sqlite",
234 tables: tables.map((name) => ({
235 name,
236 count: Number(
237 database!.exec(`SELECT count(*) FROM ${quote(name)}`)[0]?.values[0]?.[0] ?? 0,
238 ),
239 })),
240 });
241 } else {
242 files = new Map();
243 let entries: ArchiveEntry[];
244 if (
245 /\.(zip|jar)$/i.test(input.name) ||
246 (input.bytes.byteLength >= 4 &&
247 [0x04034b50, 0x06054b50].includes(new DataView(input.bytes).getUint32(0, true)))
248 ) {
249 const archive = await boundedZip(input.bytes, BINARY_PREVIEW_MAX_BYTES, { password });
250 entries = [...archive].map(([path, file]) => {
251 files.set(path, file.bytes);
252 return {
253 path,
254 size: file.bytes.length,
255 directory: file.directory,
256 // ZIP stores wall-clock time without a zone, while JSZip reads those fields as UTC.
257 // Omitting "Z" marks the timestamp as wall-clock so the viewer formats its calendar date.
258 modified: Number.isNaN(file.date.getTime()) ? null : file.date.toISOString().slice(0, -1),
259 };
260 });
261 } else if (
262 /\.(gz|tgz)$/i.test(input.name) ||
263 (input.bytes.byteLength >= 2 && new DataView(input.bytes).getUint16(0) === 0x1f8b)
264 ) {
265 const bytes = await gunzip(input.bytes);
266 if (/\.(tar\.gz|tgz)$/i.test(input.name)) entries = tarEntries(bytes);
267 else {
268 const path = input.name.replace(/\.gz$/i, "") || "contents";
269 if (/\.tar$/i.test(path)) entries = tarEntries(bytes);
270 else {
271 files.set(path, bytes);
272 entries = [{ path, size: bytes.length, directory: false, modified: null }];
273 }
274 }
275 } else entries = tarEntries(new Uint8Array(input.bytes));
276 reply({ type: "archive", entries });
277 }
278}
279
280const receive = previewUnlock(handle, reply, "preview-failed");
281self.addEventListener("message", (event: MessageEvent<BinaryWorkerRequest>) => {
282 void receive(event.data);
283});