signal-desktop/ts/updater/common.ts

1017 lines
27 KiB
TypeScript
Raw Normal View History

2023-01-03 19:55:46 +00:00
// Copyright 2019 Signal Messenger, LLC
2020-10-30 20:34:04 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
2020-09-16 19:31:05 +00:00
/* eslint-disable no-console */
2022-03-03 22:34:51 +00:00
import { createWriteStream } from 'fs';
2022-02-24 21:01:41 +00:00
import { pathExists } from 'fs-extra';
import { readdir, stat, writeFile, mkdir } from 'fs/promises';
2022-02-24 21:01:41 +00:00
import { join, normalize, extname } from 'path';
2023-01-18 23:31:10 +00:00
import { tmpdir, release as osRelease } from 'os';
import { throttle } from 'lodash';
import type { ParserConfiguration } from 'dashdash';
import { createParser } from 'dashdash';
import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';
2023-01-18 23:31:10 +00:00
import { gt, lt } from 'semver';
2021-08-27 20:21:42 +00:00
import config from 'config';
import got from 'got';
import { v4 as getGuid } from 'uuid';
import type { BrowserWindow } from 'electron';
import { app, ipcMain } from 'electron';
import * as durations from '../util/durations';
import { getTempPath, getUpdateCachePath } from '../../app/attachments';
import { markShouldNotQuit, markShouldQuit } from '../../app/window_state';
import { DialogType } from '../types/Dialogs';
import * as Errors from '../types/errors';
import { isAlpha, isBeta, isStaging } from '../util/version';
2022-02-24 21:01:41 +00:00
import { strictAssert } from '../util/assert';
2024-02-14 18:27:31 +00:00
import { drop } from '../util/drop';
import * as packageJson from '../../package.json';
import {
hexToBinary,
verifySignature,
getSignatureFileName,
} from './signature';
import { isPathInside } from '../util/isPathInside';
import type { SettingsChannel } from '../main/settingsChannel';
import type { LoggerType } from '../types/Logging';
2022-02-24 21:01:41 +00:00
import { getGotOptions } from './got';
2023-03-02 17:57:36 +00:00
import { checkIntegrity, gracefulRename, gracefulRimraf } from './util';
2022-02-24 21:01:41 +00:00
import type { PrepareDownloadResultType as DifferentialDownloadDataType } from './differential';
import {
prepareDownload as prepareDifferentialDownload,
download as downloadDifferentialData,
getBlockMapFileName,
isValidPreparedData as isValidDifferentialData,
2022-02-24 21:01:41 +00:00
} from './differential';
2024-02-14 18:27:31 +00:00
const POLL_INTERVAL = 30 * durations.MINUTE;
type JSONVendorSchema = {
minOSVersion?: string;
2023-12-13 17:20:58 +00:00
requireManualUpdate?: 'true' | 'false';
requireUserConfirmation?: 'true' | 'false';
};
type JSONUpdateSchema = {
version: string;
files: Array<{
url: string;
sha512: string;
size: string;
blockMapSize?: string;
}>;
path: string;
sha512: string;
releaseDate: string;
vendor?: JSONVendorSchema;
};
export type UpdateInformationType = {
fileName: string;
size: number;
version: string;
2022-02-24 21:01:41 +00:00
sha512: string;
differentialData: DifferentialDownloadDataType | undefined;
vendor?: JSONVendorSchema;
};
enum DownloadMode {
DifferentialOnly = 'DifferentialOnly',
FullOnly = 'FullOnly',
Automatic = 'Automatic',
}
2022-03-03 22:34:51 +00:00
type DownloadUpdateResultType = Readonly<{
updateFilePath: string;
signature: Buffer;
}>;
export type UpdaterOptionsType = Readonly<{
settingsChannel: SettingsChannel;
logger: LoggerType;
getMainWindow: () => BrowserWindow | undefined;
canRunSilently: () => boolean;
}>;
export abstract class Updater {
protected fileName: string | undefined;
protected version: string | undefined;
protected cachedDifferentialData: DifferentialDownloadDataType | undefined;
protected readonly logger: LoggerType;
private readonly settingsChannel: SettingsChannel;
protected readonly getMainWindow: () => BrowserWindow | undefined;
2024-02-23 18:54:29 +00:00
private throttledSendDownloadingUpdate: ((downloadedSize: number) => void) & {
cancel: () => void;
};
2022-03-03 22:34:51 +00:00
private activeDownload: Promise<boolean> | undefined;
private markedCannotUpdate = false;
private restarting = false;
private readonly canRunSilently: () => boolean;
constructor({
settingsChannel,
logger,
getMainWindow,
canRunSilently,
}: UpdaterOptionsType) {
this.settingsChannel = settingsChannel;
this.logger = logger;
this.getMainWindow = getMainWindow;
this.canRunSilently = canRunSilently;
this.throttledSendDownloadingUpdate = throttle((downloadedSize: number) => {
const mainWindow = this.getMainWindow();
mainWindow?.webContents.send(
'show-update-dialog',
DialogType.Downloading,
{ downloadedSize }
);
2024-02-23 18:54:29 +00:00
}, 50);
}
//
// Public APIs
//
public async force(): Promise<void> {
return this.checkForUpdatesMaybeInstall(true);
}
// If the updater was about to restart the app but the user cancelled it, show dialog
// to let them retry the restart
public onRestartCancelled(): void {
if (!this.restarting) {
return;
}
this.logger.info(
2024-02-27 06:03:07 +00:00
'updater/onRestartCancelled: restart was cancelled. forcing update to reset updater state'
);
this.restarting = false;
markShouldNotQuit();
2024-02-27 06:03:07 +00:00
drop(this.force());
}
public async start(): Promise<void> {
this.logger.info('updater/start: starting checks...');
2024-02-14 18:27:31 +00:00
this.schedulePoll();
2019-08-02 21:11:10 +00:00
await this.deletePreviousInstallers();
await this.checkForUpdatesMaybeInstall();
2019-08-02 21:11:10 +00:00
}
//
// Abstract methods
//
protected abstract deletePreviousInstallers(): Promise<void>;
protected abstract installUpdate(
updateFilePath: string,
isSilent: boolean
): Promise<void>;
//
// Protected methods
//
protected setUpdateListener(
performUpdateCallback: () => Promise<void> | void
): void {
ipcMain.removeHandler('start-update');
ipcMain.handleOnce('start-update', performUpdateCallback);
}
protected markCannotUpdate(
error: Error,
dialogType = DialogType.Cannot_Update
): void {
if (this.markedCannotUpdate) {
this.logger.warn(
'updater/markCannotUpdate: already marked',
Errors.toLogFormat(error)
);
return;
}
this.markedCannotUpdate = true;
this.logger.error(
'updater/markCannotUpdate: marking due to error: ' +
`${Errors.toLogFormat(error)}, ` +
`dialogType: ${dialogType}`
);
const mainWindow = this.getMainWindow();
mainWindow?.webContents.send('show-update-dialog', dialogType);
this.setUpdateListener(async () => {
this.logger.info('updater/markCannotUpdate: retrying after user action');
this.markedCannotUpdate = false;
await this.checkForUpdatesMaybeInstall();
});
}
protected markRestarting(): void {
this.restarting = true;
markShouldQuit();
}
//
// Private methods
//
2024-02-14 18:27:31 +00:00
private schedulePoll(): void {
const now = Date.now();
const earliestPollTime = now - (now % POLL_INTERVAL) + POLL_INTERVAL;
const selectedPollTime = Math.round(
earliestPollTime + Math.random() * POLL_INTERVAL
);
const timeoutMs = selectedPollTime - now;
this.logger.info(`updater/start: polling in ${timeoutMs}ms`);
setTimeout(() => {
drop(this.safePoll());
}, timeoutMs);
}
private async safePoll(): Promise<void> {
try {
this.logger.info('updater/start: polling now');
await this.checkForUpdatesMaybeInstall();
} catch (error) {
this.logger.error(`updater/start: ${Errors.toLogFormat(error)}`);
} finally {
this.schedulePoll();
}
}
private async downloadAndInstall(
2022-02-24 21:01:41 +00:00
updateInfo: UpdateInformationType,
mode: DownloadMode
2022-03-03 22:34:51 +00:00
): Promise<boolean> {
if (this.activeDownload) {
return this.activeDownload;
}
try {
this.activeDownload = this.doDownloadAndInstall(updateInfo, mode);
return await this.activeDownload;
} finally {
this.activeDownload = undefined;
}
}
private async doDownloadAndInstall(
updateInfo: UpdateInformationType,
mode: DownloadMode
): Promise<boolean> {
const { logger } = this;
2022-02-24 21:01:41 +00:00
const { fileName: newFileName, version: newVersion } = updateInfo;
try {
const oldVersion = this.version;
this.version = newVersion;
2022-03-03 22:34:51 +00:00
let downloadResult: DownloadUpdateResultType | undefined;
try {
2022-03-03 22:34:51 +00:00
downloadResult = await this.downloadUpdate(updateInfo, mode);
} catch (error) {
// Restore state in case of download error
this.version = oldVersion;
2022-03-03 22:34:51 +00:00
throw error;
}
2019-08-02 21:11:10 +00:00
2022-03-03 22:34:51 +00:00
if (!downloadResult) {
logger.warn('downloadAndInstall: no update was downloaded');
strictAssert(
mode !== DownloadMode.Automatic && mode !== DownloadMode.FullOnly,
'Automatic and full mode downloads are guaranteed to happen or error'
);
return false;
}
2022-03-03 22:34:51 +00:00
const { updateFilePath, signature } = downloadResult;
const publicKey = hexToBinary(config.get('updatesPublicKey'));
const verified = await verifySignature(
2022-02-24 21:01:41 +00:00
updateFilePath,
this.version,
2022-03-03 22:34:51 +00:00
signature,
publicKey
);
if (!verified) {
// Note: We don't delete the cache here, because we don't want to continually
// re-download the broken release. We will download it only once per launch.
throw new Error(
'Downloaded update did not pass signature verification ' +
2022-02-24 21:01:41 +00:00
`(version: '${this.version}'; fileName: '${newFileName}')`
);
}
await this.installUpdate(
updateFilePath,
2023-12-13 17:20:58 +00:00
updateInfo.vendor?.requireUserConfirmation !== 'true' &&
this.canRunSilently()
);
const mainWindow = this.getMainWindow();
if (mainWindow) {
2023-01-23 16:56:39 +00:00
logger.info('downloadAndInstall: showing update dialog...');
2023-03-15 16:57:27 +00:00
mainWindow.webContents.send(
'show-update-dialog',
mode === DownloadMode.Automatic
? DialogType.AutoUpdate
: DialogType.DownloadedUpdate,
{
version: this.version,
}
);
} else {
logger.warn(
'downloadAndInstall: no mainWindow, cannot show update dialog'
);
}
return true;
} catch (error) {
logger.error(`downloadAndInstall: ${Errors.toLogFormat(error)}`);
this.markCannotUpdate(error);
throw error;
}
}
private async checkForUpdatesMaybeInstall(force = false): Promise<void> {
const { logger } = this;
logger.info('checkForUpdatesMaybeInstall: checking for update...');
const updateInfo = await this.checkForUpdates(force);
if (!updateInfo) {
return;
}
const { version: newVersion } = updateInfo;
if (!force && this.version && !gt(newVersion, this.version)) {
return;
}
const autoDownloadUpdates = await this.getAutoDownloadUpdateSetting();
if (autoDownloadUpdates) {
await this.downloadAndInstall(updateInfo, DownloadMode.Automatic);
return;
}
let mode = DownloadMode.FullOnly;
if (updateInfo.differentialData) {
mode = DownloadMode.DifferentialOnly;
}
await this.offerUpdate(updateInfo, mode, 0);
}
private async offerUpdate(
updateInfo: UpdateInformationType,
mode: DownloadMode,
attempt: number
): Promise<void> {
const { logger } = this;
this.setUpdateListener(async () => {
logger.info('offerUpdate: have not downloaded update, going to download');
const didDownload = await this.downloadAndInstall(updateInfo, mode);
if (!didDownload && mode === DownloadMode.DifferentialOnly) {
this.logger.warn(
'offerUpdate: Failed to download differential update, offering full'
);
2024-02-23 18:54:29 +00:00
this.throttledSendDownloadingUpdate.cancel();
return this.offerUpdate(updateInfo, DownloadMode.FullOnly, attempt + 1);
}
strictAssert(didDownload, 'FullOnly must always download update');
});
const mainWindow = this.getMainWindow();
if (!mainWindow) {
logger.warn('offerUpdate: no mainWindow, cannot show update dialog');
return;
}
let downloadSize: number;
if (mode === DownloadMode.DifferentialOnly) {
strictAssert(
updateInfo.differentialData,
'Must have differential data in DifferentialOnly mode'
);
downloadSize = updateInfo.differentialData.downloadSize;
} else {
downloadSize = updateInfo.size;
}
logger.info(`offerUpdate: offering ${mode} update`);
mainWindow.webContents.send(
'show-update-dialog',
attempt === 0 ? DialogType.DownloadReady : DialogType.FullDownloadReady,
{
downloadSize,
downloadMode: mode,
version: updateInfo.version,
}
);
}
private async checkForUpdates(
forceUpdate = false
2022-02-24 21:01:41 +00:00
): Promise<UpdateInformationType | undefined> {
const yaml = await getUpdateYaml();
const parsedYaml = parseYaml(yaml);
2023-01-18 23:31:10 +00:00
const { vendor } = parsedYaml;
if (vendor) {
2023-12-13 17:20:58 +00:00
if (vendor.requireManualUpdate === 'true') {
2023-01-18 23:31:10 +00:00
this.logger.warn('checkForUpdates: manual update required');
this.markCannotUpdate(
new Error('yaml file has requireManualUpdate flag'),
DialogType.Cannot_Update_Require_Manual
);
return;
}
if (vendor.minOSVersion && lt(osRelease(), vendor.minOSVersion)) {
this.logger.warn(
`checkForUpdates: OS version ${osRelease()} is less than the ` +
`minimum supported version ${vendor.minOSVersion}`
);
this.markCannotUpdate(
new Error('yaml file has unsatisfied minOSVersion value'),
DialogType.UnsupportedOS
);
return;
}
}
const version = getVersion(parsedYaml);
if (!version) {
this.logger.warn(
'checkForUpdates: no version extracted from downloaded yaml'
);
2022-02-24 21:01:41 +00:00
return;
}
2022-02-24 21:01:41 +00:00
if (!forceUpdate && !isVersionNewer(version)) {
this.logger.info(
2022-02-24 21:01:41 +00:00
`checkForUpdates: ${version} is not newer than ${packageJson.version}; ` +
'no new update available'
2021-12-03 22:49:15 +00:00
);
2022-02-24 21:01:41 +00:00
return;
}
this.logger.info(
2022-02-24 21:01:41 +00:00
`checkForUpdates: found newer version ${version} ` +
`forceUpdate=${forceUpdate}`
);
const fileName = getUpdateFileName(
parsedYaml,
process.platform,
await this.getArch()
);
const sha512 = getSHA512(parsedYaml, fileName);
strictAssert(sha512 !== undefined, 'Missing required hash');
const latestInstaller = await this.getLatestCachedInstaller(
extname(fileName)
);
2022-02-24 21:01:41 +00:00
let differentialData: DifferentialDownloadDataType | undefined;
if (latestInstaller) {
this.logger.info(
`checkForUpdates: Found local installer ${latestInstaller}`
);
const diffOptions = {
oldFile: latestInstaller,
newUrl: `${getUpdatesBase()}/${fileName}`,
sha512,
};
2022-02-24 21:01:41 +00:00
if (
this.cachedDifferentialData &&
isValidDifferentialData(this.cachedDifferentialData, diffOptions)
) {
this.logger.info('checkForUpdates: using cached differential data');
differentialData = this.cachedDifferentialData;
} else {
try {
differentialData = await prepareDifferentialDownload(diffOptions);
this.cachedDifferentialData = differentialData;
this.logger.info(
'checkForUpdates: differential download size',
differentialData.downloadSize
);
} catch (error) {
this.logger.error(
'checkForUpdates: Failed to prepare differential update',
Errors.toLogFormat(error)
);
this.cachedDifferentialData = undefined;
}
2022-02-24 21:01:41 +00:00
}
}
return {
fileName,
size: getSize(parsedYaml, fileName),
version,
sha512,
differentialData,
vendor,
2022-02-24 21:01:41 +00:00
};
}
private async getLatestCachedInstaller(
extension: string
): Promise<string | undefined> {
const cacheDir = await createUpdateCacheDirIfNeeded();
const oldFiles = (await readdir(cacheDir)).map(fileName => {
return join(cacheDir, fileName);
});
return oldFiles.find(fileName => extname(fileName) === extension);
}
private async downloadUpdate(
2022-02-24 21:01:41 +00:00
{ fileName, sha512, differentialData }: UpdateInformationType,
mode: DownloadMode
2022-03-03 22:34:51 +00:00
): Promise<DownloadUpdateResultType | undefined> {
const baseUrl = getUpdatesBase();
const updateFileUrl = `${baseUrl}/${fileName}`;
const updateOnProgress = mode !== DownloadMode.Automatic;
const signatureFileName = getSignatureFileName(fileName);
2022-02-24 21:01:41 +00:00
const blockMapFileName = getBlockMapFileName(fileName);
const signatureUrl = `${baseUrl}/${signatureFileName}`;
2022-02-24 21:01:41 +00:00
const blockMapUrl = `${baseUrl}/${blockMapFileName}`;
2022-03-03 22:34:51 +00:00
let cacheDir = await createUpdateCacheDirIfNeeded();
2022-02-24 21:01:41 +00:00
const targetUpdatePath = join(cacheDir, fileName);
2022-03-03 22:34:51 +00:00
const tempDir = await createTempDir();
const tempUpdatePath = join(tempDir, fileName);
const tempBlockMapPath = join(tempDir, blockMapFileName);
// If true - we will attempt to install from a temporary directory.
let tempPathFailover = false;
try {
2022-02-24 21:01:41 +00:00
validatePath(cacheDir, targetUpdatePath);
2022-03-03 22:34:51 +00:00
validatePath(tempDir, tempUpdatePath);
validatePath(tempDir, tempBlockMapPath);
this.logger.info(`downloadUpdate: Downloading signature ${signatureUrl}`);
2022-03-03 22:34:51 +00:00
const signature = Buffer.from(
2024-03-20 18:05:10 +00:00
await got(signatureUrl, await getGotOptions()).text(),
2022-03-03 22:34:51 +00:00
'hex'
);
if (differentialData) {
this.logger.info(`downloadUpdate: Saving blockmap ${blockMapUrl}`);
2022-03-03 22:34:51 +00:00
await writeFile(tempBlockMapPath, differentialData.newBlockMap);
} else {
try {
this.logger.info(
`downloadUpdate: Downloading blockmap ${blockMapUrl}`
);
2024-03-20 18:05:10 +00:00
const blockMap = await got(
blockMapUrl,
await getGotOptions()
).buffer();
2022-03-03 22:34:51 +00:00
await writeFile(tempBlockMapPath, blockMap);
} catch (error) {
this.logger.warn(
'downloadUpdate: Failed to download blockmap, continuing',
Errors.toLogFormat(error)
);
}
2022-02-24 21:01:41 +00:00
}
2022-02-24 21:01:41 +00:00
let gotUpdate = false;
if (!gotUpdate && (await pathExists(targetUpdatePath))) {
const checkResult = await checkIntegrity(targetUpdatePath, sha512);
if (checkResult.ok) {
this.logger.info(
`downloadUpdate: Not downloading update ${updateFileUrl}, ` +
'local file has the same hash'
);
2022-03-03 22:34:51 +00:00
// Move file into downloads directory
try {
await gracefulRename(this.logger, targetUpdatePath, tempUpdatePath);
2022-03-03 22:34:51 +00:00
gotUpdate = true;
} catch (error) {
this.logger.error(
'downloadUpdate: failed to move already downloaded file',
Errors.toLogFormat(error)
);
}
2022-02-24 21:01:41 +00:00
} else {
this.logger.error(
'downloadUpdate: integrity check failure',
checkResult.error
);
}
}
const isDifferentialEnabled =
differentialData && mode !== DownloadMode.FullOnly;
if (!gotUpdate && isDifferentialEnabled) {
2022-02-24 21:01:41 +00:00
this.logger.info(
`downloadUpdate: Downloading differential update ${updateFileUrl}`
);
2022-02-24 21:01:41 +00:00
try {
2022-03-03 22:34:51 +00:00
await downloadDifferentialData(tempUpdatePath, differentialData, {
statusCallback: updateOnProgress
? this.throttledSendDownloadingUpdate
: undefined,
logger: this.logger,
});
2022-02-24 21:01:41 +00:00
gotUpdate = true;
} catch (error) {
this.logger.error(
'downloadUpdate: Failed to apply differential update',
Errors.toLogFormat(error)
);
}
}
const isFullEnabled = mode !== DownloadMode.DifferentialOnly;
if (!gotUpdate && isFullEnabled) {
2022-02-24 21:01:41 +00:00
this.logger.info(
`downloadUpdate: Downloading full update ${updateFileUrl}`
);
2022-03-03 22:34:51 +00:00
// We could have failed to update differentially due to low free disk
// space. Remove all cached updates since we are doing a full download
// anyway.
2023-03-02 17:57:36 +00:00
await gracefulRimraf(this.logger, cacheDir);
2022-03-03 22:34:51 +00:00
cacheDir = await createUpdateCacheDirIfNeeded();
2022-02-24 21:01:41 +00:00
await this.downloadAndReport(
updateFileUrl,
2022-03-03 22:34:51 +00:00
tempUpdatePath,
2022-02-24 21:01:41 +00:00
updateOnProgress
);
gotUpdate = true;
}
if (!gotUpdate) {
return undefined;
}
2022-03-04 19:59:47 +00:00
this.logger.info(
'downloadUpdate: Downloaded update, moving into cache dir'
);
2022-03-03 22:34:51 +00:00
// Backup old files
2022-03-04 19:59:47 +00:00
const restoreDir = await getTempDir();
await gracefulRename(this.logger, cacheDir, restoreDir);
2022-03-03 22:34:51 +00:00
// Move the files into the final position
2022-02-24 21:01:41 +00:00
try {
await gracefulRename(this.logger, tempDir, cacheDir);
2022-03-03 22:34:51 +00:00
} catch (error) {
try {
// Attempt to restore old files
await gracefulRename(this.logger, restoreDir, cacheDir);
} catch (restoreError) {
this.logger.warn(
'downloadUpdate: Failed to restore from backup folder, ignoring',
Errors.toLogFormat(restoreError)
);
}
2022-03-03 22:34:51 +00:00
this.logger.warn(
'downloadUpdate: running update from a temporary folder due to error',
Errors.toLogFormat(error)
);
tempPathFailover = true;
return { updateFilePath: tempUpdatePath, signature };
}
2022-03-03 22:34:51 +00:00
2022-03-04 19:59:47 +00:00
try {
2023-03-02 17:57:36 +00:00
await deleteTempDir(this.logger, restoreDir);
2022-03-04 19:59:47 +00:00
} catch (error) {
this.logger.warn(
'downloadUpdate: Failed to remove backup folder, ignoring',
Errors.toLogFormat(error)
);
}
2022-03-03 22:34:51 +00:00
return { updateFilePath: targetUpdatePath, signature };
} finally {
if (!tempPathFailover) {
2023-03-02 17:57:36 +00:00
await deleteTempDir(this.logger, tempDir);
}
}
}
2022-02-24 21:01:41 +00:00
private async downloadAndReport(
updateFileUrl: string,
targetUpdatePath: string,
updateOnProgress = false
): Promise<void> {
2024-03-20 18:05:10 +00:00
const downloadStream = got.stream(updateFileUrl, await getGotOptions());
2022-02-24 21:01:41 +00:00
const writeStream = createWriteStream(targetUpdatePath);
await new Promise<void>((resolve, reject) => {
if (updateOnProgress) {
2022-02-24 21:01:41 +00:00
let downloadedSize = 0;
downloadStream.on('data', data => {
downloadedSize += data.length;
this.throttledSendDownloadingUpdate(downloadedSize);
2022-02-24 21:01:41 +00:00
});
}
downloadStream.on('error', error => {
reject(error);
});
downloadStream.on('end', () => {
resolve();
});
writeStream.on('error', error => {
reject(error);
});
downloadStream.pipe(writeStream);
});
}
private async getAutoDownloadUpdateSetting(): Promise<boolean> {
try {
return await this.settingsChannel.getSettingFromMainWindow(
'autoDownloadUpdate'
);
} catch (error) {
this.logger.warn(
'getAutoDownloadUpdateSetting: Failed to fetch, returning false',
Errors.toLogFormat(error)
);
return false;
}
}
2021-12-03 22:49:15 +00:00
private async getArch(): Promise<typeof process.arch> {
if (process.platform !== 'darwin' || process.arch === 'arm64') {
return process.arch;
}
2023-03-07 17:04:42 +00:00
if (app.runningUnderARM64Translation) {
this.logger.info('updater: running under arm64 translation');
return 'arm64';
2021-12-03 22:49:15 +00:00
}
2023-03-07 17:04:42 +00:00
this.logger.info('updater: not running under arm64 translation');
2021-12-03 22:49:15 +00:00
return process.arch;
}
}
export function validatePath(basePath: string, targetPath: string): void {
const normalized = normalize(targetPath);
if (!isPathInside(normalized, basePath)) {
throw new Error(
`validatePath: Path ${normalized} is not under base path ${basePath}`
);
}
}
// Helper functions
export function getUpdateCheckUrl(): string {
return `${getUpdatesBase()}/${getUpdatesFileName()}`;
}
export function getUpdatesBase(): string {
2021-08-27 20:21:42 +00:00
return config.get('updatesUrl');
}
export function getUpdatesFileName(): string {
2021-08-06 21:21:01 +00:00
const prefix = getChannel();
2021-12-03 22:49:15 +00:00
if (process.platform === 'darwin') {
return `${prefix}-mac.yml`;
}
2020-09-16 19:31:05 +00:00
return `${prefix}.yml`;
}
2021-08-06 21:21:01 +00:00
function getChannel(): string {
const { version } = packageJson;
if (isStaging(version)) {
return 'staging';
}
2021-08-06 21:21:01 +00:00
if (isAlpha(version)) {
return 'alpha';
}
if (isBeta(version)) {
return 'beta';
}
return 'latest';
}
function isVersionNewer(newVersion: string): boolean {
const { version } = packageJson;
return gt(newVersion, version);
}
export function getVersion(info: JSONUpdateSchema): string | null {
2020-09-16 19:31:05 +00:00
return info && info.version;
}
2020-09-16 19:31:05 +00:00
const validFile = /^[A-Za-z0-9.-]+$/;
export function isUpdateFileNameValid(name: string): boolean {
2019-08-02 21:11:10 +00:00
return validFile.test(name);
}
2021-12-03 22:49:15 +00:00
export function getUpdateFileName(
info: JSONUpdateSchema,
platform: typeof process.platform,
arch: typeof process.arch
): string {
2019-08-02 21:11:10 +00:00
if (!info || !info.path) {
throw new Error('getUpdateFileName: No path present in YAML file');
}
2021-12-03 22:49:15 +00:00
let path: string | undefined;
if (platform === 'darwin') {
const { files } = info;
const candidates = files.filter(
({ url }) => url.includes(arch) && url.endsWith('.zip')
);
if (candidates.length === 1) {
path = candidates[0].url;
}
}
path = path ?? info.path;
2019-08-02 21:11:10 +00:00
if (!isUpdateFileNameValid(path)) {
throw new Error(
`getUpdateFileName: Path '${path}' contains invalid characters`
);
}
return path;
}
2022-02-24 21:01:41 +00:00
function getSHA512(
info: JSONUpdateSchema,
fileName: string
): string | undefined {
if (!info || !info.files) {
throw new Error('getSHA512: No files present in YAML file');
}
const foundFile = info.files.find(file => file.url === fileName);
return foundFile?.sha512;
}
function getSize(info: JSONUpdateSchema, fileName: string): number {
if (!info || !info.files) {
2022-02-24 21:01:41 +00:00
throw new Error('getSize: No files present in YAML file');
}
const foundFile = info.files.find(file => file.url === fileName);
return Number(foundFile?.size) || 0;
}
export function parseYaml(yaml: string): JSONUpdateSchema {
return safeLoad(yaml, { schema: FAILSAFE_SCHEMA, json: true });
}
async function getUpdateYaml(): Promise<string> {
const targetUrl = getUpdateCheckUrl();
2024-03-20 18:05:10 +00:00
const body = await got(targetUrl, await getGotOptions()).text();
if (!body) {
throw new Error('Got unexpected response back from update check');
}
2021-10-06 16:25:22 +00:00
return body;
}
function getBaseTempDir() {
// We only use tmpdir() when this code is run outside of an Electron app (as in: tests)
return app ? getTempPath(app.getPath('userData')) : tmpdir();
}
2020-09-16 19:31:05 +00:00
export async function createTempDir(): Promise<string> {
2022-03-04 19:59:47 +00:00
const targetDir = await getTempDir();
await mkdir(targetDir, { recursive: true });
return targetDir;
}
2022-03-04 19:59:47 +00:00
export async function getTempDir(): Promise<string> {
const baseTempDir = getBaseTempDir();
const uniqueName = getGuid();
// Create parent folder if not already present
if (!(await pathExists(baseTempDir))) {
await mkdir(baseTempDir, { recursive: true });
2022-03-04 19:59:47 +00:00
}
return join(baseTempDir, uniqueName);
}
2022-02-24 21:01:41 +00:00
function getUpdateCacheDir() {
// We only use tmpdir() when this code is run outside of an Electron app (as in: tests)
return app ? getUpdateCachePath(app.getPath('userData')) : tmpdir();
}
export async function createUpdateCacheDirIfNeeded(): Promise<string> {
const targetDir = getUpdateCacheDir();
await mkdir(targetDir, { recursive: true });
2022-02-24 21:01:41 +00:00
return targetDir;
}
2023-03-02 17:57:36 +00:00
export async function deleteTempDir(
logger: LoggerType,
targetDir: string
): Promise<void> {
2022-03-03 22:34:51 +00:00
if (await pathExists(targetDir)) {
const pathInfo = await stat(targetDir);
if (!pathInfo.isDirectory()) {
throw new Error(
`deleteTempDir: Cannot delete path '${targetDir}' because it is not a directory`
);
}
}
const baseTempDir = getBaseTempDir();
if (!isPathInside(targetDir, baseTempDir)) {
throw new Error(
`deleteTempDir: Cannot delete path '${targetDir}' since it is not within base temp dir`
);
}
2023-03-02 17:57:36 +00:00
await gracefulRimraf(logger, targetDir);
}
2020-09-16 19:31:05 +00:00
export function getCliOptions<T>(options: ParserConfiguration['options']): T {
const parser = createParser({ options });
const cliOptions = parser.parse(process.argv);
if (cliOptions.help) {
const help = parser.help().trimRight();
console.log(help);
process.exit(0);
}
2021-11-11 22:43:05 +00:00
return cliOptions as unknown as T;
}