keycloakify 7.3.0 → 7.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ import { createReadStream, createWriteStream } from "fs";
2
+ import { mkdir, stat, unlink } from "fs/promises";
3
+ import { dirname as pathDirname, join as pathJoin, relative as pathRelative } from "path";
4
+ import { type Readable } from "stream";
5
+ import { createInflateRaw } from "zlib";
6
+ import { partitionPromiseSettledResults } from "./partitionPromiseSettledResults";
7
+
8
+ export type MultiError = Error & { cause: Error[] };
9
+
10
+ /**
11
+ * Extract the archive `zipFile` into the directory `dir`. If `archiveDir` is given,
12
+ * only that directory will be extracted, stripping the given path components.
13
+ *
14
+ * If dir does not exist, it will be created.
15
+ *
16
+ * If any archive file exists, it will be overwritten.
17
+ *
18
+ * Will unzip using all available nodejs worker threads.
19
+ *
20
+ * Will try to clean up extracted files on failure.
21
+ *
22
+ * If unpacking fails, will either throw an regular error, or
23
+ * possibly an `MultiError`, which contains a `cause` field with
24
+ * a number of root cause errors.
25
+ *
26
+ * Warning this method is not optimized for continuous reading of the zip
27
+ * archive, but is a trade-off between simplicity and allowing extraction
28
+ * of a single directory from the archive.
29
+ *
30
+ * @param zipFilePath the file to unzip
31
+ * @param extractDirPath the target directory
32
+ * @param pathOfDirToExtractInArchive if given, unpack only files from this archive directory
33
+ * @throws {MultiError} error
34
+ * @returns Promise for a list of full file paths pointing to actually extracted files
35
+ */
36
+ export async function unzip(zipFilePath: string, extractDirPath: string, pathOfDirToExtractInArchive?: string): Promise<string[]> {
37
+ const dirsCreated: (string | undefined)[] = [];
38
+ dirsCreated.push(await mkdir(extractDirPath, { recursive: true }));
39
+ const promises: Promise<string>[] = [];
40
+
41
+ // Iterate over all files in the zip, skip files which are not in archiveDir,
42
+ // if given.
43
+ for await (const record of iterateZipArchive(zipFilePath)) {
44
+ const { path: recordPath, createReadStream: createRecordReadStream } = record;
45
+ if (pathOfDirToExtractInArchive && !recordPath.startsWith(pathOfDirToExtractInArchive)) {
46
+ continue;
47
+ }
48
+ const relativePath = pathOfDirToExtractInArchive ? pathRelative(pathOfDirToExtractInArchive, recordPath) : recordPath;
49
+ const filePath = pathJoin(extractDirPath, relativePath);
50
+ const parent = pathDirname(filePath);
51
+ promises.push(
52
+ new Promise<string>(async (resolve, reject) => {
53
+ if (!dirsCreated.includes(parent)) dirsCreated.push(await mkdir(parent, { recursive: true }));
54
+
55
+ // Pull the file out of the archive, write it to the target directory
56
+ const output = createWriteStream(filePath);
57
+ output.on("error", e => reject(Object.assign(e, { filePath })));
58
+ output.on("finish", () => resolve(filePath));
59
+ createRecordReadStream().pipe(output);
60
+ })
61
+ );
62
+ }
63
+
64
+ // Wait until _all_ files are either extracted or failed
65
+ const [success, failure] = (await Promise.allSettled(promises)).reduce(...partitionPromiseSettledResults<string>());
66
+
67
+ // If any extraction failed, try to clean up, then throw a MultiError,
68
+ // which has a `cause` field, containing a list of root cause errors.
69
+ if (failure.length) {
70
+ await Promise.all([
71
+ ...success.map(path => unlink(path).catch(_unused => undefined)),
72
+ ...failure.map(e => e && e.path && unlink(e.path as string).catch(_unused => undefined))
73
+ ]);
74
+ await Promise.all(dirsCreated.filter(Boolean).sort(sortByFolderDepth("desc")));
75
+ const e = new Error("Failed to extract: " + failure.map(e => e.message).join(";"));
76
+ (e as any).cause = failure;
77
+ throw e;
78
+ }
79
+
80
+ return success;
81
+ }
82
+
83
+ function depth(dir: string) {
84
+ return dir.match(/\//g)?.length ?? 0;
85
+ }
86
+
87
+ function sortByFolderDepth(order: "asc" | "desc") {
88
+ const ord = order === "asc" ? 1 : -1;
89
+ return (a: string | undefined, b: string | undefined) => ord * depth(a ?? "") + -ord * depth(b ?? "");
90
+ }
91
+
92
+ /**
93
+ *
94
+ * @param file file to read
95
+ * @param start first byte to read
96
+ * @param end last byte to read
97
+ * @returns Promise of a buffer of read bytes
98
+ */
99
+ async function readFileChunk(file: string, start: number, end: number): Promise<Buffer> {
100
+ const chunks: Buffer[] = [];
101
+ return new Promise((resolve, reject) => {
102
+ const stream = createReadStream(file, { start, end });
103
+ stream.setMaxListeners(Infinity);
104
+ stream.on("error", e => reject(e));
105
+ stream.on("end", () => resolve(Buffer.concat(chunks)));
106
+ stream.on("data", chunk => chunks.push(chunk as Buffer));
107
+ });
108
+ }
109
+
110
+ type ZipRecord = {
111
+ path: string;
112
+ createReadStream: () => Readable;
113
+ compressionMethod: "deflate" | undefined;
114
+ };
115
+
116
+ type ZipRecordGenerator = AsyncGenerator<ZipRecord, void, unknown>;
117
+
118
+ /**
119
+ * Iterate over all records of a zipfile, and yield a ZipRecord.
120
+ * Use `record.createReadStream()` to actually read the file.
121
+ *
122
+ * Warning this method will only work with single-disk zip files.
123
+ * Warning this method may fail if the zip archive has an crazy amount
124
+ * of files and the central directory is not fully contained within the
125
+ * last 65k bytes of the zip file.
126
+ *
127
+ * @param zipFile
128
+ * @returns AsyncGenerator which will yield ZipRecords
129
+ */
130
+ async function* iterateZipArchive(zipFile: string): ZipRecordGenerator {
131
+ // Need to know zip file size before we can do anything else
132
+ const { size } = await stat(zipFile);
133
+ const chunkSize = 65_535 + 22 + 1; // max comment size + end header size + wiggle
134
+ // Read last ~65k bytes. Zip files have an comment up to 65_535 bytes at the very end,
135
+ // before that comes the zip central directory end header.
136
+ let chunk = await readFileChunk(zipFile, size - chunkSize, size);
137
+ const unread = size - chunk.length;
138
+ let i = chunk.length - 4;
139
+ let found = false;
140
+ // Find central directory end header, reading backwards from the end
141
+ while (!found && i-- > 0) if (chunk[i] === 0x50 && chunk.readUInt32LE(i) === 0x06054b50) found = true;
142
+ if (!found) throw new Error("Not a zip file");
143
+ // This method will fail on a multi-disk zip, so bail early.
144
+ if (chunk.readUInt16LE(i + 4) !== 0) throw new Error("Multi-disk zip not supported");
145
+ let nFiles = chunk.readUint16LE(i + 10);
146
+ // Get the position of the central directory
147
+ const directorySize = chunk.readUint32LE(i + 12);
148
+ const directoryOffset = chunk.readUint32LE(i + 16);
149
+ if (directoryOffset === 0xffff_ffff) throw new Error("zip64 not supported");
150
+ if (directoryOffset > size) throw new Error(`Central directory offset ${directoryOffset} is outside file`);
151
+ i = directoryOffset - unread;
152
+ // If i < 0, it means that the central directory is not contained within `chunk`
153
+ if (i < 0) {
154
+ chunk = await readFileChunk(zipFile, directoryOffset, directoryOffset + directorySize);
155
+ i = 0;
156
+ }
157
+ // Now iterate the central directory records, yield an `ZipRecord` for every entry
158
+ while (nFiles-- > 0) {
159
+ // Check for marker bytes
160
+ if (chunk.readUInt32LE(i) !== 0x02014b50) throw new Error("No central directory record at position " + (unread + i));
161
+ const compressionMethod = ({ 8: "deflate" } as const)[chunk.readUint16LE(i + 10)];
162
+ const compressedFileSize = chunk.readUint32LE(i + 20);
163
+ const filenameLength = chunk.readUint16LE(i + 28);
164
+ const extraLength = chunk.readUint16LE(i + 30);
165
+ const commentLength = chunk.readUint16LE(i + 32);
166
+ // Start of the actual content byte stream is after the 'local' record header,
167
+ // which is 30 bytes long plus filename and extra field
168
+ const start = chunk.readUint32LE(i + 42) + 30 + filenameLength + extraLength;
169
+ const end = start + compressedFileSize;
170
+ const filename = chunk.slice(i + 46, i + 46 + filenameLength).toString("utf-8");
171
+ const createRecordReadStream = () => {
172
+ const input = createReadStream(zipFile, { start, end });
173
+ if (compressionMethod === "deflate") {
174
+ const inflate = createInflateRaw();
175
+ input.pipe(inflate);
176
+ return inflate;
177
+ }
178
+ return input;
179
+ };
180
+ if (end > start) yield { path: filename, createReadStream: createRecordReadStream, compressionMethod };
181
+ // advance pointer to next central directory entry
182
+ i += 46 + filenameLength + extraLength + commentLength;
183
+ }
184
+ }