electron-updater 6.3.3 → 6.3.5
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.
- package/out/AppUpdater.js +1 -1
- package/out/AppUpdater.js.map +1 -1
- package/out/differentialDownloader/DifferentialDownloader.js +5 -1
- package/out/differentialDownloader/DifferentialDownloader.js.map +1 -1
- package/out/windowsExecutableCodeSignatureVerifier.js +3 -1
- package/out/windowsExecutableCodeSignatureVerifier.js.map +1 -1
- package/package.json +3 -3
package/out/AppUpdater.js
CHANGED
|
@@ -565,7 +565,7 @@ class AppUpdater extends events_1.EventEmitter {
|
|
|
565
565
|
const tempUpdateFile = await (0, DownloadedUpdateHelper_1.createTempUpdateFile)(`temp-${updateFileName}`, cacheDir, log);
|
|
566
566
|
try {
|
|
567
567
|
await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny);
|
|
568
|
-
await (0, fs_extra_1.rename)(tempUpdateFile, updateFile);
|
|
568
|
+
await (0, builder_util_runtime_1.retry)(() => (0, fs_extra_1.rename)(tempUpdateFile, updateFile), 60, 500, 0, 0, error => error instanceof Error && /^EBUSY:/.test(error.message));
|
|
569
569
|
}
|
|
570
570
|
catch (e) {
|
|
571
571
|
await removeFileIfAny();
|
package/out/AppUpdater.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AppUpdater.js","sourceRoot":"","sources":["../src/AppUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAY6B;AAC7B,mCAAoC;AACpC,2BAA4B;AAC5B,mCAAqC;AACrC,uCAAsE;AAEtE,qCAA8B;AAC9B,uCAA+B;AAC/B,6BAA4B;AAC5B,mCAA8K;AAE9K,qEAAuF;AACvF,6DAAyD;AACzD,iEAA2F;AAC3F,iEAA6D;AAC7D,iCAAgK;AAChK,uDAAwF;AAKxF,+BAAiC;AACjC,iCAAsC;AAEtC,0GAAsG;AActG,MAAsB,UAAW,SAAS,qBAAyD;IA0EjG;;OA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ChB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC,CAAA;YAChG,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE,CAAC;gBAClC,YAAY;gBACZ,MAAM,CAAC,CAAA;YACT,CAAC;YACD,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;CACF;AA/tBD,gCA+tBC;AAUD,SAAS,uBAAuB,CAAC,OAAe;IAC9C,MAAM,0BAA0B,GAAG,IAAA,mBAA4B,EAAC,OAAO,CAAC,CAAA;IACxE,OAAO,0BAA0B,IAAI,IAAI,IAAI,0BAA0B,CAAC,MAAM,GAAG,CAAC,CAAA;AACpF,CAAC;AAED,eAAe;AACf,MAAa,UAAU;IACrB,6DAA6D;IAC7D,IAAI,CAAC,OAAa;QAChB,SAAS;IACX,CAAC;IAED,6DAA6D;IAC7D,IAAI,CAAC,OAAa;QAChB,SAAS;IACX,CAAC;IAED,6DAA6D;IAC7D,KAAK,CAAC,OAAa;QACjB,SAAS;IACX,CAAC;CACF;AAfD,gCAeC","sourcesContent":["import {\n AllPublishOptions,\n asArray,\n CancellationToken,\n newError,\n PublishConfiguration,\n UpdateInfo,\n UUID,\n DownloadOptions,\n CancellationError,\n ProgressInfo,\n BlockMap,\n} from \"builder-util-runtime\"\nimport { randomBytes } from \"crypto\"\nimport { release } from \"os\"\nimport { EventEmitter } from \"events\"\nimport { mkdir, outputFile, readFile, rename, unlink } from \"fs-extra\"\nimport { OutgoingHttpHeaders } from \"http\"\nimport { load } from \"js-yaml\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { eq as isVersionsEqual, gt as isVersionGreaterThan, lt as isVersionLessThan, parse as parseVersion, prerelease as getVersionPreleaseComponents, SemVer } from \"semver\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { createTempUpdateFile, DownloadedUpdateHelper } from \"./DownloadedUpdateHelper\"\nimport { ElectronAppAdapter } from \"./ElectronAppAdapter\"\nimport { ElectronHttpExecutor, getNetSession, LoginCallback } from \"./electronHttpExecutor\"\nimport { GenericProvider } from \"./providers/GenericProvider\"\nimport { DOWNLOAD_PROGRESS, Logger, Provider, ResolvedUpdateFileInfo, UPDATE_DOWNLOADED, UpdateCheckResult, UpdateDownloadedEvent, UpdaterSignal } from \"./main\"\nimport { createClient, isUrlProbablySupportMultiRangeRequests } from \"./providerFactory\"\nimport { ProviderPlatform } from \"./providers/Provider\"\nimport type { TypedEmitter } from \"tiny-typed-emitter\"\nimport Session = Electron.Session\nimport type { AuthInfo } from \"electron\"\nimport { gunzipSync } from \"zlib\"\nimport { blockmapFiles } from \"./util\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { GenericDifferentialDownloader } from \"./differentialDownloader/GenericDifferentialDownloader\"\n\nexport type AppUpdaterEvents = {\n error: (error: Error, message?: string) => void\n login: (info: AuthInfo, callback: LoginCallback) => void\n \"checking-for-update\": () => void\n \"update-not-available\": (info: UpdateInfo) => void\n \"update-available\": (info: UpdateInfo) => void\n \"update-downloaded\": (event: UpdateDownloadedEvent) => void\n \"download-progress\": (info: ProgressInfo) => void\n \"update-cancelled\": (info: UpdateInfo) => void\n \"appimage-filename-updated\": (path: string) => void\n}\n\nexport abstract class AppUpdater extends (EventEmitter as new () => TypedEmitter<AppUpdaterEvents>) {\n /**\n * Whether to automatically download an update when it is found.\n */\n autoDownload = true\n\n /**\n * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).\n */\n autoInstallOnAppQuit = true\n\n /**\n * *windows-only* Whether to run the app after finish install when run the installer NOT in silent mode.\n * @default true\n */\n autoRunAppAfterInstall = true\n\n /**\n * *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.\n *\n * If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).\n */\n allowPrerelease = false\n\n /**\n * *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.\n * @default false\n */\n fullChangelog = false\n\n /**\n * Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).\n *\n * Taken in account only if channel differs (pre-release version component in terms of semantic versioning).\n *\n * @default false\n */\n allowDowngrade = false\n\n /**\n * Web installer files might not have signature verification, this switch prevents to load them unless it is needed.\n *\n * Currently false to prevent breaking the current API, but it should be changed to default true at some point that\n * breaking changes are allowed.\n *\n * @default false\n */\n disableWebInstaller = false\n\n /**\n * *NSIS only* Disable differential downloads and always perform full download of installer.\n *\n * @default false\n */\n disableDifferentialDownload = false\n\n /**\n * Allows developer to force the updater to work in \"dev\" mode, looking for \"dev-app-update.yml\" instead of \"app-update.yml\"\n * Dev: `path.join(this.app.getAppPath(), \"dev-app-update.yml\")`\n * Prod: `path.join(process.resourcesPath!, \"app-update.yml\")`\n *\n * @default false\n */\n forceDevUpdateConfig = false\n\n /**\n * The current application version.\n */\n readonly currentVersion: SemVer\n\n private _channel: string | null = null\n\n protected downloadedUpdateHelper: DownloadedUpdateHelper | null = null\n\n /**\n * Get the update channel. Doesn't return `channel` from the update configuration, only if was previously set.\n */\n get channel(): string | null {\n return this._channel\n }\n\n /**\n * Set the update channel. Overrides `channel` in the update configuration.\n *\n * `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.\n */\n set channel(value: string | null) {\n if (this._channel != null) {\n // noinspection SuspiciousTypeOfGuard\n if (typeof value !== \"string\") {\n throw newError(`Channel must be a string, but got: ${value}`, \"ERR_UPDATER_INVALID_CHANNEL\")\n } else if (value.length === 0) {\n throw newError(`Channel must be not an empty string`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n }\n\n this._channel = value\n this.allowDowngrade = true\n }\n\n /**\n * The request headers.\n */\n requestHeaders: OutgoingHttpHeaders | null = null\n\n /**\n * Shortcut for explicitly adding auth tokens to request headers\n */\n addAuthHeader(token: string) {\n this.requestHeaders = Object.assign({}, this.requestHeaders, {\n authorization: token,\n })\n }\n\n protected _logger: Logger = console\n\n // noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n get netSession(): Session {\n return getNetSession()\n }\n\n /**\n * The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.\n * Set it to `null` if you would like to disable a logging feature.\n */\n get logger(): Logger | null {\n return this._logger\n }\n\n set logger(value: Logger | null) {\n this._logger = value == null ? new NoOpLogger() : value\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`\n */\n readonly signals = new UpdaterSignal(this)\n\n private _appUpdateConfigPath: string | null = null\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * test only\n * @private\n */\n set updateConfigPath(value: string | null) {\n this.clientPromise = null\n this._appUpdateConfigPath = value\n this.configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n }\n\n private clientPromise: Promise<Provider<any>> | null = null\n\n protected readonly stagingUserIdPromise = new Lazy<string>(() => this.getOrCreateStagingUserId())\n\n // public, allow to read old config for anyone\n /** @internal */\n configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n\n private checkForUpdatesPromise: Promise<UpdateCheckResult> | null = null\n private downloadPromise: Promise<Array<string>> | null = null\n\n protected readonly app: AppAdapter\n\n protected updateInfoAndProvider: UpdateInfoAndProvider | null = null\n\n /** @internal */\n readonly httpExecutor: ElectronHttpExecutor\n\n protected constructor(options: AllPublishOptions | null | undefined, app?: AppAdapter) {\n super()\n\n this.on(\"error\", (error: Error) => {\n this._logger.error(`Error: ${error.stack || error.message}`)\n })\n\n if (app == null) {\n this.app = new ElectronAppAdapter()\n this.httpExecutor = new ElectronHttpExecutor((authInfo, callback) => this.emit(\"login\", authInfo, callback))\n } else {\n this.app = app\n this.httpExecutor = null as any\n }\n\n const currentVersionString = this.app.version\n const currentVersion = parseVersion(currentVersionString)\n if (currentVersion == null) {\n throw newError(`App version is not a valid semver version: \"${currentVersionString}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n this.currentVersion = currentVersion\n this.allowPrerelease = hasPrereleaseComponents(currentVersion)\n\n if (options != null) {\n this.setFeedURL(options)\n\n if (typeof options !== \"string\" && options.requestHeaders) {\n this.requestHeaders = options.requestHeaders\n }\n }\n }\n\n //noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n getFeedURL(): string | null | undefined {\n return \"Deprecated. Do not use it.\"\n }\n\n /**\n * Configure update provider. If value is `string`, [GenericServerOptions](/configuration/publish#genericserveroptions) will be set with value as `url`.\n * @param options If you want to override configuration in the `app-update.yml`.\n */\n setFeedURL(options: PublishConfiguration | AllPublishOptions | string) {\n const runtimeOptions = this.createProviderRuntimeOptions()\n // https://github.com/electron-userland/electron-builder/issues/1105\n let provider: Provider<any>\n if (typeof options === \"string\") {\n provider = new GenericProvider({ provider: \"generic\", url: options }, this, {\n ...runtimeOptions,\n isUseMultipleRangeRequest: isUrlProbablySupportMultiRangeRequests(options),\n })\n } else {\n provider = createClient(options, this, runtimeOptions)\n }\n this.clientPromise = Promise.resolve(provider)\n }\n\n /**\n * Asks the server whether there is an update.\n */\n checkForUpdates(): Promise<UpdateCheckResult | null> {\n if (!this.isUpdaterActive()) {\n return Promise.resolve(null)\n }\n\n let checkForUpdatesPromise = this.checkForUpdatesPromise\n if (checkForUpdatesPromise != null) {\n this._logger.info(\"Checking for update (already in progress)\")\n return checkForUpdatesPromise\n }\n\n const nullizePromise = () => (this.checkForUpdatesPromise = null)\n\n this._logger.info(\"Checking for update\")\n checkForUpdatesPromise = this.doCheckForUpdates()\n .then(it => {\n nullizePromise()\n return it\n })\n .catch((e: any) => {\n nullizePromise()\n this.emit(\"error\", e, `Cannot check for updates: ${(e.stack || e).toString()}`)\n throw e\n })\n\n this.checkForUpdatesPromise = checkForUpdatesPromise\n return checkForUpdatesPromise\n }\n\n public isUpdaterActive(): boolean {\n const isEnabled = this.app.isPackaged || this.forceDevUpdateConfig\n if (!isEnabled) {\n this._logger.info(\"Skip checkForUpdates because application is not packed and dev update config is not forced\")\n return false\n }\n return true\n }\n\n // noinspection JSUnusedGlobalSymbols\n checkForUpdatesAndNotify(downloadNotification?: DownloadNotification): Promise<UpdateCheckResult | null> {\n return this.checkForUpdates().then(it => {\n if (!it?.downloadPromise) {\n if (this._logger.debug != null) {\n this._logger.debug(\"checkForUpdatesAndNotify called, downloadPromise is null\")\n }\n return it\n }\n\n void it.downloadPromise.then(() => {\n const notificationContent = AppUpdater.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification)\n new (require(\"electron\").Notification)(notificationContent).show()\n })\n\n return it\n })\n }\n\n private static formatDownloadNotification(version: string, appName: string, downloadNotification?: DownloadNotification): DownloadNotification {\n if (downloadNotification == null) {\n downloadNotification = {\n title: \"A new update is ready to install\",\n body: `{appName} version {version} has been downloaded and will be automatically installed on exit`,\n }\n }\n downloadNotification = {\n title: downloadNotification.title.replace(\"{appName}\", appName).replace(\"{version}\", version),\n body: downloadNotification.body.replace(\"{appName}\", appName).replace(\"{version}\", version),\n }\n return downloadNotification\n }\n\n private async isStagingMatch(updateInfo: UpdateInfo): Promise<boolean> {\n const rawStagingPercentage = updateInfo.stagingPercentage\n let stagingPercentage = rawStagingPercentage\n if (stagingPercentage == null) {\n return true\n }\n\n stagingPercentage = parseInt(stagingPercentage as any, 10)\n if (isNaN(stagingPercentage)) {\n this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`)\n return true\n }\n\n // convert from user 0-100 to internal 0-1\n stagingPercentage = stagingPercentage / 100\n\n const stagingUserId = await this.stagingUserIdPromise.value\n const val = UUID.parse(stagingUserId).readUInt32BE(12)\n const percentage = val / 0xffffffff\n this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`)\n return percentage < stagingPercentage\n }\n\n private computeFinalHeaders(headers: OutgoingHttpHeaders) {\n if (this.requestHeaders != null) {\n Object.assign(headers, this.requestHeaders)\n }\n return headers\n }\n\n private async isUpdateAvailable(updateInfo: UpdateInfo): Promise<boolean> {\n const latestVersion = parseVersion(updateInfo.version)\n if (latestVersion == null) {\n throw newError(\n `This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: \"${updateInfo.version}\"`,\n \"ERR_UPDATER_INVALID_VERSION\"\n )\n }\n\n const currentVersion = this.currentVersion\n if (isVersionsEqual(latestVersion, currentVersion)) {\n return false\n }\n\n const minimumSystemVersion = updateInfo?.minimumSystemVersion\n const currentOSVersion = release()\n if (minimumSystemVersion) {\n try {\n if (isVersionLessThan(currentOSVersion, minimumSystemVersion)) {\n this._logger.info(`Current OS version ${currentOSVersion} is less than the minimum OS version required ${minimumSystemVersion} for version ${currentOSVersion}`)\n return false\n }\n } catch (e: any) {\n this._logger.warn(`Failed to compare current OS version(${currentOSVersion}) with minimum OS version(${minimumSystemVersion}): ${(e.message || e).toString()}`)\n }\n }\n\n const isStagingMatch = await this.isStagingMatch(updateInfo)\n if (!isStagingMatch) {\n return false\n }\n\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797\n const isLatestVersionNewer = isVersionGreaterThan(latestVersion, currentVersion)\n const isLatestVersionOlder = isVersionLessThan(latestVersion, currentVersion)\n\n if (isLatestVersionNewer) {\n return true\n }\n return this.allowDowngrade && isLatestVersionOlder\n }\n\n protected async getUpdateInfoAndProvider(): Promise<UpdateInfoAndProvider> {\n await this.app.whenReady()\n\n if (this.clientPromise == null) {\n this.clientPromise = this.configOnDisk.value.then(it => createClient(it, this, this.createProviderRuntimeOptions()))\n }\n\n const client = await this.clientPromise\n const stagingUserId = await this.stagingUserIdPromise.value\n client.setRequestHeaders(this.computeFinalHeaders({ \"x-user-staging-id\": stagingUserId }))\n return {\n info: await client.getLatestVersion(),\n provider: client,\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n private createProviderRuntimeOptions() {\n return {\n isUseMultipleRangeRequest: true,\n platform: this._testOnlyOptions == null ? (process.platform as ProviderPlatform) : this._testOnlyOptions.platform,\n executor: this.httpExecutor,\n }\n }\n\n private async doCheckForUpdates(): Promise<UpdateCheckResult> {\n this.emit(\"checking-for-update\")\n\n const result = await this.getUpdateInfoAndProvider()\n const updateInfo = result.info\n if (!(await this.isUpdateAvailable(updateInfo))) {\n this._logger.info(\n `Update for version ${this.currentVersion.format()} is not available (latest version: ${updateInfo.version}, downgrade is ${\n this.allowDowngrade ? \"allowed\" : \"disallowed\"\n }).`\n )\n this.emit(\"update-not-available\", updateInfo)\n return {\n versionInfo: updateInfo,\n updateInfo,\n }\n }\n\n this.updateInfoAndProvider = result\n this.onUpdateAvailable(updateInfo)\n\n const cancellationToken = new CancellationToken()\n //noinspection ES6MissingAwait\n return {\n versionInfo: updateInfo,\n updateInfo,\n cancellationToken,\n downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null,\n }\n }\n\n protected onUpdateAvailable(updateInfo: UpdateInfo): void {\n this._logger.info(\n `Found version ${updateInfo.version} (url: ${asArray(updateInfo.files)\n .map(it => it.url)\n .join(\", \")})`\n )\n this.emit(\"update-available\", updateInfo)\n }\n\n /**\n * Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.\n * @returns {Promise<Array<string>>} Paths to downloaded files.\n */\n downloadUpdate(cancellationToken: CancellationToken = new CancellationToken()): Promise<Array<string>> {\n const updateInfoAndProvider = this.updateInfoAndProvider\n if (updateInfoAndProvider == null) {\n const error = new Error(\"Please check update first\")\n this.dispatchError(error)\n return Promise.reject(error)\n }\n\n if (this.downloadPromise != null) {\n this._logger.info(\"Downloading update (already in progress)\")\n return this.downloadPromise\n }\n\n this._logger.info(\n `Downloading update from ${asArray(updateInfoAndProvider.info.files)\n .map(it => it.url)\n .join(\", \")}`\n )\n const errorHandler = (e: Error): Error => {\n // https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159\n if (!(e instanceof CancellationError)) {\n try {\n this.dispatchError(e)\n } catch (nestedError: any) {\n this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`)\n }\n }\n\n return e\n }\n\n this.downloadPromise = this.doDownloadUpdate({\n updateInfoAndProvider,\n requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider),\n cancellationToken,\n disableWebInstaller: this.disableWebInstaller,\n disableDifferentialDownload: this.disableDifferentialDownload,\n })\n .catch((e: any) => {\n throw errorHandler(e)\n })\n .finally(() => {\n this.downloadPromise = null\n })\n\n return this.downloadPromise\n }\n\n protected dispatchError(e: Error): void {\n this.emit(\"error\", e, (e.stack || e).toString())\n }\n\n protected dispatchUpdateDownloaded(event: UpdateDownloadedEvent): void {\n this.emit(UPDATE_DOWNLOADED, event)\n }\n\n protected abstract doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>\n\n /**\n * Restarts the app and installs the update after it has been downloaded.\n * It should only be called after `update-downloaded` has been emitted.\n *\n * **Note:** `autoUpdater.quitAndInstall()` will close all application windows first and only emit `before-quit` event on `app` after that.\n * This is different from the normal quit event sequence.\n *\n * @param isSilent *windows-only* Runs the installer in silent mode. Defaults to `false`.\n * @param isForceRunAfter Run the app after finish even on silent install. Not applicable for macOS.\n * Ignored if `isSilent` is set to `false`(In this case you can still set `autoRunAppAfterInstall` to `false` to prevent run the app after finish).\n */\n abstract quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void\n\n private async loadUpdateConfig(): Promise<any> {\n if (this._appUpdateConfigPath == null) {\n this._appUpdateConfigPath = this.app.appUpdateConfigPath\n }\n return load(await readFile(this._appUpdateConfigPath, \"utf-8\"))\n }\n\n private computeRequestHeaders(provider: Provider<any>): OutgoingHttpHeaders {\n const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders\n if (fileExtraDownloadHeaders != null) {\n const requestHeaders = this.requestHeaders\n return requestHeaders == null\n ? fileExtraDownloadHeaders\n : {\n ...fileExtraDownloadHeaders,\n ...requestHeaders,\n }\n }\n return this.computeFinalHeaders({ accept: \"*/*\" })\n }\n\n private async getOrCreateStagingUserId(): Promise<string> {\n const file = path.join(this.app.userDataPath, \".updaterId\")\n try {\n const id = await readFile(file, \"utf-8\")\n if (UUID.check(id)) {\n return id\n } else {\n this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`)\n }\n } catch (e: any) {\n if (e.code !== \"ENOENT\") {\n this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`)\n }\n }\n\n const id = UUID.v5(randomBytes(4096), UUID.OID)\n this._logger.info(`Generated new staging user ID: ${id}`)\n try {\n await outputFile(file, id)\n } catch (e: any) {\n this._logger.warn(`Couldn't write out staging user ID: ${e}`)\n }\n return id\n }\n\n /** @internal */\n get isAddNoCacheQuery(): boolean {\n const headers = this.requestHeaders\n // https://github.com/electron-userland/electron-builder/issues/3021\n if (headers == null) {\n return true\n }\n\n for (const headerName of Object.keys(headers)) {\n const s = headerName.toLowerCase()\n if (s === \"authorization\" || s === \"private-token\") {\n return false\n }\n }\n return true\n }\n\n /**\n * @private\n * @internal\n */\n _testOnlyOptions: TestOnlyUpdaterOptions | null = null\n\n private async getOrCreateDownloadHelper(): Promise<DownloadedUpdateHelper> {\n let result = this.downloadedUpdateHelper\n if (result == null) {\n const dirName = (await this.configOnDisk.value).updaterCacheDirName\n const logger = this._logger\n if (dirName == null) {\n logger.error(\"updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?\")\n }\n const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name)\n if (logger.debug != null) {\n logger.debug(`updater cache dir: ${cacheDir}`)\n }\n\n result = new DownloadedUpdateHelper(cacheDir)\n this.downloadedUpdateHelper = result\n }\n return result\n }\n\n protected async executeDownload(taskOptions: DownloadExecutorTask): Promise<Array<string>> {\n const fileInfo = taskOptions.fileInfo\n const downloadOptions: DownloadOptions = {\n headers: taskOptions.downloadUpdateOptions.requestHeaders,\n cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,\n sha2: (fileInfo.info as any).sha2,\n sha512: fileInfo.info.sha512,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info\n const version = updateInfo.version\n const packageInfo = fileInfo.packageInfo\n\n function getCacheUpdateFileName(): string {\n // NodeJS URL doesn't decode automatically\n const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname)\n if (urlPath.endsWith(`.${taskOptions.fileExtension}`)) {\n return path.basename(urlPath)\n } else {\n // url like /latest, generate name\n return taskOptions.fileInfo.info.url\n }\n }\n\n const downloadedUpdateHelper = await this.getOrCreateDownloadHelper()\n const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate\n await mkdir(cacheDir, { recursive: true })\n const updateFileName = getCacheUpdateFileName()\n let updateFile = path.join(cacheDir, updateFileName)\n const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || \".7z\"}`)\n\n const done = async (isSaveCache: boolean) => {\n await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache)\n await taskOptions.done!({\n ...updateInfo,\n downloadedFile: updateFile,\n })\n return packageFile == null ? [updateFile] : [updateFile, packageFile]\n }\n\n const log = this._logger\n const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log)\n if (cachedUpdateFile != null) {\n updateFile = cachedUpdateFile\n return await done(false)\n }\n\n const removeFileIfAny = async () => {\n await downloadedUpdateHelper.clear().catch(() => {\n // ignore\n })\n return await unlink(updateFile).catch(() => {\n // ignore\n })\n }\n\n const tempUpdateFile = await createTempUpdateFile(`temp-${updateFileName}`, cacheDir, log)\n try {\n await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny)\n await rename(tempUpdateFile, updateFile)\n } catch (e: any) {\n await removeFileIfAny()\n\n if (e instanceof CancellationError) {\n log.info(\"cancelled\")\n this.emit(\"update-cancelled\", updateInfo)\n }\n throw e\n }\n\n log.info(`New version ${version} has been downloaded to ${updateFile}`)\n return await done(true)\n }\n protected async differentialDownloadInstaller(\n fileInfo: ResolvedUpdateFileInfo,\n downloadUpdateOptions: DownloadUpdateOptions,\n installerPath: string,\n provider: Provider<any>,\n oldInstallerFileName: string\n ): Promise<boolean> {\n try {\n if (this._testOnlyOptions != null && !this._testOnlyOptions.isUseDifferentialDownload) {\n return true\n }\n const blockmapFileUrls = blockmapFiles(fileInfo.url, this.app.version, downloadUpdateOptions.updateInfoAndProvider.info.version)\n this._logger.info(`Download block maps (old: \"${blockmapFileUrls[0]}\", new: ${blockmapFileUrls[1]})`)\n\n const downloadBlockMap = async (url: URL): Promise<BlockMap> => {\n const data = await this.httpExecutor.downloadToBuffer(url, {\n headers: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n })\n\n if (data == null || data.length === 0) {\n throw new Error(`Blockmap \"${url.href}\" is empty`)\n }\n\n try {\n return JSON.parse(gunzipSync(data).toString())\n } catch (e: any) {\n throw new Error(`Cannot parse blockmap \"${url.href}\", error: ${e}`)\n }\n }\n\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: fileInfo.url,\n oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, oldInstallerFileName),\n logger: this._logger,\n newFile: installerPath,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n requestHeaders: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const blockMapDataList = await Promise.all(blockmapFileUrls.map(u => downloadBlockMap(u)))\n await new GenericDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download(blockMapDataList[0], blockMapDataList[1])\n return false\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n if (this._testOnlyOptions != null) {\n // test mode\n throw e\n }\n return true\n }\n }\n}\n\nexport interface DownloadUpdateOptions {\n readonly updateInfoAndProvider: UpdateInfoAndProvider\n readonly requestHeaders: OutgoingHttpHeaders\n readonly cancellationToken: CancellationToken\n readonly disableWebInstaller?: boolean\n readonly disableDifferentialDownload?: boolean\n}\n\nfunction hasPrereleaseComponents(version: SemVer) {\n const versionPrereleaseComponent = getVersionPreleaseComponents(version)\n return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0\n}\n\n/** @private */\nexport class NoOpLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n warn(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(message?: any) {\n // ignore\n }\n}\n\nexport interface UpdateInfoAndProvider {\n info: UpdateInfo\n provider: Provider<any>\n}\n\nexport interface DownloadExecutorTask {\n readonly fileExtension: string\n readonly fileInfo: ResolvedUpdateFileInfo\n readonly downloadUpdateOptions: DownloadUpdateOptions\n readonly task: (destinationFile: string, downloadOptions: DownloadOptions, packageFile: string | null, removeTempDirIfAny: () => Promise<any>) => Promise<any>\n\n readonly done?: (event: UpdateDownloadedEvent) => Promise<any>\n}\n\nexport interface DownloadNotification {\n body: string\n title: string\n}\n\n/** @private */\nexport interface TestOnlyUpdaterOptions {\n platform: ProviderPlatform\n\n isUseDifferentialDownload?: boolean\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AppUpdater.js","sourceRoot":"","sources":["../src/AppUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAa6B;AAC7B,mCAAoC;AACpC,2BAA4B;AAC5B,mCAAqC;AACrC,uCAAsE;AAEtE,qCAA8B;AAC9B,uCAA+B;AAC/B,6BAA4B;AAC5B,mC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AAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YAC1F,MAAM,IAAI,6DAA6B,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,eAAe,CAAC,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAA;YAC7I,OAAO,KAAK,CAAA;QACd,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC,CAAA;YAChG,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE,CAAC;gBAClC,YAAY;gBACZ,MAAM,CAAC,CAAA;YACT,CAAC;YACD,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;CACF;AAtuBD,gCAsuBC;AAUD,SAAS,uBAAuB,CAAC,OAAe;IAC9C,MAAM,0BAA0B,GAAG,IAAA,mBAA4B,EAAC,OAAO,CAAC,CAAA;IACxE,OAAO,0BAA0B,IAAI,IAAI,IAAI,0BAA0B,CAAC,MAAM,GAAG,CAAC,CAAA;AACpF,CAAC;AAED,eAAe;AACf,MAAa,UAAU;IACrB,6DAA6D;IAC7D,IAAI,CAAC,OAAa;QAChB,SAAS;IACX,CAAC;IAED,6DAA6D;IAC7D,IAAI,CAAC,OAAa;QAChB,SAAS;IACX,CAAC;IAED,6DAA6D;IAC7D,KAAK,CAAC,OAAa;QACjB,SAAS;IACX,CAAC;CACF;AAfD,gCAeC","sourcesContent":["import {\n AllPublishOptions,\n asArray,\n CancellationToken,\n newError,\n PublishConfiguration,\n UpdateInfo,\n UUID,\n DownloadOptions,\n CancellationError,\n ProgressInfo,\n BlockMap,\n retry,\n} from \"builder-util-runtime\"\nimport { randomBytes } from \"crypto\"\nimport { release } from \"os\"\nimport { EventEmitter } from \"events\"\nimport { mkdir, outputFile, readFile, rename, unlink } from \"fs-extra\"\nimport { OutgoingHttpHeaders } from \"http\"\nimport { load } from \"js-yaml\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { eq as isVersionsEqual, gt as isVersionGreaterThan, lt as isVersionLessThan, parse as parseVersion, prerelease as getVersionPreleaseComponents, SemVer } from \"semver\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { createTempUpdateFile, DownloadedUpdateHelper } from \"./DownloadedUpdateHelper\"\nimport { ElectronAppAdapter } from \"./ElectronAppAdapter\"\nimport { ElectronHttpExecutor, getNetSession, LoginCallback } from \"./electronHttpExecutor\"\nimport { GenericProvider } from \"./providers/GenericProvider\"\nimport { DOWNLOAD_PROGRESS, Logger, Provider, ResolvedUpdateFileInfo, UPDATE_DOWNLOADED, UpdateCheckResult, UpdateDownloadedEvent, UpdaterSignal } from \"./main\"\nimport { createClient, isUrlProbablySupportMultiRangeRequests } from \"./providerFactory\"\nimport { ProviderPlatform } from \"./providers/Provider\"\nimport type { TypedEmitter } from \"tiny-typed-emitter\"\nimport Session = Electron.Session\nimport type { AuthInfo } from \"electron\"\nimport { gunzipSync } from \"zlib\"\nimport { blockmapFiles } from \"./util\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { GenericDifferentialDownloader } from \"./differentialDownloader/GenericDifferentialDownloader\"\n\nexport type AppUpdaterEvents = {\n error: (error: Error, message?: string) => void\n login: (info: AuthInfo, callback: LoginCallback) => void\n \"checking-for-update\": () => void\n \"update-not-available\": (info: UpdateInfo) => void\n \"update-available\": (info: UpdateInfo) => void\n \"update-downloaded\": (event: UpdateDownloadedEvent) => void\n \"download-progress\": (info: ProgressInfo) => void\n \"update-cancelled\": (info: UpdateInfo) => void\n \"appimage-filename-updated\": (path: string) => void\n}\n\nexport abstract class AppUpdater extends (EventEmitter as new () => TypedEmitter<AppUpdaterEvents>) {\n /**\n * Whether to automatically download an update when it is found.\n */\n autoDownload = true\n\n /**\n * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).\n */\n autoInstallOnAppQuit = true\n\n /**\n * *windows-only* Whether to run the app after finish install when run the installer NOT in silent mode.\n * @default true\n */\n autoRunAppAfterInstall = true\n\n /**\n * *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.\n *\n * If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).\n */\n allowPrerelease = false\n\n /**\n * *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.\n * @default false\n */\n fullChangelog = false\n\n /**\n * Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).\n *\n * Taken in account only if channel differs (pre-release version component in terms of semantic versioning).\n *\n * @default false\n */\n allowDowngrade = false\n\n /**\n * Web installer files might not have signature verification, this switch prevents to load them unless it is needed.\n *\n * Currently false to prevent breaking the current API, but it should be changed to default true at some point that\n * breaking changes are allowed.\n *\n * @default false\n */\n disableWebInstaller = false\n\n /**\n * *NSIS only* Disable differential downloads and always perform full download of installer.\n *\n * @default false\n */\n disableDifferentialDownload = false\n\n /**\n * Allows developer to force the updater to work in \"dev\" mode, looking for \"dev-app-update.yml\" instead of \"app-update.yml\"\n * Dev: `path.join(this.app.getAppPath(), \"dev-app-update.yml\")`\n * Prod: `path.join(process.resourcesPath!, \"app-update.yml\")`\n *\n * @default false\n */\n forceDevUpdateConfig = false\n\n /**\n * The current application version.\n */\n readonly currentVersion: SemVer\n\n private _channel: string | null = null\n\n protected downloadedUpdateHelper: DownloadedUpdateHelper | null = null\n\n /**\n * Get the update channel. Doesn't return `channel` from the update configuration, only if was previously set.\n */\n get channel(): string | null {\n return this._channel\n }\n\n /**\n * Set the update channel. Overrides `channel` in the update configuration.\n *\n * `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.\n */\n set channel(value: string | null) {\n if (this._channel != null) {\n // noinspection SuspiciousTypeOfGuard\n if (typeof value !== \"string\") {\n throw newError(`Channel must be a string, but got: ${value}`, \"ERR_UPDATER_INVALID_CHANNEL\")\n } else if (value.length === 0) {\n throw newError(`Channel must be not an empty string`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n }\n\n this._channel = value\n this.allowDowngrade = true\n }\n\n /**\n * The request headers.\n */\n requestHeaders: OutgoingHttpHeaders | null = null\n\n /**\n * Shortcut for explicitly adding auth tokens to request headers\n */\n addAuthHeader(token: string) {\n this.requestHeaders = Object.assign({}, this.requestHeaders, {\n authorization: token,\n })\n }\n\n protected _logger: Logger = console\n\n // noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n get netSession(): Session {\n return getNetSession()\n }\n\n /**\n * The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.\n * Set it to `null` if you would like to disable a logging feature.\n */\n get logger(): Logger | null {\n return this._logger\n }\n\n set logger(value: Logger | null) {\n this._logger = value == null ? new NoOpLogger() : value\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`\n */\n readonly signals = new UpdaterSignal(this)\n\n private _appUpdateConfigPath: string | null = null\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * test only\n * @private\n */\n set updateConfigPath(value: string | null) {\n this.clientPromise = null\n this._appUpdateConfigPath = value\n this.configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n }\n\n private clientPromise: Promise<Provider<any>> | null = null\n\n protected readonly stagingUserIdPromise = new Lazy<string>(() => this.getOrCreateStagingUserId())\n\n // public, allow to read old config for anyone\n /** @internal */\n configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n\n private checkForUpdatesPromise: Promise<UpdateCheckResult> | null = null\n private downloadPromise: Promise<Array<string>> | null = null\n\n protected readonly app: AppAdapter\n\n protected updateInfoAndProvider: UpdateInfoAndProvider | null = null\n\n /** @internal */\n readonly httpExecutor: ElectronHttpExecutor\n\n protected constructor(options: AllPublishOptions | null | undefined, app?: AppAdapter) {\n super()\n\n this.on(\"error\", (error: Error) => {\n this._logger.error(`Error: ${error.stack || error.message}`)\n })\n\n if (app == null) {\n this.app = new ElectronAppAdapter()\n this.httpExecutor = new ElectronHttpExecutor((authInfo, callback) => this.emit(\"login\", authInfo, callback))\n } else {\n this.app = app\n this.httpExecutor = null as any\n }\n\n const currentVersionString = this.app.version\n const currentVersion = parseVersion(currentVersionString)\n if (currentVersion == null) {\n throw newError(`App version is not a valid semver version: \"${currentVersionString}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n this.currentVersion = currentVersion\n this.allowPrerelease = hasPrereleaseComponents(currentVersion)\n\n if (options != null) {\n this.setFeedURL(options)\n\n if (typeof options !== \"string\" && options.requestHeaders) {\n this.requestHeaders = options.requestHeaders\n }\n }\n }\n\n //noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n getFeedURL(): string | null | undefined {\n return \"Deprecated. Do not use it.\"\n }\n\n /**\n * Configure update provider. If value is `string`, [GenericServerOptions](/configuration/publish#genericserveroptions) will be set with value as `url`.\n * @param options If you want to override configuration in the `app-update.yml`.\n */\n setFeedURL(options: PublishConfiguration | AllPublishOptions | string) {\n const runtimeOptions = this.createProviderRuntimeOptions()\n // https://github.com/electron-userland/electron-builder/issues/1105\n let provider: Provider<any>\n if (typeof options === \"string\") {\n provider = new GenericProvider({ provider: \"generic\", url: options }, this, {\n ...runtimeOptions,\n isUseMultipleRangeRequest: isUrlProbablySupportMultiRangeRequests(options),\n })\n } else {\n provider = createClient(options, this, runtimeOptions)\n }\n this.clientPromise = Promise.resolve(provider)\n }\n\n /**\n * Asks the server whether there is an update.\n */\n checkForUpdates(): Promise<UpdateCheckResult | null> {\n if (!this.isUpdaterActive()) {\n return Promise.resolve(null)\n }\n\n let checkForUpdatesPromise = this.checkForUpdatesPromise\n if (checkForUpdatesPromise != null) {\n this._logger.info(\"Checking for update (already in progress)\")\n return checkForUpdatesPromise\n }\n\n const nullizePromise = () => (this.checkForUpdatesPromise = null)\n\n this._logger.info(\"Checking for update\")\n checkForUpdatesPromise = this.doCheckForUpdates()\n .then(it => {\n nullizePromise()\n return it\n })\n .catch((e: any) => {\n nullizePromise()\n this.emit(\"error\", e, `Cannot check for updates: ${(e.stack || e).toString()}`)\n throw e\n })\n\n this.checkForUpdatesPromise = checkForUpdatesPromise\n return checkForUpdatesPromise\n }\n\n public isUpdaterActive(): boolean {\n const isEnabled = this.app.isPackaged || this.forceDevUpdateConfig\n if (!isEnabled) {\n this._logger.info(\"Skip checkForUpdates because application is not packed and dev update config is not forced\")\n return false\n }\n return true\n }\n\n // noinspection JSUnusedGlobalSymbols\n checkForUpdatesAndNotify(downloadNotification?: DownloadNotification): Promise<UpdateCheckResult | null> {\n return this.checkForUpdates().then(it => {\n if (!it?.downloadPromise) {\n if (this._logger.debug != null) {\n this._logger.debug(\"checkForUpdatesAndNotify called, downloadPromise is null\")\n }\n return it\n }\n\n void it.downloadPromise.then(() => {\n const notificationContent = AppUpdater.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification)\n new (require(\"electron\").Notification)(notificationContent).show()\n })\n\n return it\n })\n }\n\n private static formatDownloadNotification(version: string, appName: string, downloadNotification?: DownloadNotification): DownloadNotification {\n if (downloadNotification == null) {\n downloadNotification = {\n title: \"A new update is ready to install\",\n body: `{appName} version {version} has been downloaded and will be automatically installed on exit`,\n }\n }\n downloadNotification = {\n title: downloadNotification.title.replace(\"{appName}\", appName).replace(\"{version}\", version),\n body: downloadNotification.body.replace(\"{appName}\", appName).replace(\"{version}\", version),\n }\n return downloadNotification\n }\n\n private async isStagingMatch(updateInfo: UpdateInfo): Promise<boolean> {\n const rawStagingPercentage = updateInfo.stagingPercentage\n let stagingPercentage = rawStagingPercentage\n if (stagingPercentage == null) {\n return true\n }\n\n stagingPercentage = parseInt(stagingPercentage as any, 10)\n if (isNaN(stagingPercentage)) {\n this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`)\n return true\n }\n\n // convert from user 0-100 to internal 0-1\n stagingPercentage = stagingPercentage / 100\n\n const stagingUserId = await this.stagingUserIdPromise.value\n const val = UUID.parse(stagingUserId).readUInt32BE(12)\n const percentage = val / 0xffffffff\n this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`)\n return percentage < stagingPercentage\n }\n\n private computeFinalHeaders(headers: OutgoingHttpHeaders) {\n if (this.requestHeaders != null) {\n Object.assign(headers, this.requestHeaders)\n }\n return headers\n }\n\n private async isUpdateAvailable(updateInfo: UpdateInfo): Promise<boolean> {\n const latestVersion = parseVersion(updateInfo.version)\n if (latestVersion == null) {\n throw newError(\n `This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: \"${updateInfo.version}\"`,\n \"ERR_UPDATER_INVALID_VERSION\"\n )\n }\n\n const currentVersion = this.currentVersion\n if (isVersionsEqual(latestVersion, currentVersion)) {\n return false\n }\n\n const minimumSystemVersion = updateInfo?.minimumSystemVersion\n const currentOSVersion = release()\n if (minimumSystemVersion) {\n try {\n if (isVersionLessThan(currentOSVersion, minimumSystemVersion)) {\n this._logger.info(`Current OS version ${currentOSVersion} is less than the minimum OS version required ${minimumSystemVersion} for version ${currentOSVersion}`)\n return false\n }\n } catch (e: any) {\n this._logger.warn(`Failed to compare current OS version(${currentOSVersion}) with minimum OS version(${minimumSystemVersion}): ${(e.message || e).toString()}`)\n }\n }\n\n const isStagingMatch = await this.isStagingMatch(updateInfo)\n if (!isStagingMatch) {\n return false\n }\n\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797\n const isLatestVersionNewer = isVersionGreaterThan(latestVersion, currentVersion)\n const isLatestVersionOlder = isVersionLessThan(latestVersion, currentVersion)\n\n if (isLatestVersionNewer) {\n return true\n }\n return this.allowDowngrade && isLatestVersionOlder\n }\n\n protected async getUpdateInfoAndProvider(): Promise<UpdateInfoAndProvider> {\n await this.app.whenReady()\n\n if (this.clientPromise == null) {\n this.clientPromise = this.configOnDisk.value.then(it => createClient(it, this, this.createProviderRuntimeOptions()))\n }\n\n const client = await this.clientPromise\n const stagingUserId = await this.stagingUserIdPromise.value\n client.setRequestHeaders(this.computeFinalHeaders({ \"x-user-staging-id\": stagingUserId }))\n return {\n info: await client.getLatestVersion(),\n provider: client,\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n private createProviderRuntimeOptions() {\n return {\n isUseMultipleRangeRequest: true,\n platform: this._testOnlyOptions == null ? (process.platform as ProviderPlatform) : this._testOnlyOptions.platform,\n executor: this.httpExecutor,\n }\n }\n\n private async doCheckForUpdates(): Promise<UpdateCheckResult> {\n this.emit(\"checking-for-update\")\n\n const result = await this.getUpdateInfoAndProvider()\n const updateInfo = result.info\n if (!(await this.isUpdateAvailable(updateInfo))) {\n this._logger.info(\n `Update for version ${this.currentVersion.format()} is not available (latest version: ${updateInfo.version}, downgrade is ${\n this.allowDowngrade ? \"allowed\" : \"disallowed\"\n }).`\n )\n this.emit(\"update-not-available\", updateInfo)\n return {\n versionInfo: updateInfo,\n updateInfo,\n }\n }\n\n this.updateInfoAndProvider = result\n this.onUpdateAvailable(updateInfo)\n\n const cancellationToken = new CancellationToken()\n //noinspection ES6MissingAwait\n return {\n versionInfo: updateInfo,\n updateInfo,\n cancellationToken,\n downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null,\n }\n }\n\n protected onUpdateAvailable(updateInfo: UpdateInfo): void {\n this._logger.info(\n `Found version ${updateInfo.version} (url: ${asArray(updateInfo.files)\n .map(it => it.url)\n .join(\", \")})`\n )\n this.emit(\"update-available\", updateInfo)\n }\n\n /**\n * Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.\n * @returns {Promise<Array<string>>} Paths to downloaded files.\n */\n downloadUpdate(cancellationToken: CancellationToken = new CancellationToken()): Promise<Array<string>> {\n const updateInfoAndProvider = this.updateInfoAndProvider\n if (updateInfoAndProvider == null) {\n const error = new Error(\"Please check update first\")\n this.dispatchError(error)\n return Promise.reject(error)\n }\n\n if (this.downloadPromise != null) {\n this._logger.info(\"Downloading update (already in progress)\")\n return this.downloadPromise\n }\n\n this._logger.info(\n `Downloading update from ${asArray(updateInfoAndProvider.info.files)\n .map(it => it.url)\n .join(\", \")}`\n )\n const errorHandler = (e: Error): Error => {\n // https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159\n if (!(e instanceof CancellationError)) {\n try {\n this.dispatchError(e)\n } catch (nestedError: any) {\n this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`)\n }\n }\n\n return e\n }\n\n this.downloadPromise = this.doDownloadUpdate({\n updateInfoAndProvider,\n requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider),\n cancellationToken,\n disableWebInstaller: this.disableWebInstaller,\n disableDifferentialDownload: this.disableDifferentialDownload,\n })\n .catch((e: any) => {\n throw errorHandler(e)\n })\n .finally(() => {\n this.downloadPromise = null\n })\n\n return this.downloadPromise\n }\n\n protected dispatchError(e: Error): void {\n this.emit(\"error\", e, (e.stack || e).toString())\n }\n\n protected dispatchUpdateDownloaded(event: UpdateDownloadedEvent): void {\n this.emit(UPDATE_DOWNLOADED, event)\n }\n\n protected abstract doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>\n\n /**\n * Restarts the app and installs the update after it has been downloaded.\n * It should only be called after `update-downloaded` has been emitted.\n *\n * **Note:** `autoUpdater.quitAndInstall()` will close all application windows first and only emit `before-quit` event on `app` after that.\n * This is different from the normal quit event sequence.\n *\n * @param isSilent *windows-only* Runs the installer in silent mode. Defaults to `false`.\n * @param isForceRunAfter Run the app after finish even on silent install. Not applicable for macOS.\n * Ignored if `isSilent` is set to `false`(In this case you can still set `autoRunAppAfterInstall` to `false` to prevent run the app after finish).\n */\n abstract quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void\n\n private async loadUpdateConfig(): Promise<any> {\n if (this._appUpdateConfigPath == null) {\n this._appUpdateConfigPath = this.app.appUpdateConfigPath\n }\n return load(await readFile(this._appUpdateConfigPath, \"utf-8\"))\n }\n\n private computeRequestHeaders(provider: Provider<any>): OutgoingHttpHeaders {\n const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders\n if (fileExtraDownloadHeaders != null) {\n const requestHeaders = this.requestHeaders\n return requestHeaders == null\n ? fileExtraDownloadHeaders\n : {\n ...fileExtraDownloadHeaders,\n ...requestHeaders,\n }\n }\n return this.computeFinalHeaders({ accept: \"*/*\" })\n }\n\n private async getOrCreateStagingUserId(): Promise<string> {\n const file = path.join(this.app.userDataPath, \".updaterId\")\n try {\n const id = await readFile(file, \"utf-8\")\n if (UUID.check(id)) {\n return id\n } else {\n this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`)\n }\n } catch (e: any) {\n if (e.code !== \"ENOENT\") {\n this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`)\n }\n }\n\n const id = UUID.v5(randomBytes(4096), UUID.OID)\n this._logger.info(`Generated new staging user ID: ${id}`)\n try {\n await outputFile(file, id)\n } catch (e: any) {\n this._logger.warn(`Couldn't write out staging user ID: ${e}`)\n }\n return id\n }\n\n /** @internal */\n get isAddNoCacheQuery(): boolean {\n const headers = this.requestHeaders\n // https://github.com/electron-userland/electron-builder/issues/3021\n if (headers == null) {\n return true\n }\n\n for (const headerName of Object.keys(headers)) {\n const s = headerName.toLowerCase()\n if (s === \"authorization\" || s === \"private-token\") {\n return false\n }\n }\n return true\n }\n\n /**\n * @private\n * @internal\n */\n _testOnlyOptions: TestOnlyUpdaterOptions | null = null\n\n private async getOrCreateDownloadHelper(): Promise<DownloadedUpdateHelper> {\n let result = this.downloadedUpdateHelper\n if (result == null) {\n const dirName = (await this.configOnDisk.value).updaterCacheDirName\n const logger = this._logger\n if (dirName == null) {\n logger.error(\"updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?\")\n }\n const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name)\n if (logger.debug != null) {\n logger.debug(`updater cache dir: ${cacheDir}`)\n }\n\n result = new DownloadedUpdateHelper(cacheDir)\n this.downloadedUpdateHelper = result\n }\n return result\n }\n\n protected async executeDownload(taskOptions: DownloadExecutorTask): Promise<Array<string>> {\n const fileInfo = taskOptions.fileInfo\n const downloadOptions: DownloadOptions = {\n headers: taskOptions.downloadUpdateOptions.requestHeaders,\n cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,\n sha2: (fileInfo.info as any).sha2,\n sha512: fileInfo.info.sha512,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info\n const version = updateInfo.version\n const packageInfo = fileInfo.packageInfo\n\n function getCacheUpdateFileName(): string {\n // NodeJS URL doesn't decode automatically\n const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname)\n if (urlPath.endsWith(`.${taskOptions.fileExtension}`)) {\n return path.basename(urlPath)\n } else {\n // url like /latest, generate name\n return taskOptions.fileInfo.info.url\n }\n }\n\n const downloadedUpdateHelper = await this.getOrCreateDownloadHelper()\n const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate\n await mkdir(cacheDir, { recursive: true })\n const updateFileName = getCacheUpdateFileName()\n let updateFile = path.join(cacheDir, updateFileName)\n const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || \".7z\"}`)\n\n const done = async (isSaveCache: boolean) => {\n await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache)\n await taskOptions.done!({\n ...updateInfo,\n downloadedFile: updateFile,\n })\n return packageFile == null ? [updateFile] : [updateFile, packageFile]\n }\n\n const log = this._logger\n const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log)\n if (cachedUpdateFile != null) {\n updateFile = cachedUpdateFile\n return await done(false)\n }\n\n const removeFileIfAny = async () => {\n await downloadedUpdateHelper.clear().catch(() => {\n // ignore\n })\n return await unlink(updateFile).catch(() => {\n // ignore\n })\n }\n\n const tempUpdateFile = await createTempUpdateFile(`temp-${updateFileName}`, cacheDir, log)\n try {\n await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny)\n await retry(\n () => rename(tempUpdateFile, updateFile),\n 60,\n 500,\n 0,\n 0,\n error => error instanceof Error && /^EBUSY:/.test(error.message)\n )\n } catch (e: any) {\n await removeFileIfAny()\n\n if (e instanceof CancellationError) {\n log.info(\"cancelled\")\n this.emit(\"update-cancelled\", updateInfo)\n }\n throw e\n }\n\n log.info(`New version ${version} has been downloaded to ${updateFile}`)\n return await done(true)\n }\n protected async differentialDownloadInstaller(\n fileInfo: ResolvedUpdateFileInfo,\n downloadUpdateOptions: DownloadUpdateOptions,\n installerPath: string,\n provider: Provider<any>,\n oldInstallerFileName: string\n ): Promise<boolean> {\n try {\n if (this._testOnlyOptions != null && !this._testOnlyOptions.isUseDifferentialDownload) {\n return true\n }\n const blockmapFileUrls = blockmapFiles(fileInfo.url, this.app.version, downloadUpdateOptions.updateInfoAndProvider.info.version)\n this._logger.info(`Download block maps (old: \"${blockmapFileUrls[0]}\", new: ${blockmapFileUrls[1]})`)\n\n const downloadBlockMap = async (url: URL): Promise<BlockMap> => {\n const data = await this.httpExecutor.downloadToBuffer(url, {\n headers: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n })\n\n if (data == null || data.length === 0) {\n throw new Error(`Blockmap \"${url.href}\" is empty`)\n }\n\n try {\n return JSON.parse(gunzipSync(data).toString())\n } catch (e: any) {\n throw new Error(`Cannot parse blockmap \"${url.href}\", error: ${e}`)\n }\n }\n\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: fileInfo.url,\n oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, oldInstallerFileName),\n logger: this._logger,\n newFile: installerPath,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n requestHeaders: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const blockMapDataList = await Promise.all(blockmapFileUrls.map(u => downloadBlockMap(u)))\n await new GenericDifferentialDownloader(fileInfo.info, this.httpExecutor, downloadOptions).download(blockMapDataList[0], blockMapDataList[1])\n return false\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n if (this._testOnlyOptions != null) {\n // test mode\n throw e\n }\n return true\n }\n }\n}\n\nexport interface DownloadUpdateOptions {\n readonly updateInfoAndProvider: UpdateInfoAndProvider\n readonly requestHeaders: OutgoingHttpHeaders\n readonly cancellationToken: CancellationToken\n readonly disableWebInstaller?: boolean\n readonly disableDifferentialDownload?: boolean\n}\n\nfunction hasPrereleaseComponents(version: SemVer) {\n const versionPrereleaseComponent = getVersionPreleaseComponents(version)\n return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0\n}\n\n/** @private */\nexport class NoOpLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n warn(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(message?: any) {\n // ignore\n }\n}\n\nexport interface UpdateInfoAndProvider {\n info: UpdateInfo\n provider: Provider<any>\n}\n\nexport interface DownloadExecutorTask {\n readonly fileExtension: string\n readonly fileInfo: ResolvedUpdateFileInfo\n readonly downloadUpdateOptions: DownloadUpdateOptions\n readonly task: (destinationFile: string, downloadOptions: DownloadOptions, packageFile: string | null, removeTempDirIfAny: () => Promise<any>) => Promise<any>\n\n readonly done?: (event: UpdateDownloadedEvent) => Promise<any>\n}\n\nexport interface DownloadNotification {\n body: string\n title: string\n}\n\n/** @private */\nexport interface TestOnlyUpdaterOptions {\n platform: ProviderPlatform\n\n isUseDifferentialDownload?: boolean\n}\n"]}
|
|
@@ -189,7 +189,7 @@ class DifferentialDownloader {
|
|
|
189
189
|
}
|
|
190
190
|
const request = this.httpExecutor.createRequest(requestOptions, response => {
|
|
191
191
|
response.on("error", reject);
|
|
192
|
-
response.on("
|
|
192
|
+
response.on("aborted", () => {
|
|
193
193
|
reject(new Error("response has been aborted by the server"));
|
|
194
194
|
});
|
|
195
195
|
// Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
|
|
@@ -245,6 +245,10 @@ class DifferentialDownloader {
|
|
|
245
245
|
if (!(0, multipleRangeDownloader_1.checkIsRangesSupported)(response, reject)) {
|
|
246
246
|
return;
|
|
247
247
|
}
|
|
248
|
+
response.on("error", reject);
|
|
249
|
+
response.on("aborted", () => {
|
|
250
|
+
reject(new Error("response has been aborted by the server"));
|
|
251
|
+
});
|
|
248
252
|
response.on("data", dataHandler);
|
|
249
253
|
response.on("end", () => resolve());
|
|
250
254
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/DifferentialDownloader.ts"],"names":[],"mappings":";;;AAAA,+DAAuJ;AAEvJ,uCAAsC;AACtC,2BAAsC;AAItC,iDAAyC;AACzC,6BAAyB;AACzB,+DAAmF;AACnF,uEAA0G;AAC1G,mHAAiJ;AAgBjJ,MAAsB,sBAAsB;IAK1C,oEAAoE;IACpE,YACqB,kBAAsC,EAChD,YAA+B,EAC/B,OAAsC;QAF5B,uBAAkB,GAAlB,kBAAkB,CAAoB;QAChD,iBAAY,GAAZ,YAAY,CAAmB;QAC/B,YA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,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;gBAChC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAA;YACrC,CAAC,CAAC,CAAA;YACF,IAAI,CAAC,YAAY,CAAC,0BAA0B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;YAC7D,OAAO,CAAC,GAAG,EAAE,CAAA;QACf,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AArRD,wDAqRC;AAED,SAAS,WAAW,CAAC,KAAa,EAAE,MAAM,GAAG,KAAK;IAChD,OAAO,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAQ,CAAC,GAAG,MAAM,CAAA;AACtF,CAAC;AAED,SAAS;AACT,SAAS,WAAW,CAAC,GAAW;IAC9B,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;AAClD,CAAC","sourcesContent":["import { BlockMapDataHolder, createHttpError, DigestTransform, HttpExecutor, configureRequestUrl, configureRequestOptions } from \"builder-util-runtime\"\nimport { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, open } from \"fs-extra\"\nimport { createWriteStream } from \"fs\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { ProgressInfo, CancellationToken } from \"builder-util-runtime\"\nimport { Logger } from \"../main\"\nimport { copyData } from \"./DataSplitter\"\nimport { URL } from \"url\"\nimport { computeOperations, Operation, OperationKind } from \"./downloadPlanBuilder\"\nimport { checkIsRangesSupported, executeTasksUsingMultipleRangeRequests } from \"./multipleRangeDownloader\"\nimport { ProgressDifferentialDownloadCallbackTransform, ProgressDifferentialDownloadInfo } from \"./ProgressDifferentialDownloadCallbackTransform\"\n\nexport interface DifferentialDownloaderOptions {\n readonly oldFile: string\n readonly newUrl: URL\n readonly logger: Logger\n readonly newFile: string\n\n readonly requestHeaders: OutgoingHttpHeaders | null\n\n readonly isUseMultipleRangeRequest?: boolean\n\n readonly cancellationToken: CancellationToken\n onProgress?: (progress: ProgressInfo) => void\n}\n\nexport abstract class DifferentialDownloader {\n fileMetadataBuffer: Buffer | null = null\n\n private readonly logger: Logger\n\n // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected\n constructor(\n protected readonly blockAwareFileInfo: BlockMapDataHolder,\n readonly httpExecutor: HttpExecutor<any>,\n readonly options: DifferentialDownloaderOptions\n ) {\n this.logger = options.logger\n }\n\n createRequestOptions(): RequestOptions {\n const result = {\n headers: {\n ...this.options.requestHeaders,\n accept: \"*/*\",\n },\n }\n configureRequestUrl(this.options.newUrl, result)\n // user-agent, cache-control and other common options\n configureRequestOptions(result)\n return result\n }\n\n protected doDownload(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any> {\n // we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it\n if (oldBlockMap.version !== newBlockMap.version) {\n throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`)\n }\n\n const logger = this.logger\n const operations = computeOperations(oldBlockMap, newBlockMap, logger)\n if (logger.debug != null) {\n logger.debug(JSON.stringify(operations, null, 2))\n }\n\n let downloadSize = 0\n let copySize = 0\n for (const operation of operations) {\n const length = operation.end - operation.start\n if (operation.kind === OperationKind.DOWNLOAD) {\n downloadSize += length\n } else {\n copySize += length\n }\n }\n\n const newSize = this.blockAwareFileInfo.size\n if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) {\n throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`)\n }\n\n logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`)\n\n return this.downloadFile(operations)\n }\n\n private downloadFile(tasks: Array<Operation>): Promise<any> {\n const fdList: Array<OpenedFile> = []\n const closeFiles = (): Promise<Array<void>> => {\n return Promise.all(\n fdList.map(openedFile => {\n return close(openedFile.descriptor).catch((e: any) => {\n this.logger.error(`cannot close file \"${openedFile.path}\": ${e}`)\n })\n })\n )\n }\n return this.doDownloadFile(tasks, fdList)\n .then(closeFiles)\n .catch((e: any) => {\n // then must be after catch here (since then always throws error)\n return closeFiles()\n .catch(closeFilesError => {\n // closeFiles never throw error, but just to be sure\n try {\n this.logger.error(`cannot close files: ${closeFilesError}`)\n } catch (errorOnLog) {\n try {\n console.error(errorOnLog)\n } catch (ignored) {\n // ok, give up and ignore error\n }\n }\n throw e\n })\n .then(() => {\n throw e\n })\n })\n }\n\n private async doDownloadFile(tasks: Array<Operation>, fdList: Array<OpenedFile>): Promise<any> {\n const oldFileFd = await open(this.options.oldFile, \"r\")\n fdList.push({ descriptor: oldFileFd, path: this.options.oldFile })\n const newFileFd = await open(this.options.newFile, \"w\")\n fdList.push({ descriptor: newFileFd, path: this.options.newFile })\n const fileOut = createWriteStream(this.options.newFile, { fd: newFileFd })\n await new Promise((resolve, reject) => {\n const streams: Array<any> = []\n\n // Create our download info transformer if we have one\n let downloadInfoTransform: ProgressDifferentialDownloadCallbackTransform | undefined = undefined\n if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) {\n // TODO: Does not support multiple ranges (someone feel free to PR this!)\n const expectedByteCounts: Array<number> = []\n let grandTotalBytes = 0\n\n for (const task of tasks) {\n if (task.kind === OperationKind.DOWNLOAD) {\n expectedByteCounts.push(task.end - task.start)\n grandTotalBytes += task.end - task.start\n }\n }\n\n const progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo = {\n expectedByteCounts: expectedByteCounts,\n grandTotal: grandTotalBytes,\n }\n\n downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress)\n streams.push(downloadInfoTransform)\n }\n\n const digestTransform = new DigestTransform(this.blockAwareFileInfo.sha512)\n // to simply debug, do manual validation to allow file to be fully written\n digestTransform.isValidateOnEnd = false\n streams.push(digestTransform)\n\n // noinspection JSArrowFunctionCanBeReplacedWithShorthand\n fileOut.on(\"finish\", () => {\n ;(fileOut.close as any)(() => {\n // remove from fd list because closed successfully\n fdList.splice(1, 1)\n try {\n digestTransform.validate()\n } catch (e: any) {\n reject(e)\n return\n }\n\n resolve(undefined)\n })\n })\n\n streams.push(fileOut)\n\n let lastStream = null\n for (const stream of streams) {\n stream.on(\"error\", reject)\n if (lastStream == null) {\n lastStream = stream\n } else {\n lastStream = lastStream.pipe(stream)\n }\n }\n\n const firstStream = streams[0]\n\n let w: any\n if (this.options.isUseMultipleRangeRequest) {\n w = executeTasksUsingMultipleRangeRequests(this, tasks, firstStream, oldFileFd, reject)\n w(0)\n return\n }\n\n let downloadOperationCount = 0\n let actualUrl: string | null = null\n this.logger.info(`Differential download: ${this.options.newUrl}`)\n\n const requestOptions = this.createRequestOptions()\n ;(requestOptions as any).redirect = \"manual\"\n\n w = (index: number): void => {\n if (index >= tasks.length) {\n if (this.fileMetadataBuffer != null) {\n firstStream.write(this.fileMetadataBuffer)\n }\n firstStream.end()\n return\n }\n\n const operation = tasks[index++]\n if (operation.kind === OperationKind.COPY) {\n // We are copying, let's not send status updates to the UI\n if (downloadInfoTransform) {\n downloadInfoTransform.beginFileCopy()\n }\n\n copyData(operation, firstStream, oldFileFd, reject, () => w(index))\n return\n }\n\n const range = `bytes=${operation.start}-${operation.end - 1}`\n requestOptions.headers!.range = range\n\n this.logger?.debug?.(`download range: ${range}`)\n\n // We are starting to download\n if (downloadInfoTransform) {\n downloadInfoTransform.beginRangeDownload()\n }\n\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n response.on(\"error\", reject)\n response.on(\"abort\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.\n if (response.statusCode >= 400) {\n reject(createHttpError(response))\n }\n\n response.pipe(firstStream, {\n end: false,\n })\n response.once(\"end\", () => {\n // Pass on that we are downloading a segment\n if (downloadInfoTransform) {\n downloadInfoTransform.endRangeDownload()\n }\n\n if (++downloadOperationCount === 100) {\n downloadOperationCount = 0\n setTimeout(() => w(index), 1000)\n } else {\n w(index)\n }\n })\n })\n request.on(\"redirect\", (statusCode: number, method: string, redirectUrl: string) => {\n this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`)\n actualUrl = redirectUrl\n configureRequestUrl(new URL(actualUrl), requestOptions)\n request.followRedirect()\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n }\n\n w(0)\n })\n }\n\n protected async readRemoteBytes(start: number, endInclusive: number): Promise<Buffer> {\n const buffer = Buffer.allocUnsafe(endInclusive + 1 - start)\n const requestOptions = this.createRequestOptions()\n requestOptions.headers!.range = `bytes=${start}-${endInclusive}`\n let position = 0\n await this.request(requestOptions, chunk => {\n chunk.copy(buffer, position)\n position += chunk.length\n })\n\n if (position !== buffer.length) {\n throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`)\n }\n return buffer\n }\n\n private request(requestOptions: RequestOptions, dataHandler: (chunk: Buffer) => void): Promise<void> {\n return new Promise((resolve, reject) => {\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n response.on(\"data\", dataHandler)\n response.on(\"end\", () => resolve())\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n })\n }\n}\n\nfunction formatBytes(value: number, symbol = \" KB\"): string {\n return new Intl.NumberFormat(\"en\").format((value / 1024).toFixed(2) as any) + symbol\n}\n\n// safety\nfunction removeQuery(url: string): string {\n const index = url.indexOf(\"?\")\n return index < 0 ? url : url.substring(0, index)\n}\n\ninterface OpenedFile {\n readonly descriptor: number\n readonly path: string\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/DifferentialDownloader.ts"],"names":[],"mappings":";;;AAAA,+DAAuJ;AAEvJ,uCAAsC;AACtC,2BAAsC;AAItC,iDAAyC;AACzC,6BAAyB;AACzB,+DAAmF;AACnF,uEAA0G;AAC1G,mHAAiJ;AAgBjJ,MAAsB,sBAAsB;IAK1C,oEAAoE;IACpE,YACqB,kBAAsC,EAChD,YAA+B,EAC/B,OAAsC;QAF5B,uBAAkB,GAAlB,kBAAkB,CAAoB;QAChD,iBAAY,GAAZ,YAAY,CAAmB;QAC/B,YAAO,GAAP,OAAO,CAA+B;QARjD,uBAAkB,GAAkB,IAAI,CAAA;QAUtC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;IAC9B,CAAC;IAED,oBAAoB;QAClB,MAAM,MAAM,GAAG;YACb,OAAO,EAAE;gBACP,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc;gBAC9B,MAAM,EAAE,KAAK;aACd;SACF,CAAA;QACD,IAAA,0CAAmB,EAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChD,qDAAqD;QACrD,IAAA,8CAAuB,EAAC,MAAM,CAAC,CAAA;QAC/B,OAAO,MAAM,CAAA;IACf,CAAC;IAES,UAAU,CAAC,WAAqB,EAAE,WAAqB;QAC/D,yIAAyI;QACzI,IAAI,WAAW,CAAC,OAAO,KAAK,WAAW,CAAC,OAAO,EAAE,CAAC;YAChD,MAAM,IAAI,KAAK,CAAC,yBAAyB,WAAW,CAAC,OAAO,MAAM,WAAW,CAAC,OAAO,8BAA8B,CAAC,CAAA;QACtH,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAC1B,MAAM,UAAU,GAAG,IAAA,uCAAiB,EAAC,WAAW,EAAE,WAAW,EAAE,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AS,WAAW,CAAC,GAAW;IAC9B,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;AAClD,CAAC","sourcesContent":["import { BlockMapDataHolder, createHttpError, DigestTransform, HttpExecutor, configureRequestUrl, configureRequestOptions } from \"builder-util-runtime\"\nimport { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, open } from \"fs-extra\"\nimport { createWriteStream } from \"fs\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { ProgressInfo, CancellationToken } from \"builder-util-runtime\"\nimport { Logger } from \"../main\"\nimport { copyData } from \"./DataSplitter\"\nimport { URL } from \"url\"\nimport { computeOperations, Operation, OperationKind } from \"./downloadPlanBuilder\"\nimport { checkIsRangesSupported, executeTasksUsingMultipleRangeRequests } from \"./multipleRangeDownloader\"\nimport { ProgressDifferentialDownloadCallbackTransform, ProgressDifferentialDownloadInfo } from \"./ProgressDifferentialDownloadCallbackTransform\"\n\nexport interface DifferentialDownloaderOptions {\n readonly oldFile: string\n readonly newUrl: URL\n readonly logger: Logger\n readonly newFile: string\n\n readonly requestHeaders: OutgoingHttpHeaders | null\n\n readonly isUseMultipleRangeRequest?: boolean\n\n readonly cancellationToken: CancellationToken\n onProgress?: (progress: ProgressInfo) => void\n}\n\nexport abstract class DifferentialDownloader {\n fileMetadataBuffer: Buffer | null = null\n\n private readonly logger: Logger\n\n // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected\n constructor(\n protected readonly blockAwareFileInfo: BlockMapDataHolder,\n readonly httpExecutor: HttpExecutor<any>,\n readonly options: DifferentialDownloaderOptions\n ) {\n this.logger = options.logger\n }\n\n createRequestOptions(): RequestOptions {\n const result = {\n headers: {\n ...this.options.requestHeaders,\n accept: \"*/*\",\n },\n }\n configureRequestUrl(this.options.newUrl, result)\n // user-agent, cache-control and other common options\n configureRequestOptions(result)\n return result\n }\n\n protected doDownload(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any> {\n // we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it\n if (oldBlockMap.version !== newBlockMap.version) {\n throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`)\n }\n\n const logger = this.logger\n const operations = computeOperations(oldBlockMap, newBlockMap, logger)\n if (logger.debug != null) {\n logger.debug(JSON.stringify(operations, null, 2))\n }\n\n let downloadSize = 0\n let copySize = 0\n for (const operation of operations) {\n const length = operation.end - operation.start\n if (operation.kind === OperationKind.DOWNLOAD) {\n downloadSize += length\n } else {\n copySize += length\n }\n }\n\n const newSize = this.blockAwareFileInfo.size\n if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) {\n throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`)\n }\n\n logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`)\n\n return this.downloadFile(operations)\n }\n\n private downloadFile(tasks: Array<Operation>): Promise<any> {\n const fdList: Array<OpenedFile> = []\n const closeFiles = (): Promise<Array<void>> => {\n return Promise.all(\n fdList.map(openedFile => {\n return close(openedFile.descriptor).catch((e: any) => {\n this.logger.error(`cannot close file \"${openedFile.path}\": ${e}`)\n })\n })\n )\n }\n return this.doDownloadFile(tasks, fdList)\n .then(closeFiles)\n .catch((e: any) => {\n // then must be after catch here (since then always throws error)\n return closeFiles()\n .catch(closeFilesError => {\n // closeFiles never throw error, but just to be sure\n try {\n this.logger.error(`cannot close files: ${closeFilesError}`)\n } catch (errorOnLog) {\n try {\n console.error(errorOnLog)\n } catch (ignored) {\n // ok, give up and ignore error\n }\n }\n throw e\n })\n .then(() => {\n throw e\n })\n })\n }\n\n private async doDownloadFile(tasks: Array<Operation>, fdList: Array<OpenedFile>): Promise<any> {\n const oldFileFd = await open(this.options.oldFile, \"r\")\n fdList.push({ descriptor: oldFileFd, path: this.options.oldFile })\n const newFileFd = await open(this.options.newFile, \"w\")\n fdList.push({ descriptor: newFileFd, path: this.options.newFile })\n const fileOut = createWriteStream(this.options.newFile, { fd: newFileFd })\n await new Promise((resolve, reject) => {\n const streams: Array<any> = []\n\n // Create our download info transformer if we have one\n let downloadInfoTransform: ProgressDifferentialDownloadCallbackTransform | undefined = undefined\n if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) {\n // TODO: Does not support multiple ranges (someone feel free to PR this!)\n const expectedByteCounts: Array<number> = []\n let grandTotalBytes = 0\n\n for (const task of tasks) {\n if (task.kind === OperationKind.DOWNLOAD) {\n expectedByteCounts.push(task.end - task.start)\n grandTotalBytes += task.end - task.start\n }\n }\n\n const progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo = {\n expectedByteCounts: expectedByteCounts,\n grandTotal: grandTotalBytes,\n }\n\n downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress)\n streams.push(downloadInfoTransform)\n }\n\n const digestTransform = new DigestTransform(this.blockAwareFileInfo.sha512)\n // to simply debug, do manual validation to allow file to be fully written\n digestTransform.isValidateOnEnd = false\n streams.push(digestTransform)\n\n // noinspection JSArrowFunctionCanBeReplacedWithShorthand\n fileOut.on(\"finish\", () => {\n ;(fileOut.close as any)(() => {\n // remove from fd list because closed successfully\n fdList.splice(1, 1)\n try {\n digestTransform.validate()\n } catch (e: any) {\n reject(e)\n return\n }\n\n resolve(undefined)\n })\n })\n\n streams.push(fileOut)\n\n let lastStream = null\n for (const stream of streams) {\n stream.on(\"error\", reject)\n if (lastStream == null) {\n lastStream = stream\n } else {\n lastStream = lastStream.pipe(stream)\n }\n }\n\n const firstStream = streams[0]\n\n let w: any\n if (this.options.isUseMultipleRangeRequest) {\n w = executeTasksUsingMultipleRangeRequests(this, tasks, firstStream, oldFileFd, reject)\n w(0)\n return\n }\n\n let downloadOperationCount = 0\n let actualUrl: string | null = null\n this.logger.info(`Differential download: ${this.options.newUrl}`)\n\n const requestOptions = this.createRequestOptions()\n ;(requestOptions as any).redirect = \"manual\"\n\n w = (index: number): void => {\n if (index >= tasks.length) {\n if (this.fileMetadataBuffer != null) {\n firstStream.write(this.fileMetadataBuffer)\n }\n firstStream.end()\n return\n }\n\n const operation = tasks[index++]\n if (operation.kind === OperationKind.COPY) {\n // We are copying, let's not send status updates to the UI\n if (downloadInfoTransform) {\n downloadInfoTransform.beginFileCopy()\n }\n\n copyData(operation, firstStream, oldFileFd, reject, () => w(index))\n return\n }\n\n const range = `bytes=${operation.start}-${operation.end - 1}`\n requestOptions.headers!.range = range\n\n this.logger?.debug?.(`download range: ${range}`)\n\n // We are starting to download\n if (downloadInfoTransform) {\n downloadInfoTransform.beginRangeDownload()\n }\n\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.\n if (response.statusCode >= 400) {\n reject(createHttpError(response))\n }\n\n response.pipe(firstStream, {\n end: false,\n })\n response.once(\"end\", () => {\n // Pass on that we are downloading a segment\n if (downloadInfoTransform) {\n downloadInfoTransform.endRangeDownload()\n }\n\n if (++downloadOperationCount === 100) {\n downloadOperationCount = 0\n setTimeout(() => w(index), 1000)\n } else {\n w(index)\n }\n })\n })\n request.on(\"redirect\", (statusCode: number, method: string, redirectUrl: string) => {\n this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`)\n actualUrl = redirectUrl\n configureRequestUrl(new URL(actualUrl), requestOptions)\n request.followRedirect()\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n }\n\n w(0)\n })\n }\n\n protected async readRemoteBytes(start: number, endInclusive: number): Promise<Buffer> {\n const buffer = Buffer.allocUnsafe(endInclusive + 1 - start)\n const requestOptions = this.createRequestOptions()\n requestOptions.headers!.range = `bytes=${start}-${endInclusive}`\n let position = 0\n await this.request(requestOptions, chunk => {\n chunk.copy(buffer, position)\n position += chunk.length\n })\n\n if (position !== buffer.length) {\n throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`)\n }\n return buffer\n }\n\n private request(requestOptions: RequestOptions, dataHandler: (chunk: Buffer) => void): Promise<void> {\n return new Promise((resolve, reject) => {\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n\n response.on(\"data\", dataHandler)\n response.on(\"end\", () => resolve())\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n })\n }\n}\n\nfunction formatBytes(value: number, symbol = \" KB\"): string {\n return new Intl.NumberFormat(\"en\").format((value / 1024).toFixed(2) as any) + symbol\n}\n\n// safety\nfunction removeQuery(url: string): string {\n const index = url.indexOf(\"?\")\n return index < 0 ? url : url.substring(0, index)\n}\n\ninterface OpenedFile {\n readonly descriptor: number\n readonly path: string\n}\n"]}
|
|
@@ -33,7 +33,9 @@ function verifySignature(publisherNames, unescapedTempUpdateFile, logger) {
|
|
|
33
33
|
// https://github.com/electron-userland/electron-builder/issues/2421
|
|
34
34
|
// https://github.com/electron-userland/electron-builder/issues/2535
|
|
35
35
|
// Resetting PSModulePath is necessary https://github.com/electron-userland/electron-builder/issues/7127
|
|
36
|
-
|
|
36
|
+
// semicolon wont terminate the set command and run chcp thus leading to verification errors on certificats with special chars like german umlauts, so rather
|
|
37
|
+
// join commands using & https://github.com/electron-userland/electron-builder/issues/8162
|
|
38
|
+
(0, child_process_1.execFile)(`set "PSModulePath=" & chcp 65001 >NUL & powershell.exe`, ["-NoProfile", "-NonInteractive", "-InputFormat", "None", "-Command", `"Get-AuthenticodeSignature -LiteralPath '${tempUpdateFile}' | ConvertTo-Json -Compress"`], {
|
|
37
39
|
shell: true,
|
|
38
40
|
timeout: 20 * 1000,
|
|
39
41
|
}, (error, stdout, stderr) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"windowsExecutableCodeSignatureVerifier.js","sourceRoot":"","sources":["../src/windowsExecutableCodeSignatureVerifier.ts"],"names":[],"mappings":";;AASA,0CAsFC;AA/FD,+DAA8C;AAC9C,iDAAsD;AACtD,yBAAwB;AAExB,6BAA4B;AAE5B,8DAA8D;AAC9D,kJAAkJ;AAClJ,kEAAkE;AAClE,SAAgB,eAAe,CAAC,cAA6B,EAAE,uBAA+B,EAAE,MAAc;IAC5G,OAAO,IAAI,OAAO,CAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpD,6EAA6E;QAC7E,oDAAoD;QACpD,EAAE;QACF,uCAAuC;QACvC,gBAAgB;QAChB,oEAAoE;QACpE,MAAM;QACN,+FAA+F;QAC/F,wCAAwC;QACxC,EAAE;QACF,iCAAiC;QACjC,2HAA2H;QAC3H,0EAA0E;QAC1E,sEAAsE;QACtE,EAAE;QACF,0FAA0F;QAC1F,kFAAkF;QAClF,sEAAsE;QACtE,MAAM,cAAc,GAAG,uBAAuB,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAClE,MAAM,CAAC,IAAI,CAAC,uBAAuB,cAAc,EAAE,CAAC,CAAA;QAEpD,oEAAoE;QACpE,oEAAoE;QACpE,wGAAwG;QACxG,IAAA,wBAAQ,EACN,uDAAuD,EACvD,CAAC,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,4CAA4C,cAAc,+BAA+B,CAAC,EAChK;YACE,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,EAAE,GAAG,IAAI;SACnB,EACD,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE;;YACxB,IAAI,CAA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,CAAC,CAAC,CAAA;IACvI,CAAC;AACH,CAAC;AAED,SAAS,SAAS;IAChB,MAAM,UAAU,GAAG,EAAE,CAAC,OAAO,EAAE,CAAA;IAC/B,OAAO,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;AACrE,CAAC","sourcesContent":["import { parseDn } from \"builder-util-runtime\"\nimport { execFile, execFileSync } from \"child_process\"\nimport * as os from \"os\"\nimport { Logger } from \"./main\"\nimport * as path from \"path\"\n\n// $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\nexport function verifySignature(publisherNames: Array<string>, unescapedTempUpdateFile: string, logger: Logger): Promise<string | null> {\n return new Promise<string | null>((resolve, reject) => {\n // Escape quotes and backticks in filenames to prevent user from breaking the\n // arguments and perform a remote command injection.\n //\n // Consider example powershell command:\n // ```powershell\n // Get-AuthenticodeSignature 'C:\\\\path\\\\my-bad-';calc;'filename.exe'\n // ```\n // The above would work expected and find the file name, however, it will also execute `;calc;`\n // command and start the calculator app.\n //\n // From Powershell quoting rules:\n // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7\n // * Double quotes `\"` are treated literally within single-quoted strings;\n // * Single quotes can be escaped by doubling them: 'don''t' -> don't;\n //\n // Also note that at this point the file has already been written to the disk, thus we are\n // guaranteed that the path will not contain any illegal characters like <>:\"/\\|?*\n // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file\n const tempUpdateFile = unescapedTempUpdateFile.replace(/'/g, \"''\")\n logger.info(`Verifying signature ${tempUpdateFile}`)\n\n // https://github.com/electron-userland/electron-builder/issues/2421\n // https://github.com/electron-userland/electron-builder/issues/2535\n // Resetting PSModulePath is necessary https://github.com/electron-userland/electron-builder/issues/7127\n execFile(\n `set \"PSModulePath=\"; chcp 65001 >NUL & powershell.exe`,\n [\"-NoProfile\", \"-NonInteractive\", \"-InputFormat\", \"None\", \"-Command\", `\"Get-AuthenticodeSignature -LiteralPath '${tempUpdateFile}' | ConvertTo-Json -Compress\"`],\n {\n shell: true,\n timeout: 20 * 1000,\n },\n (error, stdout, stderr) => {\n try {\n if (error != null || stderr) {\n handleError(logger, error, stderr, reject)\n resolve(null)\n return\n }\n const data = parseOut(stdout)\n if (data.Status === 0) {\n try {\n const normlaizedUpdateFilePath = path.normalize(data.Path)\n const normalizedTempUpdateFile = path.normalize(unescapedTempUpdateFile)\n logger.info(`LiteralPath: ${normlaizedUpdateFilePath}. Update Path: ${normalizedTempUpdateFile}`)\n if (normlaizedUpdateFilePath !== normalizedTempUpdateFile) {\n handleError(logger, new Error(`LiteralPath of ${normlaizedUpdateFilePath} is different than ${normalizedTempUpdateFile}`), stderr, reject)\n resolve(null)\n return\n }\n } catch (error: any) {\n logger.warn(`Unable to verify LiteralPath of update asset due to missing data.Path. Skipping this step of validation. Message: ${error.message ?? error.stack}`)\n }\n const subject = parseDn(data.SignerCertificate.Subject)\n let match = false\n for (const name of publisherNames) {\n const dn = parseDn(name)\n if (dn.size) {\n // if we have a full DN, compare all values\n const allKeys = Array.from(dn.keys())\n match = allKeys.every(key => {\n return dn.get(key) === subject.get(key)\n })\n } else if (name === subject.get(\"CN\")!) {\n logger.warn(`Signature validated using only CN ${name}. Please add your full Distinguished Name (DN) to publisherNames configuration`)\n match = true\n }\n if (match) {\n resolve(null)\n return\n }\n }\n }\n\n const result = `publisherNames: ${publisherNames.join(\" | \")}, raw info: ` + JSON.stringify(data, (name, value) => (name === \"RawData\" ? undefined : value), 2)\n logger.warn(`Sign verification failed, installer signed with incorrect certificate: ${result}`)\n resolve(result)\n } catch (e: any) {\n handleError(logger, e, null, reject)\n resolve(null)\n return\n }\n }\n )\n })\n}\n\nfunction parseOut(out: string): any {\n const data = JSON.parse(out)\n delete data.PrivateKey\n delete data.IsOSBinary\n delete data.SignatureType\n const signerCertificate = data.SignerCertificate\n if (signerCertificate != null) {\n delete signerCertificate.Archived\n delete signerCertificate.Extensions\n delete signerCertificate.Handle\n delete signerCertificate.HasPrivateKey\n // duplicates data.SignerCertificate (contains RawData)\n delete signerCertificate.SubjectName\n }\n return data\n}\n\nfunction handleError(logger: Logger, error: Error | null, stderr: string | null, reject: (reason: any) => void): void {\n if (isOldWin6()) {\n logger.warn(\n `Cannot execute Get-AuthenticodeSignature: ${error || stderr}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n )\n return\n }\n\n try {\n execFileSync(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\", \"ConvertTo-Json test\"], { timeout: 10 * 1000 } as any)\n } catch (testError: any) {\n logger.warn(\n `Cannot execute ConvertTo-Json: ${testError.message}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n )\n return\n }\n\n if (error != null) {\n reject(error)\n }\n\n if (stderr) {\n reject(new Error(`Cannot execute Get-AuthenticodeSignature, stderr: ${stderr}. Failing signature validation due to unknown stderr.`))\n }\n}\n\nfunction isOldWin6(): boolean {\n const winVersion = os.release()\n return winVersion.startsWith(\"6.\") && !winVersion.startsWith(\"6.3\")\n}\n"]}
|
|
1
|
+
{"version":3,"file":"windowsExecutableCodeSignatureVerifier.js","sourceRoot":"","sources":["../src/windowsExecutableCodeSignatureVerifier.ts"],"names":[],"mappings":";;AASA,0CAwFC;AAjGD,+DAA8C;AAC9C,iDAAsD;AACtD,yBAAwB;AAExB,6BAA4B;AAE5B,8DAA8D;AAC9D,kJAAkJ;AAClJ,kEAAkE;AAClE,SAAgB,eAAe,CAAC,cAA6B,EAAE,uBAA+B,EAAE,MAAc;IAC5G,OAAO,IAAI,OAAO,CAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpD,6EAA6E;QAC7E,oDAAoD;QACpD,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I,CAAA;AACb,CAAC;AAED,SAAS,WAAW,CAAC,MAAc,EAAE,KAAmB,EAAE,MAAqB,EAAE,MAA6B;IAC5G,IAAI,SAAS,EAAE,EAAE,CAAC;QAChB,MAAM,CAAC,IAAI,CACT,6CAA6C,KAAK,IAAI,MAAM,kHAAkH,CAC/K,CAAA;QACD,OAAM;IACR,CAAC;IAED,IAAI,CAAC;QACH,IAAA,4BAAY,EAAC,gBAAgB,EAAE,CAAC,YAAY,EAAE,iBAAiB,EAAE,UAAU,EAAE,qBAAqB,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,GAAG,IAAI,EAAS,CAAC,CAAA;IACrI,CAAC;IAAC,OAAO,SAAc,EAAE,CAAC;QACxB,MAAM,CAAC,IAAI,CACT,kCAAkC,SAAS,CAAC,OAAO,kHAAkH,CACtK,CAAA;QACD,OAAM;IACR,CAAC;IAED,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;QAClB,MAAM,CAAC,KAAK,CAAC,CAAA;IACf,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,CAAC,IAAI,KAAK,CAAC,qDAAqD,MAAM,uDAAuD,CAAC,CAAC,CAAA;IACvI,CAAC;AACH,CAAC;AAED,SAAS,SAAS;IAChB,MAAM,UAAU,GAAG,EAAE,CAAC,OAAO,EAAE,CAAA;IAC/B,OAAO,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,CAAA;AACrE,CAAC","sourcesContent":["import { parseDn } from \"builder-util-runtime\"\nimport { execFile, execFileSync } from \"child_process\"\nimport * as os from \"os\"\nimport { Logger } from \"./main\"\nimport * as path from \"path\"\n\n// $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\nexport function verifySignature(publisherNames: Array<string>, unescapedTempUpdateFile: string, logger: Logger): Promise<string | null> {\n return new Promise<string | null>((resolve, reject) => {\n // Escape quotes and backticks in filenames to prevent user from breaking the\n // arguments and perform a remote command injection.\n //\n // Consider example powershell command:\n // ```powershell\n // Get-AuthenticodeSignature 'C:\\\\path\\\\my-bad-';calc;'filename.exe'\n // ```\n // The above would work expected and find the file name, however, it will also execute `;calc;`\n // command and start the calculator app.\n //\n // From Powershell quoting rules:\n // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7\n // * Double quotes `\"` are treated literally within single-quoted strings;\n // * Single quotes can be escaped by doubling them: 'don''t' -> don't;\n //\n // Also note that at this point the file has already been written to the disk, thus we are\n // guaranteed that the path will not contain any illegal characters like <>:\"/\\|?*\n // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file\n const tempUpdateFile = unescapedTempUpdateFile.replace(/'/g, \"''\")\n logger.info(`Verifying signature ${tempUpdateFile}`)\n\n // https://github.com/electron-userland/electron-builder/issues/2421\n // https://github.com/electron-userland/electron-builder/issues/2535\n // Resetting PSModulePath is necessary https://github.com/electron-userland/electron-builder/issues/7127\n // semicolon wont terminate the set command and run chcp thus leading to verification errors on certificats with special chars like german umlauts, so rather\n // join commands using & https://github.com/electron-userland/electron-builder/issues/8162\n execFile(\n `set \"PSModulePath=\" & chcp 65001 >NUL & powershell.exe`,\n [\"-NoProfile\", \"-NonInteractive\", \"-InputFormat\", \"None\", \"-Command\", `\"Get-AuthenticodeSignature -LiteralPath '${tempUpdateFile}' | ConvertTo-Json -Compress\"`],\n {\n shell: true,\n timeout: 20 * 1000,\n },\n (error, stdout, stderr) => {\n try {\n if (error != null || stderr) {\n handleError(logger, error, stderr, reject)\n resolve(null)\n return\n }\n const data = parseOut(stdout)\n if (data.Status === 0) {\n try {\n const normlaizedUpdateFilePath = path.normalize(data.Path)\n const normalizedTempUpdateFile = path.normalize(unescapedTempUpdateFile)\n logger.info(`LiteralPath: ${normlaizedUpdateFilePath}. Update Path: ${normalizedTempUpdateFile}`)\n if (normlaizedUpdateFilePath !== normalizedTempUpdateFile) {\n handleError(logger, new Error(`LiteralPath of ${normlaizedUpdateFilePath} is different than ${normalizedTempUpdateFile}`), stderr, reject)\n resolve(null)\n return\n }\n } catch (error: any) {\n logger.warn(`Unable to verify LiteralPath of update asset due to missing data.Path. Skipping this step of validation. Message: ${error.message ?? error.stack}`)\n }\n const subject = parseDn(data.SignerCertificate.Subject)\n let match = false\n for (const name of publisherNames) {\n const dn = parseDn(name)\n if (dn.size) {\n // if we have a full DN, compare all values\n const allKeys = Array.from(dn.keys())\n match = allKeys.every(key => {\n return dn.get(key) === subject.get(key)\n })\n } else if (name === subject.get(\"CN\")!) {\n logger.warn(`Signature validated using only CN ${name}. Please add your full Distinguished Name (DN) to publisherNames configuration`)\n match = true\n }\n if (match) {\n resolve(null)\n return\n }\n }\n }\n\n const result = `publisherNames: ${publisherNames.join(\" | \")}, raw info: ` + JSON.stringify(data, (name, value) => (name === \"RawData\" ? undefined : value), 2)\n logger.warn(`Sign verification failed, installer signed with incorrect certificate: ${result}`)\n resolve(result)\n } catch (e: any) {\n handleError(logger, e, null, reject)\n resolve(null)\n return\n }\n }\n )\n })\n}\n\nfunction parseOut(out: string): any {\n const data = JSON.parse(out)\n delete data.PrivateKey\n delete data.IsOSBinary\n delete data.SignatureType\n const signerCertificate = data.SignerCertificate\n if (signerCertificate != null) {\n delete signerCertificate.Archived\n delete signerCertificate.Extensions\n delete signerCertificate.Handle\n delete signerCertificate.HasPrivateKey\n // duplicates data.SignerCertificate (contains RawData)\n delete signerCertificate.SubjectName\n }\n return data\n}\n\nfunction handleError(logger: Logger, error: Error | null, stderr: string | null, reject: (reason: any) => void): void {\n if (isOldWin6()) {\n logger.warn(\n `Cannot execute Get-AuthenticodeSignature: ${error || stderr}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n )\n return\n }\n\n try {\n execFileSync(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\", \"ConvertTo-Json test\"], { timeout: 10 * 1000 } as any)\n } catch (testError: any) {\n logger.warn(\n `Cannot execute ConvertTo-Json: ${testError.message}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`\n )\n return\n }\n\n if (error != null) {\n reject(error)\n }\n\n if (stderr) {\n reject(new Error(`Cannot execute Get-AuthenticodeSignature, stderr: ${stderr}. Failing signature validation due to unknown stderr.`))\n }\n}\n\nfunction isOldWin6(): boolean {\n const winVersion = os.release()\n return winVersion.startsWith(\"6.\") && !winVersion.startsWith(\"6.3\")\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "electron-updater",
|
|
3
|
-
"version": "6.3.
|
|
3
|
+
"version": "6.3.5",
|
|
4
4
|
"description": "Cross platform updater for electron applications",
|
|
5
5
|
"main": "out/main.js",
|
|
6
6
|
"author": "Vladimir Krivosheev",
|
|
@@ -21,9 +21,9 @@
|
|
|
21
21
|
"lazy-val": "^1.0.5",
|
|
22
22
|
"lodash.escaperegexp": "^4.1.2",
|
|
23
23
|
"lodash.isequal": "^4.5.0",
|
|
24
|
-
"semver": "^7.3
|
|
24
|
+
"semver": "^7.6.3",
|
|
25
25
|
"tiny-typed-emitter": "^2.1.0",
|
|
26
|
-
"builder-util-runtime": "9.2.
|
|
26
|
+
"builder-util-runtime": "9.2.6"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/fs-extra": "9.0.13",
|