Repository navigation
Expand file tree
/
Copy pathunpack-worker.js
More file actions
89 lines (66 loc) · 2.53 KB
/
Copy pathunpack-worker.js
File metadata and controls
89 lines (66 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const fs = require("fs");
const zlib = require("zlib");
const path = require("path");
// Get the file paths from command line arguments
let [jsonFilePath, destDir] = process.argv.slice(2);
if (!jsonFilePath || !destDir) {
console.error("Usage: node script.js <json-file-path> <destination-directory>");
process.exit(1);
}
// Function to decompress the content
function decompressContent(base64Encoded) {
// Decode base64 string to buffer
const compressedData = Buffer.from(base64Encoded, "base64");
// Decompress the data
const decompressedData = zlib.inflateSync(compressedData);
// Convert buffer to string
return decompressedData.toString();
}
try {
// Read and parse the JSON file
const jsonContent = fs.readFileSync(jsonFilePath, "utf8");
const data = JSON.parse(jsonContent)[0];
console.log(data);
const id = data.id;
// The id becomes the extraction root, so it must be a single path component.
if (
typeof id !== "string" ||
id.length === 0 ||
id === "." ||
id === ".." ||
id.includes("/") ||
id.includes("\\") ||
id.includes("\0")
) {
throw new Error(`Unsafe worker id: ${id}`);
}
console.log(`Extracting files for: ${id} to ${destDir}`);
destDir = path.join(destDir, id);
console.log(`Extracting files to: ${destDir}`);
// Resolve the extraction root once so we can keep every file inside it.
const extractionRoot = path.resolve(destDir);
// Create the destination directory if it doesn't exist
fs.mkdirSync(extractionRoot, { recursive: true });
// Process each item in the array
const sourceFiles = data.metadata.sourceFiles;
sourceFiles.forEach((file) => {
// Decompress the contents
const decompressedContent = decompressContent(file.contents);
// Combine destination directory with file path
const fullPath = path.resolve(extractionRoot, file.filePath);
// Reject any path that escapes the extraction root (zip-slip via ../ etc.)
if (fullPath !== extractionRoot && !fullPath.startsWith(extractionRoot + path.sep)) {
throw new Error(`Refusing to write outside destination: ${file.filePath}`);
}
// Create directory structure if it doesn't exist
const dirPath = path.dirname(fullPath);
fs.mkdirSync(dirPath, { recursive: true });
// Write the decompressed content to the file
fs.writeFileSync(fullPath, decompressedContent);
console.log(`Created file: ${fullPath}`);
});
console.log(`\nAll files have been extracted to: ${extractionRoot}`);
} catch (error) {
console.error(error);
process.exit(1);
}