-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathNsisUpdater.ts
More file actions
227 lines (205 loc) · 9.54 KB
/
Copy pathNsisUpdater.ts
File metadata and controls
227 lines (205 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import { AllPublishOptions, newError, PackageFileInfo, CURRENT_APP_INSTALLER_FILE_NAME, CURRENT_APP_PACKAGE_FILE_NAME } from "builder-util-runtime"
import * as path from "path"
import { AppAdapter } from "./AppAdapter"
import { DownloadUpdateOptions } from "./AppUpdater"
import { BaseUpdater, InstallOptions } from "./BaseUpdater"
import { DifferentialDownloaderOptions } from "./differentialDownloader/DifferentialDownloader"
import { FileWithEmbeddedBlockMapDifferentialDownloader } from "./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader"
import { DOWNLOAD_PROGRESS } from "./types"
import { VerifyUpdateCodeSignature } from "./main"
import { findFile, Provider } from "./providers/Provider"
import { unlink } from "fs-extra"
import { verifySignature } from "./windowsExecutableCodeSignatureVerifier"
import { URL } from "url"
export class NsisUpdater extends BaseUpdater {
/**
* Specify custom install directory path
*
*/
installDirectory?: string
constructor(options?: AllPublishOptions | null, app?: AppAdapter) {
super(options, app)
}
protected _verifyUpdateCodeSignature: VerifyUpdateCodeSignature = (publisherNames: Array<string>, unescapedTempUpdateFile: string) =>
verifySignature(publisherNames, unescapedTempUpdateFile, this._logger)
/**
* The verifyUpdateCodeSignature. You can pass [win-verify-signature](https://github.com/beyondkmp/win-verify-trust) or another custom verify function: ` (publisherName: string[], path: string) => Promise<string | null>`.
* The default verify function uses [windowsExecutableCodeSignatureVerifier](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/windowsExecutableCodeSignatureVerifier.ts)
*/
get verifyUpdateCodeSignature(): VerifyUpdateCodeSignature {
return this._verifyUpdateCodeSignature
}
set verifyUpdateCodeSignature(value: VerifyUpdateCodeSignature) {
if (value) {
this._verifyUpdateCodeSignature = value
}
}
/*** @private */
protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>> {
const provider = downloadUpdateOptions.updateInfoAndProvider.provider
const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), "exe")!
return this.executeDownload({
fileExtension: "exe",
downloadUpdateOptions,
fileInfo,
task: async (destinationFile, downloadOptions, packageFile, removeTempDirIfAny) => {
const packageInfo = fileInfo.packageInfo
const isWebInstaller = packageInfo != null && packageFile != null
if (isWebInstaller && downloadUpdateOptions.disableWebInstaller) {
throw newError(
`Unable to download new version ${downloadUpdateOptions.updateInfoAndProvider.info.version}. Web Installers are disabled`,
"ERR_UPDATER_WEB_INSTALLER_DISABLED"
)
}
if (!isWebInstaller && !downloadUpdateOptions.disableWebInstaller) {
this._logger.warn(
"disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version."
)
}
if (
isWebInstaller ||
downloadUpdateOptions.disableDifferentialDownload ||
(await this.differentialDownloadInstaller(fileInfo, downloadUpdateOptions, destinationFile, provider, CURRENT_APP_INSTALLER_FILE_NAME))
) {
await this.httpExecutor.download(fileInfo.url, destinationFile, downloadOptions)
}
const signatureVerificationStatus = await this.verifySignature(destinationFile)
if (signatureVerificationStatus != null) {
await removeTempDirIfAny()
// noinspection ThrowInsideFinallyBlockJS
throw newError(
`New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`,
"ERR_UPDATER_INVALID_SIGNATURE"
)
}
if (isWebInstaller) {
if (await this.differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packageFile, provider)) {
try {
await this.httpExecutor.download(new URL(packageInfo.path), packageFile, {
headers: downloadUpdateOptions.requestHeaders,
cancellationToken: downloadUpdateOptions.cancellationToken,
sha512: packageInfo.sha512,
})
} catch (e: any) {
try {
await unlink(packageFile)
} catch (_ignored) {
// ignore
}
throw e
}
}
}
},
})
}
// $certificateInfo = (Get-AuthenticodeSignature 'xxx\yyy.exe'
// | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains("CN=siemens.com")})
// | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }
private async verifySignature(tempUpdateFile: string): Promise<string | null> {
let publisherName: Array<string> | string | null
try {
publisherName = (await this.configOnDisk.value).publisherName
if (publisherName == null) {
return null
}
} catch (e: any) {
if (e.code === "ENOENT") {
// no app-update.yml
return null
}
throw e
}
return await this._verifyUpdateCodeSignature(Array.isArray(publisherName) ? publisherName : [publisherName], tempUpdateFile)
}
protected doInstall(options: InstallOptions): boolean {
const installerPath = this.installerPath
if (installerPath == null) {
this.dispatchError(new Error("No update filepath provided, can't quit and install"))
return false
}
const args = ["--updated"]
if (options.isSilent) {
args.push("/S")
}
if (options.isForceRunAfter) {
args.push("--force-run")
}
if (this.installDirectory) {
// maybe check if folder exists
args.push(`/D=${this.installDirectory}`)
}
const packagePath = this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.packageFile
if (packagePath != null) {
// only = form is supported
args.push(`--package-file=${packagePath}`)
}
const callUsingElevation = (): void => {
// Wrap args containing spaces in Win32 double-quotes so Start-Process preserves them as single tokens
const psInstallArgs = args.map(a => (a.includes(" ") ? `'"${a.replace(/"/g, '""')}"'` : `'${a.replace(/'/g, "''")}'`)).join(",")
const psScript = `Start-Process -FilePath '${installerPath.replace(/'/g, "''")}' -ArgumentList @(${psInstallArgs}) -Verb RunAs`
const encodedCmd = Buffer.from(psScript, "utf16le").toString("base64")
this.spawnLog("powershell.exe", ["-NonInteractive", "-NoProfile", "-EncodedCommand", encodedCmd]).catch(e => {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") {
this.dispatchError(e)
return
}
// powershell.exe not found — fall back to legacy elevate.exe
this.spawnLog(path.join(process.resourcesPath, "elevate.exe"), [installerPath].concat(args)).catch(err => this.dispatchError(err))
})
}
if (options.isAdminRightsRequired) {
this._logger.info("isAdminRightsRequired is set to true, running installer with UAC elevation via PowerShell (elevate.exe fallback if PowerShell unavailable)")
callUsingElevation()
return true
}
this.spawnLog(installerPath, args).catch((e: Error) => {
// https://github.com/electron-userland/electron-builder/issues/1129
// Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors
const errorCode = (e as NodeJS.ErrnoException).code
this._logger.info(
`Cannot run installer: error code: ${errorCode}, error message: "${e.message}", will be executed again using UAC elevation if EACCES, and will try to use electron.shell.openPath if ENOENT`
)
if (errorCode === "UNKNOWN" || errorCode === "EACCES") {
callUsingElevation()
} else if (errorCode === "ENOENT") {
require("electron")
.shell.openPath(installerPath)
.catch((err: Error) => this.dispatchError(err))
} else {
this.dispatchError(e)
}
})
return true
}
private async differentialDownloadWebPackage(
downloadUpdateOptions: DownloadUpdateOptions,
packageInfo: PackageFileInfo,
packagePath: string,
provider: Provider<any>
): Promise<boolean> {
if (packageInfo.blockMapSize == null) {
return true
}
try {
const downloadOptions: DifferentialDownloaderOptions = {
newUrl: new URL(packageInfo.path),
oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, CURRENT_APP_PACKAGE_FILE_NAME),
logger: this._logger,
newFile: packagePath,
requestHeaders: this.requestHeaders,
isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,
cancellationToken: downloadUpdateOptions.cancellationToken,
}
if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {
downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)
}
await new FileWithEmbeddedBlockMapDifferentialDownloader(packageInfo, this.httpExecutor, downloadOptions).download()
} catch (e: any) {
this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)
// during test (developer machine mac or linux) we must throw error
return process.platform === "win32"
}
return false
}
}