basic-electron-updater
Version:
A secure, cross-platform auto-update library for Electron Forge apps using GitHub Releases.
147 lines (146 loc) • 6.13 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Downloader = void 0;
const https = __importStar(require("https"));
const fs = __importStar(require("fs"));
const crypto = __importStar(require("crypto"));
const gpg_1 = require("./validators/gpg");
/**
* Downloader handles secure asset downloads, SHA256, and GPG validation.
* Used internally by Updater.
*/
class Downloader {
/**
* Downloads an asset to the given path, with optional progress and SHA256 validation.
* @param assetUrl URL to download
* @param destPath Local file path to save
* @param onProgress Optional progress callback
* @param expectedSha256 Optional SHA256 hash to validate
* @returns Path to downloaded file
* @throws Error if download or hash validation fails
*/
async downloadAsset(assetUrl, destPath, onProgress, expectedSha256) {
return new Promise((resolve, reject) => {
const downloadFile = (url, redirectCount = 0) => {
if (redirectCount > 5) {
return reject(new Error("Too many redirects"));
}
const file = fs.createWriteStream(destPath);
https.get(url, res => {
// Handle redirects (302, 301, etc.)
if (res.statusCode === 302 || res.statusCode === 301 || res.statusCode === 307 || res.statusCode === 308) {
const redirectUrl = res.headers.location;
if (!redirectUrl) {
return reject(new Error("Redirect without location header"));
}
file.close();
return downloadFile(redirectUrl, redirectCount + 1);
}
if (res.statusCode !== 200) {
return reject(new Error(`Failed to download: ${res.statusCode}`));
}
const total = parseInt(res.headers["content-length"] || "0", 10);
let transferred = 0;
res.on("data", chunk => {
transferred += chunk.length;
if (onProgress && total) {
onProgress({
percent: (transferred / total) * 100,
transferred,
total,
});
}
});
res.pipe(file);
file.on("finish", async () => {
file.close(async () => {
if (expectedSha256) {
try {
await this.validateSha256(destPath, expectedSha256);
resolve(destPath);
}
catch (err) {
fs.unlink(destPath, () => reject(err));
}
}
else {
resolve(destPath);
}
});
});
}).on("error", err => {
file.close();
fs.unlink(destPath, () => reject(err));
});
};
downloadFile(assetUrl);
});
}
/**
* Validates a file's SHA256 hash.
* @param filePath Path to file
* @param expected Expected SHA256 hash
* @throws Error if hash does not match
*/
async validateSha256(filePath, expected) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash("sha256");
const stream = fs.createReadStream(filePath);
stream.on("data", chunk => hash.update(chunk));
stream.on("end", () => {
const digest = hash.digest("hex");
if (digest.toLowerCase() !== expected.toLowerCase()) {
reject(new Error(`SHA256 mismatch: expected ${expected}, got ${digest}`));
}
else {
resolve();
}
});
stream.on("error", reject);
});
}
/**
* Validates a file's GPG signature using a detached .sig file.
* @param filePath Path to file
* @param sigPath Path to .sig file
* @param keyringPath Optional keyring
* @throws Error if signature is invalid
*/
async validateGpg(filePath, sigPath, keyringPath) {
await (0, gpg_1.validateGpgSignature)(filePath, sigPath, keyringPath);
}
}
exports.Downloader = Downloader;