Modernize icons and file previews; add bounded ZIP directory viewer
This commit is contained in:
1 parent
9110c8a9d5
commit
2366035c72
67 files changed
+1657
-658
No files matched your search
@@ -0,0 +1,42 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { previewBuffer, previewKind } from "../preview";
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
it("classifies supported previews before server fallback types", () => {
|
||||
for (const [name, kind] of [
|
||||
["a.ZIP", "zip"],
|
||||
["a.dcm", "dicom"],
|
||||
["a.pdf", "pdf"],
|
||||
["a.csv", "csv"],
|
||||
["a.md", "markdown"],
|
||||
["a.tif", "tiff"],
|
||||
["a.mp3", "audio"],
|
||||
["a.mp4", "video"],
|
||||
["a.png", "image"],
|
||||
["a.epub", "epub"],
|
||||
["a.html", "text"],
|
||||
])
|
||||
expect(previewKind(name, "blob")).toBe(kind);
|
||||
expect(previewKind("installer.msi", "blob")).toBeNull();
|
||||
expect(previewKind("folder.zip", "", true)).toBeNull();
|
||||
});
|
||||
it("bounds preview data even without Content-Length", async () => {
|
||||
const cancel = vi.fn();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(11));
|
||||
},
|
||||
cancel,
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
previewBuffer("/raw", new AbortController().signal, 10)
|
||||
).rejects.toThrow("PREVIEW_TOO_LARGE");
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { zipDirectory, zipTree } from "../zip-preview";
|
||||
function central(names: string[]) {
|
||||
const records = names.map((name) => {
|
||||
const text = new TextEncoder().encode(name),
|
||||
data = new Uint8Array(46 + text.length),
|
||||
view = new DataView(data.buffer);
|
||||
view.setUint32(0, 0x02014b50, true);
|
||||
view.setUint16(28, text.length, true);
|
||||
// Huge claimed inflated sizes must never cause allocation or extraction.
|
||||
view.setUint32(24, 0xffffffff, true);
|
||||
data.set(text, 46);
|
||||
return data;
|
||||
});
|
||||
const result = new Uint8Array(records.reduce((n, row) => n + row.length, 0));
|
||||
let offset = 0;
|
||||
for (const row of records) {
|
||||
result.set(row, offset);
|
||||
offset += row.length;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function archive(names: string[]) {
|
||||
const directory = central(names),
|
||||
data = new Uint8Array(100000 + directory.length + 22);
|
||||
data.set(directory, 100000);
|
||||
const end = new DataView(data.buffer, data.length - 22);
|
||||
end.setUint32(0, 0x06054b50, true);
|
||||
end.setUint16(8, names.length, true);
|
||||
end.setUint16(10, names.length, true);
|
||||
end.setUint32(12, directory.length, true);
|
||||
end.setUint32(16, 100000, true);
|
||||
return data;
|
||||
}
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
describe("ZIP listing without extraction", () => {
|
||||
it("fetches a larger central directory separately without reading file data", async () => {
|
||||
const names = Array.from(
|
||||
{ length: 2000 },
|
||||
(_, index) => `folder/file-${index}.txt`
|
||||
);
|
||||
const data = archive(names);
|
||||
const fetcher = vi.fn(async (_source: string, options: RequestInit) => {
|
||||
const [, start, end] = /bytes=(\d+)-(\d+)/.exec(
|
||||
(options.headers as Record<string, string>).Range
|
||||
)!;
|
||||
expect(Number(start)).toBeGreaterThanOrEqual(100000);
|
||||
return new Response(data.slice(Number(start), Number(end) + 1), {
|
||||
status: 206,
|
||||
headers: { "Content-Range": `bytes ${start}-${end}/${data.length}` },
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
expect(
|
||||
(await zipTree("/zip", data.length, new AbortController().signal))[0]
|
||||
.children
|
||||
).toHaveLength(2000);
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("builds directories, merges explicit parents and sorts folders first", () => {
|
||||
const rows = zipDirectory(central(["z.txt", "scans/a.dcm", "scans/"]), 3);
|
||||
expect(rows.map((node) => node.name)).toEqual(["scans", "z.txt"]);
|
||||
expect(rows[0].children[0].name).toBe("a.dcm");
|
||||
});
|
||||
it("rejects traversal, conflicting paths, deep trees and truncated records", () => {
|
||||
for (const name of ["../a", "/a", "a/./b", "a\u0000b", "a/".repeat(33)])
|
||||
expect(() => zipDirectory(central([name]), 1)).toThrow();
|
||||
expect(() => zipDirectory(central(["a", "a/b"]), 2)).toThrow();
|
||||
expect(() => zipDirectory(central(["a"]).subarray(0, 45), 1)).toThrow();
|
||||
expect(() => zipDirectory(new Uint8Array(), 10001)).toThrow("ZIP_LIMIT");
|
||||
expect(() => zipDirectory(new Uint8Array(4 * 1024 * 1024 + 1), 0)).toThrow(
|
||||
"ZIP_LIMIT"
|
||||
);
|
||||
});
|
||||
it("reads only the bounded tail and central directory, never local entries", async () => {
|
||||
const data = archive(["a.dcm"]);
|
||||
const fetcher = vi.fn(async (_source: string, options: RequestInit) => {
|
||||
const header = (options.headers as Record<string, string>).Range;
|
||||
const [, start, end] = /bytes=(\d+)-(\d+)/.exec(header)!;
|
||||
expect(Number(start)).toBeGreaterThan(0);
|
||||
return new Response(data.slice(Number(start), Number(end) + 1), {
|
||||
status: 206,
|
||||
headers: { "Content-Range": `bytes ${start}-${end}/${data.length}` },
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
expect(
|
||||
(
|
||||
await zipTree("/raw/a.zip", data.length, new AbortController().signal)
|
||||
)[0].name
|
||||
).toBe("a.dcm");
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("refuses full responses instead of downloading the archive", async () => {
|
||||
const cancel = vi.fn();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(new ReadableStream({ cancel }), { status: 200 })
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
zipTree("/zip", 100000, new AbortController().signal)
|
||||
).rejects.toThrow("ZIP_RANGE");
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("rejects ZIP64 and oversized central directories before a second request", async () => {
|
||||
for (const field of ["zip64", "directory", "entries"]) {
|
||||
const data = archive(["a"]),
|
||||
end = new DataView(data.buffer, data.length - 22);
|
||||
if (field === "zip64") end.setUint32(16, 0xffffffff, true);
|
||||
if (field === "directory") end.setUint32(12, 5 * 1024 * 1024, true);
|
||||
if (field === "entries") {
|
||||
end.setUint16(8, 10001, true);
|
||||
end.setUint16(10, 10001, true);
|
||||
}
|
||||
const fetcher = vi.fn(
|
||||
async () =>
|
||||
new Response(data.slice(data.length - 65557), {
|
||||
status: 206,
|
||||
headers: {
|
||||
"Content-Range": `bytes ${data.length - 65557}-${data.length - 1}/${data.length}`,
|
||||
},
|
||||
})
|
||||
);
|
||||
vi.stubGlobal("fetch", fetcher);
|
||||
await expect(
|
||||
zipTree("/zip", data.length, new AbortController().signal)
|
||||
).rejects.toThrow();
|
||||
expect(fetcher).toHaveBeenCalledOnce();
|
||||
}
|
||||
});
|
||||
it("cancels a range response exceeding its declared size", async () => {
|
||||
const cancel = vi.fn();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(65558));
|
||||
},
|
||||
cancel,
|
||||
}),
|
||||
{
|
||||
status: 206,
|
||||
headers: { "Content-Range": "bytes 34443-99999/100000" },
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
zipTree("/zip", 100000, new AbortController().signal)
|
||||
).rejects.toThrow("ZIP_LIMIT");
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
// Native SVG paths: one stroke weight, rounded ends and no icon font requests.
|
||||
const paths: Record<string, string> = {
|
||||
file: "M6 3h8l4 4v14H6z M14 3v5h4 M9 12h6 M9 16h6",
|
||||
folder: "M3 7V5h7l2 2h9v13H3z",
|
||||
folderOpen: "M3 10V5h7l2 2h9v3 M3 10h19l-3 10H3z",
|
||||
home: "m3 10 9-7 9 7 M5 9v12h5v-7h4v7h5V9",
|
||||
search: "M20 20l-5-5 M17 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0",
|
||||
close: "m6 6 12 12 M6 18 18 6",
|
||||
add: "M12 5v14 M5 12h14",
|
||||
remove: "M5 12h14",
|
||||
right: "m9 5 7 7-7 7",
|
||||
left: "m15 5-7 7 7 7",
|
||||
down: "m5 9 7 7 7-7",
|
||||
up: "m5 15 7-7 7 7",
|
||||
download: "M12 3v12 m-5-5 5 5 5-5 M4 16v5h16v-5",
|
||||
upload: "M12 16V4 m-5 5 5-5 5 5 M4 16v5h16v-5",
|
||||
trash: "M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7",
|
||||
edit: "m15 4 5 5 M4 20l5-1L21 7l-5-5L4 14z",
|
||||
copy: "M8 8h12v13H8z M4 16H2V2h13v2",
|
||||
paste: "M9 4H5v17h14V4h-4 M9 2h6v5H9z M8 11h8 M8 15h8",
|
||||
cut: "M9 8 20 20 M9 16 20 4 M9 7a3 3 0 1 1-6 0 3 3 0 0 1 6 0 M9 17a3 3 0 1 1-6 0 3 3 0 0 1 6 0",
|
||||
settings:
|
||||
"M12 3v3 M12 18v3 M3 12h3 M18 12h3 M5.5 5.5l2 2 M16.5 16.5l2 2 M5.5 18.5l2-2 M16.5 7.5l2-2 M17 12a5 5 0 1 1-10 0 5 5 0 0 1 10 0",
|
||||
sliders: "M4 7h3 M11 7h9 M4 17h9 M17 17h3 M7 4h4v6H7z M13 14h4v6h-4z",
|
||||
user: "M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0 M4 21v-3a8 5 0 0 1 16 0v3",
|
||||
users:
|
||||
"M14 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0 M2 21v-3a8 5 0 0 1 16 0v3 M17 3a4 4 0 0 1 0 8 M20 15a4 4 0 0 1 2 4v2",
|
||||
link: "m9 15 6-6 M8 16l-1 1a4 4 0 0 1-6-6l5-5a4 4 0 0 1 6 0 M16 8l1-1a4 4 0 0 1 6 6l-5 5a4 4 0 0 1-6 0",
|
||||
external: "M14 3h7v7 M21 3 10 14 M10 3H3v18h18v-7",
|
||||
back: "M20 12H4 m6-6-6 6 6 6",
|
||||
more: "M5 12h.01 M12 12h.01 M19 12h.01",
|
||||
moreVertical: "M12 5v.01 M12 12v.01 M12 19v.01",
|
||||
menu: "M3 6h18 M3 12h18 M3 18h18",
|
||||
info: "M12 11v6 M12 7v.01 M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0",
|
||||
warning: "m12 3 10 18H2z M12 9v5 M12 17v.01",
|
||||
check: "m4 12 5 5L20 6",
|
||||
checkCircle: "m8 12 3 3 5-6 M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0",
|
||||
refresh: "M20 8a8 8 0 1 0 0 8 M20 3v5h-5",
|
||||
undo: "m8 4-5 5 5 5 M3 9h11a6 6 0 0 1 0 12",
|
||||
save: "M4 3h13l4 4v14H3V3z M7 3v6h9V3 M7 21v-8h10v8",
|
||||
login: "M13 3h8v18h-8 M3 12h13 m-5-5 5 5-5 5",
|
||||
logout: "M11 3H3v18h8 M9 12h12 m-5-5 5 5-5 5",
|
||||
eye: "M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12 M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0",
|
||||
image: "M3 3h18v18H3z m0 14 6-6 5 5 3-3 4 4 M16 7h.01",
|
||||
music:
|
||||
"M10 17V5l10-2v12 M10 17a3 3 0 1 1-6 0 3 3 0 0 1 6 0 M20 15a3 3 0 1 1-6 0 3 3 0 0 1 6 0",
|
||||
video: "M3 5h12v14H3z m12 5 7-4v12l-7-4",
|
||||
table: "M3 4h18v16H3z M3 9h18 M3 14h18 M9 4v16 M15 4v16",
|
||||
code: "m8 6-6 6 6 6 m8-12 6 6-6 6 M14 3l-4 18",
|
||||
archive: "M3 4h18v5H3z M5 9v12h14V9 M10 13h4",
|
||||
disc: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0 M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0",
|
||||
package: "m3 7 9-4 9 4-9 4z M3 7v10l9 4 9-4V7 M12 11v10 M7 5l10 4",
|
||||
calendar: "M4 5h16v16H4z M8 3v4 M16 3v4 M4 10h16 M8 14h2 M14 14h2",
|
||||
server: "M3 3h18v7H3z M3 14h18v7H3z M7 6.5h.01 M7 17.5h.01",
|
||||
globe:
|
||||
"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0 M3 12h18 M12 3c5 5 5 13 0 18-5-5-5-13 0-18",
|
||||
bookmark: "M6 3h12v18l-6-4-6 4z",
|
||||
star: "m12 3 3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z",
|
||||
mouse: "M5 10a7 7 0 0 1 14 0v5a7 7 0 0 1-14 0z M12 3v7 M5 10h14",
|
||||
contrast: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0 M12 3v18 M16 6v12",
|
||||
lock: "M5 10h14v11H5z M8 10V6a4 4 0 0 1 8 0v4 M12 14v3",
|
||||
shield: "M12 2 3 6v6c0 5 9 10 9 10s9-5 9-10V6z m-5 10 3 3 5-6",
|
||||
palette:
|
||||
"M12 3a9 9 0 1 0 0 18c3 0 1-4 3-4h3c5 0 4-14-6-14 M7 10h.01 M10 6h.01 M15 7h.01 M18 11h.01",
|
||||
share:
|
||||
"M8 12 17 6 M8 12l9 6 M8 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0 M22 5a3 3 0 1 1-6 0 3 3 0 0 1 6 0 M22 19a3 3 0 1 1-6 0 3 3 0 0 1 6 0",
|
||||
};
|
||||
const aliases: Record<string, string> = {
|
||||
cloud_off: "warning",
|
||||
gps_off: "search",
|
||||
edit_note: "edit",
|
||||
view_module: "table",
|
||||
grid_view: "table",
|
||||
view_list: "menu",
|
||||
insert_drive_file: "file",
|
||||
description: "file",
|
||||
note_add: "file",
|
||||
picture_as_pdf: "file",
|
||||
article: "file",
|
||||
font_download: "file",
|
||||
web_asset: "package",
|
||||
folder_open: "folderOpen",
|
||||
folder_copy: "folder",
|
||||
folder_shared: "folder",
|
||||
create_new_folder: "folder",
|
||||
folder_zip: "archive",
|
||||
insert_photo: "image",
|
||||
volume_up: "music",
|
||||
movie: "video",
|
||||
slideshow: "video",
|
||||
border_all: "table",
|
||||
album: "disc",
|
||||
clear: "close",
|
||||
cancel: "close",
|
||||
delete: "trash",
|
||||
delete_outline: "trash",
|
||||
mode_edit: "edit",
|
||||
content_copy: "copy",
|
||||
content_paste: "paste",
|
||||
content_cut: "cut",
|
||||
settings_applications: "settings",
|
||||
manage_accounts: "user",
|
||||
account_circle: "user",
|
||||
person: "user",
|
||||
person_add: "user",
|
||||
group: "users",
|
||||
tune: "sliders",
|
||||
open_in_new: "external",
|
||||
north_east: "external",
|
||||
arrow_back: "back",
|
||||
forward: "right",
|
||||
chevron_right: "right",
|
||||
keyboard_arrow_right: "right",
|
||||
chevron_left: "left",
|
||||
keyboard_arrow_left: "left",
|
||||
expand_more: "down",
|
||||
keyboard_arrow_down: "down",
|
||||
expand_less: "up",
|
||||
keyboard_arrow_up: "up",
|
||||
arrow_upward: "up",
|
||||
arrow_downward: "down",
|
||||
arrow_drop_up: "up",
|
||||
arrow_drop_down: "down",
|
||||
sort: "sliders",
|
||||
file_download: "download",
|
||||
file_upload: "upload",
|
||||
cloud_upload: "upload",
|
||||
exit_to_app: "logout",
|
||||
more_horiz: "more",
|
||||
more_vert: "moreVertical",
|
||||
info_outline: "info",
|
||||
feedback: "info",
|
||||
error_outline: "warning",
|
||||
error: "warning",
|
||||
sentiment_dissatisfied: "info",
|
||||
check_circle: "checkCircle",
|
||||
done: "check",
|
||||
done_all: "check",
|
||||
checklist: "check",
|
||||
select_all: "check",
|
||||
check_box: "check",
|
||||
autorenew: "refresh",
|
||||
replay: "refresh",
|
||||
refresh: "refresh",
|
||||
bookmark_add: "bookmark",
|
||||
star_outline: "star",
|
||||
public: "globe",
|
||||
language: "globe",
|
||||
dns: "server",
|
||||
storage: "server",
|
||||
policy: "shield",
|
||||
security: "shield",
|
||||
help: "info",
|
||||
visibility: "eye",
|
||||
visibility_off: "eye",
|
||||
preview: "eye",
|
||||
photo_size_select_large: "image",
|
||||
hd: "image",
|
||||
zoom_in: "add",
|
||||
zoom_out: "remove",
|
||||
stop_circle: "close",
|
||||
schedule: "calendar",
|
||||
link_off: "link",
|
||||
add_link: "link",
|
||||
};
|
||||
export function iconPath(name = "file"): string {
|
||||
return paths[aliases[name] || name] || paths.file;
|
||||
}
|
||||
export function hasIcon(name: string): boolean {
|
||||
return !!(paths[name] || paths[aliases[name]]);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
export type PreviewKind =
|
||||
| "zip"
|
||||
| "pdf"
|
||||
| "dicom"
|
||||
| "image"
|
||||
| "tiff"
|
||||
| "audio"
|
||||
| "video"
|
||||
| "text"
|
||||
| "markdown"
|
||||
| "csv"
|
||||
| "epub";
|
||||
export function previewKind(
|
||||
name: string,
|
||||
type = "",
|
||||
directory = false
|
||||
): PreviewKind | null {
|
||||
if (directory) return null;
|
||||
const ext = name.split(".").pop()?.toLowerCase() || "";
|
||||
if (["dcm", "dicom"].includes(ext)) return "dicom";
|
||||
if (ext === "pdf") return "pdf";
|
||||
if (ext === "zip") return "zip";
|
||||
if (ext === "csv") return "csv";
|
||||
if (["md", "markdown"].includes(ext)) return "markdown";
|
||||
if (ext === "epub") return "epub";
|
||||
if (["tif", "tiff", "dng", "cr2", "nef"].includes(ext)) return "tiff";
|
||||
if (
|
||||
[
|
||||
"png",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"jfif",
|
||||
"gif",
|
||||
"webp",
|
||||
"avif",
|
||||
"bmp",
|
||||
"ico",
|
||||
"svg",
|
||||
].includes(ext) ||
|
||||
type === "image"
|
||||
)
|
||||
return "image";
|
||||
if (
|
||||
["mp3", "wav", "ogg", "oga", "flac", "m4a", "aac", "opus"].includes(ext) ||
|
||||
type === "audio"
|
||||
)
|
||||
return "audio";
|
||||
if (["mp4", "m4v", "webm", "ogv", "mov"].includes(ext) || type === "video")
|
||||
return "video";
|
||||
if (
|
||||
[
|
||||
"txt",
|
||||
"tsv",
|
||||
"log",
|
||||
"json",
|
||||
"xml",
|
||||
"yaml",
|
||||
"yml",
|
||||
"toml",
|
||||
"ini",
|
||||
"conf",
|
||||
"css",
|
||||
"js",
|
||||
"ts",
|
||||
"jsx",
|
||||
"tsx",
|
||||
"html",
|
||||
"htm",
|
||||
"sh",
|
||||
"bat",
|
||||
"ps1",
|
||||
"py",
|
||||
"go",
|
||||
"rs",
|
||||
"c",
|
||||
"cpp",
|
||||
"h",
|
||||
"java",
|
||||
"sql",
|
||||
].includes(ext) ||
|
||||
["text", "textImmutable"].includes(type)
|
||||
)
|
||||
return "text";
|
||||
return null;
|
||||
}
|
||||
export async function previewBuffer(
|
||||
source: string,
|
||||
signal: AbortSignal,
|
||||
limit = 5 * 1024 * 1024
|
||||
): Promise<ArrayBuffer> {
|
||||
const response = await fetch(source, { credentials: "same-origin", signal });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
if (Number(response.headers.get("Content-Length")) > limit) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("PREVIEW_TOO_LARGE");
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error("Empty response");
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
while (true) {
|
||||
const result = await reader.read();
|
||||
if (result.done) break;
|
||||
length += result.value.length;
|
||||
if (length > limit) {
|
||||
await reader.cancel();
|
||||
throw new Error("PREVIEW_TOO_LARGE");
|
||||
}
|
||||
chunks.push(result.value);
|
||||
}
|
||||
const data = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
data.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
return data.buffer;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// List the central directory only. Never read, inflate or follow file entries.
|
||||
const MAX_DIRECTORY = 4 * 1024 * 1024;
|
||||
const MAX_ENTRIES = 10000;
|
||||
const MAX_NODES = 20000;
|
||||
export interface ZipNode {
|
||||
name: string;
|
||||
directory: boolean;
|
||||
children: ZipNode[];
|
||||
}
|
||||
export function zipDirectory(data: Uint8Array, expected: number): ZipNode[] {
|
||||
if (data.length > MAX_DIRECTORY || expected > MAX_ENTRIES)
|
||||
throw new Error("ZIP_LIMIT");
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
const root: ZipNode = { name: "", directory: true, children: [] };
|
||||
const nodes = new Map<string, ZipNode>();
|
||||
let offset = 0;
|
||||
for (let index = 0; index < expected; index++) {
|
||||
if (
|
||||
offset + 46 > data.length ||
|
||||
view.getUint32(offset, true) !== 0x02014b50
|
||||
)
|
||||
throw new Error("ZIP_INVALID");
|
||||
const length = view.getUint16(offset + 28, true);
|
||||
const end = offset + 46 + length;
|
||||
const next =
|
||||
end +
|
||||
view.getUint16(offset + 30, true) +
|
||||
view.getUint16(offset + 32, true);
|
||||
if (!length || length > 1024 || next > data.length)
|
||||
throw new Error("ZIP_LIMIT");
|
||||
// Filenames are rendered as text, never used as filesystem paths or URLs.
|
||||
const name = new TextDecoder("utf-8").decode(
|
||||
data.subarray(offset + 46, end)
|
||||
);
|
||||
const parts = name.replace(/\\/g, "/").split("/");
|
||||
const directory = parts[parts.length - 1] === "";
|
||||
if (directory) parts.pop();
|
||||
if (
|
||||
parts.length > 32 ||
|
||||
parts.some(
|
||||
(part) =>
|
||||
!part ||
|
||||
part === "." ||
|
||||
part === ".." ||
|
||||
/[\u0000-\u001f\u007f]/.test(part)
|
||||
)
|
||||
)
|
||||
throw new Error("ZIP_INVALID");
|
||||
let parent = root,
|
||||
key = "";
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
key += "/" + parts[i];
|
||||
const isDirectory = i < parts.length - 1 || directory;
|
||||
let node = nodes.get(key);
|
||||
if (!node) {
|
||||
if (nodes.size >= MAX_NODES) throw new Error("ZIP_LIMIT");
|
||||
node = { name: parts[i], directory: isDirectory, children: [] };
|
||||
nodes.set(key, node);
|
||||
parent.children.push(node);
|
||||
} else if (node.directory !== isDirectory) throw new Error("ZIP_INVALID");
|
||||
parent = node;
|
||||
}
|
||||
offset = next;
|
||||
}
|
||||
if (offset !== data.length) throw new Error("ZIP_INVALID");
|
||||
function sort(node: ZipNode) {
|
||||
node.children.sort(
|
||||
(a, b) =>
|
||||
Number(b.directory) - Number(a.directory) ||
|
||||
a.name.localeCompare(b.name)
|
||||
);
|
||||
node.children.forEach(sort);
|
||||
}
|
||||
sort(root);
|
||||
return root.children;
|
||||
}
|
||||
async function range(
|
||||
source: string,
|
||||
start: number,
|
||||
end: number,
|
||||
size: number,
|
||||
signal: AbortSignal
|
||||
) {
|
||||
const response = await fetch(source, {
|
||||
credentials: "same-origin",
|
||||
signal,
|
||||
headers: { Range: `bytes=${start}-${end}` },
|
||||
});
|
||||
const expected = end - start + 1;
|
||||
if (
|
||||
response.status !== 206 ||
|
||||
response.headers.get("Content-Range") !== `bytes ${start}-${end}/${size}` ||
|
||||
(response.headers.has("Content-Length") &&
|
||||
Number(response.headers.get("Content-Length")) !== expected)
|
||||
) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("ZIP_RANGE");
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error("ZIP_INVALID");
|
||||
const bytes = new Uint8Array(expected);
|
||||
let offset = 0;
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
if (offset + value.length > expected) {
|
||||
await reader.cancel();
|
||||
throw new Error("ZIP_LIMIT");
|
||||
}
|
||||
bytes.set(value, offset);
|
||||
offset += value.length;
|
||||
}
|
||||
if (offset !== expected) throw new Error("ZIP_INVALID");
|
||||
return bytes;
|
||||
}
|
||||
export async function zipTree(
|
||||
source: string,
|
||||
size: number,
|
||||
signal: AbortSignal
|
||||
): Promise<ZipNode[]> {
|
||||
if (!Number.isSafeInteger(size) || size < 22) throw new Error("ZIP_INVALID");
|
||||
const start = Math.max(0, size - 65557);
|
||||
const tail = await range(source, start, size - 1, size, signal);
|
||||
const view = new DataView(tail.buffer);
|
||||
for (let at = tail.length - 22; at >= 0; at--) {
|
||||
if (
|
||||
view.getUint32(at, true) !== 0x06054b50 ||
|
||||
at + 22 + view.getUint16(at + 20, true) !== tail.length
|
||||
)
|
||||
continue;
|
||||
const entries = view.getUint16(at + 10, true);
|
||||
const length = view.getUint32(at + 12, true);
|
||||
const offset = view.getUint32(at + 16, true);
|
||||
if (
|
||||
view.getUint16(at + 4, true) ||
|
||||
view.getUint16(at + 6, true) ||
|
||||
view.getUint16(at + 8, true) !== entries ||
|
||||
entries === 65535 ||
|
||||
length === 0xffffffff ||
|
||||
offset === 0xffffffff
|
||||
)
|
||||
throw new Error("ZIP_UNSUPPORTED");
|
||||
if (entries > MAX_ENTRIES || length > MAX_DIRECTORY)
|
||||
throw new Error("ZIP_LIMIT");
|
||||
if (offset + length !== start + at) throw new Error("ZIP_INVALID");
|
||||
if (!entries && !length) return [];
|
||||
if (!length) throw new Error("ZIP_INVALID");
|
||||
const data =
|
||||
offset >= start
|
||||
? tail.subarray(offset - start, offset - start + length)
|
||||
: await range(source, offset, offset + length - 1, size, signal);
|
||||
return zipDirectory(data, entries);
|
||||
}
|
||||
throw new Error("ZIP_INVALID");
|
||||
}
|
||||
Reference in new issue
Block a user