Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

binaryPreview.worker.ts

265 lines10.2 KB

1import type { Database } from "sql.js";
2​
3import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
4import {
5 ARCHIVE_ENTRY_MAX_BYTES,
6 ARCHIVE_MAX_ENTRIES,
7 ARCHIVE_MAX_RATIO,
8 BINARY_PREVIEW_MAX_BYTES,
9 SQLITE_PAGE_SIZE,
10 type ArchiveEntry,
11 type BinaryWorkerRequest,
12 type BinaryWorkerResult,
13} from "./binaryPreviewProtocol";
14​
15let database: Database | null = null;
16let tables: string[] = [];
17let files = new Map<string, Uint8Array<ArrayBuffer>>();
18const reply = (result: BinaryWorkerResult) => self.postMessage(result, { transfer: [] });
19const quote = (name: string) => `"${name.replaceAll('"', '""')}"`;
20​
21async function gunzip(bytes: ArrayBuffer) {
22 const reader = new Blob([bytes])
23 .stream()
24 .pipeThrough(new DecompressionStream("gzip"))
25 .getReader();
26 const chunks: Uint8Array<ArrayBuffer>[] = [];
27 let length = 0;
28 try {
29 while (true) {
30 const { value, done } = await reader.read();
31 if (done) break;
32 length += value.length;
33 if (length > BINARY_PREVIEW_MAX_BYTES || length > bytes.byteLength * ARCHIVE_MAX_RATIO)
34 throw new Error(
35 "The expanded archive exceeds the preview size or compression ratio limit.",
36 );
37 chunks.push(value);
38 }
39 } finally {
40 await reader.cancel();
41 }
42 return new Uint8Array(await new Blob(chunks).arrayBuffer());
44​
45function tarEntries(bytes: Uint8Array<ArrayBuffer>) {
46 const entries: ArchiveEntry[] = [];
47 const text = (offset: number, length: number) =>
48 new TextDecoder().decode(bytes.subarray(offset, offset + length)).split("\0", 1)[0] ?? "";
49 const number = (offset: number, length: number) => {
50 const value = text(offset, length).trim();
51 if (!/^[0-7]*$/.test(value)) throw new Error("This TAR uses an unsupported numeric format.");
52 return Number.parseInt(value || "0", 8);
53 };
54 let longPath: string | null = null;
55 let longLink: string | null = null;
56 const globalPax: Record<string, string> = {};
57 let localPax: Record<string, string> = {};
58 let offset = 0;
59 while (offset + 512 <= bytes.length) {
60 if (bytes.subarray(offset, offset + 512).every((byte) => byte === 0)) break;
61 if (entries.length >= ARCHIVE_MAX_ENTRIES)
62 throw new Error("This archive contains more than 2,048 entries.");
63 let checksum = 0;
64 for (let index = 0; index < 512; index++)
65 checksum += index >= 148 && index < 156 ? 32 : bytes[offset + index]!;
66 if (checksum !== number(offset + 148, 8)) throw new Error("The TAR header is damaged.");
67 const type = text(offset + 156, 1);
68 const metadata = type === "L" || type === "K" || type === "x" || type === "g";
69 const attributes: Record<string, string> = metadata ? {} : { ...globalPax, ...localPax };
70 const size = attributes.size ? Number(attributes.size) : number(offset + 124, 12);
71 if (attributes.size && !/^\d+$/.test(attributes.size))
72 throw new Error("An archive entry is too large or damaged.");
73 const prefix =
74 text(offset + 257, 6) === "ustar" && text(offset + 263, 2) === "00"
75 ? text(offset + 345, 155)
76 : "";
77 const path =
78 attributes.path || longPath || [prefix, text(offset, 100)].filter(Boolean).join("/");
79 const linkpath = attributes.linkpath ?? longLink ?? text(offset + 157, 100);
80 if (!metadata) {
81 longLink = null;
82 longPath = null;
83 localPax = {};
84 }
85 if (
86 path.length > 1024 ||
87 !Number.isSafeInteger(size) ||
88 size < 0 ||
89 size > BINARY_PREVIEW_MAX_BYTES ||
90 offset + 512 + size > bytes.length
91 )
92 throw new Error("An archive entry is too large or damaged.");
93 const content = bytes.subarray(offset + 512, offset + 512 + size);
94 if (type === "L") longPath = new TextDecoder().decode(content).replace(/\0.*$/s, "");
95 else if (type === "K") longLink = new TextDecoder().decode(content).replace(/\0.*$/s, "");
96 else if (type === "x" || type === "g") {
97 if (size > 65536) throw new Error("Archive metadata is too large.");
98 for (let cursor = 0; cursor < content.length;) {
99 const separator = content.indexOf(32, cursor);
100 if (separator < cursor || separator - cursor > 10)
101 throw new Error("The TAR metadata is damaged.");
102 const lengthText = new TextDecoder().decode(content.subarray(cursor, separator));
103 const length = Number(lengthText);
104 const end = cursor + length;
105 if (
106 !/^[1-9]\d*$/.test(lengthText) ||
107 !Number.isSafeInteger(length) ||
108 end > content.length ||
109 end <= separator + 1 ||
110 content[end - 1] !== 10
111 )
112 throw new Error("The TAR metadata is damaged.");
113 const record = new TextDecoder().decode(content.subarray(separator + 1, end - 1));
114 const equals = record.indexOf("=");
115 if (equals < 1) throw new Error("The TAR metadata is damaged.");
116 const key = record.slice(0, equals);
117 const value = record.slice(equals + 1);
118 if (["path", "linkpath", "size", "mtime"].includes(key)) {
119 if (type === "x") localPax[key] = value;
120 else if (value || key === "linkpath") globalPax[key] = value;
121 else delete globalPax[key];
122 }
123 cursor = end;
124 }
125 } else if (
126 type === "" ||
127 type === "0" ||
128 type === "5" ||
129 // A hard link shares an earlier member's bytes; one without that member is skipped.
130 (type === "1" && linkpath && files.has(linkpath))
131 ) {
132 if (attributes.mtime && !/^[+-]?\d+(?:\.\d+)?$/.test(attributes.mtime))
133 throw new Error("The TAR metadata is damaged.");
134 const modified =
135 (attributes.mtime ? Number(attributes.mtime) : number(offset + 136, 12)) * 1000;
136 const date = new Date(modified);
137 const linked = type === "1" ? files.get(linkpath) : undefined;
138 entries.push({
139 path,
140 size: linked?.length ?? size,
141 directory: type === "5",
142 modified: Number.isNaN(date.getTime()) ? null : date.toISOString(),
143 });
144 if (type === "5") {
145 files.delete(path);
146 files.delete(path.replace(/\/+$/, ""));
147 } else files.set(path, linked ?? content.slice());
148 } else {
149 files.delete(path);
150 }
151 offset += 512 + Math.ceil(size / 512) * 512;
152 }
153 if (entries.length === 0) throw new Error("This archive has no readable entries.");
154 return entries;
156​
157async function handle(input: BinaryWorkerRequest) {
158 if (input.type === "entry") {
159 const bytes = files.get(input.path);
160 if (!bytes) throw new Error("This archive entry is unavailable.");
161 if (bytes.length > ARCHIVE_ENTRY_MAX_BYTES)
162 throw new Error("Entry previews are limited to 10 MB.");
163 reply({ type: "entry", path: input.path, bytes });
164 return;
165 }
166 if (input.type === "rows") {
167 if (
168 !database ||
169 !tables.includes(input.table) ||
170 !Number.isSafeInteger(input.page) ||
171 input.page < 0
172 )
173 throw new Error("This table is unavailable.");
174 const columns =
175 database
176 .exec(`PRAGMA table_xinfo(${quote(input.table)})`)[0]
177 ?.values.filter((row) => row[6] !== 1)
178 .map((row) => String(row[1]))
179 .slice(0, 50) ?? [];
180 const fields = columns.map((name) => {
181 const field = quote(name);
182 return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || ' bytes]' ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`;
183 });
184 const result = database.exec(
185 `SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`,
186 )[0];
187 reply({
188 type: "rows",
189 table: input.table,
190 page: input.page,
191 columns,
192 rows:
193 result?.values.map((row) => row.map((cell) => (cell === null ? "NULL" : String(cell)))) ??
194 [],
195 });
196 return;
197 }
198 if (input.bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
199 throw new Error("Preview limited to files under 50 MB.");
200 if (input.kind === "sqlite") {
201 const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([
202 import("sql.js"),
203 import("sql.js/dist/sql-wasm.wasm?url"),
204 ]);
205 const SQL = await initSqlJs({ locateFile: () => wasmUrl });
206 database = new SQL.Database(new Uint8Array(input.bytes));
207 database.run("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;");
208 tables =
209 database
210 .exec(
211 "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",
212 )[0]
213 ?.values.map((row) => String(row[0])) ?? [];
214 if (tables.length > 100) throw new Error("Database previews are limited to 100 tables.");
215 reply({
216 type: "sqlite",
217 tables: tables.map((name) => ({
218 name,
219 count: Number(
220 database!.exec(`SELECT count(*) FROM ${quote(name)}`)[0]?.values[0]?.[0] ?? 0,
221 ),
222 })),
223 });
224 } else {
225 files = new Map();
226 let entries: ArchiveEntry[];
227 if (
228 /\.(zip|jar)$/i.test(input.name) ||
229 (input.bytes.byteLength >= 4 &&
230 [0x04034b50, 0x06054b50].includes(new DataView(input.bytes).getUint32(0, true)))
231 ) {
232 const archive = await boundedZip(input.bytes, BINARY_PREVIEW_MAX_BYTES);
233 entries = [...archive].map(([path, file]) => {
234 files.set(path, file.bytes);
235 return {
236 path,
237 size: file.bytes.length,
238 directory: file.directory,
239 modified: Number.isNaN(file.date.getTime()) ? null : file.date.toISOString(),
240 };
241 });
242 } else if (/\.(gz|tgz)$/i.test(input.name) || new Uint8Array(input.bytes)[0] === 0x1f) {
243 const bytes = await gunzip(input.bytes);
244 if (/\.(tar\.gz|tgz)$/i.test(input.name)) entries = tarEntries(bytes);
245 else {
246 const path = input.name.replace(/\.gz$/i, "") || "contents";
247 if (/\.tar$/i.test(path)) entries = tarEntries(bytes);
248 else {
249 files.set(path, bytes);
250 entries = [{ path, size: bytes.length, directory: false, modified: null }];
251 }
252 }
253 } else entries = tarEntries(new Uint8Array(input.bytes));
254 reply({ type: "archive", entries });
255 }
257​
258self.addEventListener("message", (event: MessageEvent<BinaryWorkerRequest>) => {
259 void handle(event.data).catch((cause: unknown) =>
260 reply({
261 type: "error",
262 message: cause instanceof Error ? cause.message : "Could not preview this file.",
263 }),
264 );
265});