UNPKG

3.31 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.hashFileContents = exports.hashFile = exports.computeData = void 0;
4const bluebird_lst_1 = require("bluebird-lst");
5const crypto_1 = require("crypto");
6const fs_1 = require("fs");
7const promises_1 = require("fs/promises");
8const path = require("path");
9const asar_1 = require("./asar");
10async function computeData({ resourcesPath, resourcesRelativePath }) {
11 // sort to produce constant result
12 const names = (await (0, promises_1.readdir)(resourcesPath)).filter(it => it.endsWith(".asar")).sort();
13 const checksums = await bluebird_lst_1.default.map(names, it => hashHeader(path.join(resourcesPath, it)));
14 const result = {};
15 for (let i = 0; i < names.length; i++) {
16 result[path.join(resourcesRelativePath, names[i])] = checksums[i];
17 }
18 return result;
19}
20exports.computeData = computeData;
21async function hashHeader(file) {
22 const hash = (0, crypto_1.createHash)("sha256");
23 const { header } = await (0, asar_1.readAsarHeader)(file);
24 hash.update(header);
25 return {
26 algorithm: "SHA256",
27 hash: hash.digest("hex"),
28 };
29}
30function hashFile(file, blockSize = 4 * 1024 * 1024) {
31 return new Promise((resolve, reject) => {
32 const hash = (0, crypto_1.createHash)("sha256");
33 const blocks = new Array();
34 let blockBytes = 0;
35 let blockHash = (0, crypto_1.createHash)("sha256");
36 function updateBlockHash(chunk) {
37 let off = 0;
38 while (off < chunk.length) {
39 const toHash = Math.min(blockSize - blockBytes, chunk.length - off);
40 blockHash.update(chunk.slice(off, off + toHash));
41 off += toHash;
42 blockBytes += toHash;
43 if (blockBytes === blockSize) {
44 blocks.push(blockHash.digest("hex"));
45 blockHash = (0, crypto_1.createHash)("sha256");
46 blockBytes = 0;
47 }
48 }
49 }
50 (0, fs_1.createReadStream)(file)
51 .on("data", it => {
52 // Note that `it` is a Buffer anyway so this cast is a no-op
53 updateBlockHash(Buffer.from(it));
54 hash.update(it);
55 })
56 .on("error", reject)
57 .on("end", () => {
58 if (blockBytes !== 0) {
59 blocks.push(blockHash.digest("hex"));
60 }
61 resolve({
62 algorithm: "SHA256",
63 hash: hash.digest("hex"),
64 blockSize,
65 blocks,
66 });
67 });
68 });
69}
70exports.hashFile = hashFile;
71function hashFileContents(contents, blockSize = 4 * 1024 * 1024) {
72 const buffer = Buffer.from(contents);
73 const hash = (0, crypto_1.createHash)("sha256");
74 hash.update(buffer);
75 const blocks = new Array();
76 for (let off = 0; off < buffer.length; off += blockSize) {
77 const blockHash = (0, crypto_1.createHash)("sha256");
78 blockHash.update(buffer.slice(off, off + blockSize));
79 blocks.push(blockHash.digest("hex"));
80 }
81 return {
82 algorithm: "SHA256",
83 hash: hash.digest("hex"),
84 blockSize,
85 blocks,
86 };
87}
88exports.hashFileContents = hashFileContents;
89//# sourceMappingURL=integrity.js.map
\No newline at end of file