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

binaryPreview.worker.ts

273 lines11.1 KB

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