Merge signal-1.24.0
# Conflicts: # .github/PULL_REQUEST_TEMPLATE.md # background.html # config/default.json # config/production.json # js/models/conversations.js # js/models/messages.js # js/views/conversation_view.js # js/views/inbox_view.js # js/views/settings_view.js # main.js # package.json # test/index.html # ts/components/conversation/ContactName.tsx # yarn.lockpull/272/head
commit
8808100796
@ -0,0 +1,38 @@
|
||||
<!--
|
||||
Thanks for contributing to the project!
|
||||
Please help us keep this project in good shape by going through this checklist.
|
||||
Replace the empty checkboxes [ ] below with checked ones [X] as they are completed
|
||||
Remember, you can preview this before saving it.
|
||||
-->
|
||||
|
||||
<!-- You can remove this first section if you have contributed before -->
|
||||
|
||||
### First time contributor checklist:
|
||||
|
||||
* [ ] I have read the [README](https://github.com/signalapp/Signal-Desktop/blob/master/README.md) and [Contributor Guidelines](https://github.com/signalapp/Signal-Desktop/blob/master/CONTRIBUTING.md)
|
||||
* [ ] I have signed the [Contributor Licence Agreement](https://signal.org/cla/)
|
||||
|
||||
### Contributor checklist:
|
||||
|
||||
* [ ] My contribution is **not** related to translations. _Please submit translation changes via our [Signal Desktop Transifex project](https://www.transifex.com/signalapp/signal-desktop/)._
|
||||
* [ ] My commits are in nice logical chunks with [good commit messages](http://chris.beams.io/posts/git-commit/)
|
||||
* [ ] My changes are [rebased](https://medium.freecodecamp.org/git-rebase-and-the-golden-rule-explained-70715eccc372) on the latest [`development`](https://github.com/signalapp/Signal-Desktop/tree/development) branch
|
||||
* [ ] A `yarn ready` run passes successfully ([more about tests here](https://github.com/signalapp/Signal-Desktop/blob/master/CONTRIBUTING.md#tests))
|
||||
* [ ] My changes are ready to be shipped to users
|
||||
|
||||
### Description
|
||||
|
||||
<!--
|
||||
Describe briefly what your pull request changes. Focus on the value provided to users.
|
||||
|
||||
Does it address any outstanding issues in this project?
|
||||
https://github.com/signalapp/Signal-Desktop/issues?utf8=%E2%9C%93&q=is%3Aissue
|
||||
Reference an issue with the hash symbol: "#222"
|
||||
If you're fixing it, use something like "Fixes #222"
|
||||
|
||||
Please write a summary of your test approach:
|
||||
- What kind of manual testing did you do?
|
||||
- Did you write any new tests?
|
||||
- What operating systems did you test with? (please use specific versions: http://whatsmyos.com/)
|
||||
- What other devices did you test with? (other Desktop devices, Android, Android Simulator, iOS, iOS Simulator)
|
||||
-->
|
@ -1,89 +0,0 @@
|
||||
const { autoUpdater } = require('electron-updater');
|
||||
const { dialog } = require('electron');
|
||||
|
||||
const config = require('./config');
|
||||
const windowState = require('./window_state');
|
||||
|
||||
const hour = 60 * 60;
|
||||
const autoUpdaterInterval = hour * 1000;
|
||||
|
||||
const RESTART_BUTTON = 0;
|
||||
const LATER_BUTTON = 1;
|
||||
|
||||
function autoUpdateDisabled() {
|
||||
return (
|
||||
process.platform === 'linux' ||
|
||||
process.mas ||
|
||||
config.get('disableAutoUpdate')
|
||||
);
|
||||
}
|
||||
|
||||
async function checkForUpdates() {
|
||||
try {
|
||||
await autoUpdater.checkForUpdates();
|
||||
} catch (error) {
|
||||
console.log('checkForUpdates error:', error.stack);
|
||||
}
|
||||
}
|
||||
|
||||
let showingDialog = false;
|
||||
function showUpdateDialog(mainWindow, messages) {
|
||||
if (showingDialog || !mainWindow) {
|
||||
return;
|
||||
}
|
||||
showingDialog = true;
|
||||
|
||||
const options = {
|
||||
type: 'info',
|
||||
buttons: [
|
||||
messages.autoUpdateRestartButtonLabel.message,
|
||||
messages.autoUpdateLaterButtonLabel.message,
|
||||
],
|
||||
title: messages.autoUpdateNewVersionTitle.message,
|
||||
message: messages.autoUpdateNewVersionMessage.message,
|
||||
detail: messages.autoUpdateNewVersionInstructions.message,
|
||||
defaultId: LATER_BUTTON,
|
||||
cancelId: RESTART_BUTTON,
|
||||
};
|
||||
|
||||
dialog.showMessageBox(mainWindow, options, response => {
|
||||
if (response === RESTART_BUTTON) {
|
||||
// We delay these update calls because they don't seem to work in this
|
||||
// callback - but only if the message box has a parent window.
|
||||
// Fixes this bug: https://github.com/signalapp/Signal-Desktop/issues/1864
|
||||
setTimeout(() => {
|
||||
windowState.markShouldQuit();
|
||||
autoUpdater.quitAndInstall();
|
||||
}, 200);
|
||||
}
|
||||
|
||||
showingDialog = false;
|
||||
});
|
||||
}
|
||||
|
||||
function onError(error) {
|
||||
console.log('Got an error while updating:', error.stack);
|
||||
}
|
||||
|
||||
function initialize(getMainWindow, messages) {
|
||||
if (!messages) {
|
||||
throw new Error('auto-update initialize needs localized messages');
|
||||
}
|
||||
|
||||
if (autoUpdateDisabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
autoUpdater.addListener('update-downloaded', () => {
|
||||
showUpdateDialog(getMainWindow(), messages);
|
||||
});
|
||||
autoUpdater.addListener('error', onError);
|
||||
|
||||
checkForUpdates();
|
||||
|
||||
setInterval(checkForUpdates, autoUpdaterInterval);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
initialize,
|
||||
};
|
@ -0,0 +1,2 @@
|
||||
export function markShouldQuit(): void;
|
||||
export function shouldQuit(): void;
|
@ -1,5 +1,4 @@
|
||||
{
|
||||
"storageProfile": "development",
|
||||
"disableAutoUpdate": true,
|
||||
"openDevTools": true
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
{
|
||||
"storageProfile": "staging",
|
||||
"disableAutoUpdate": true,
|
||||
"openDevTools": true
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
{
|
||||
"storageProfile": "test",
|
||||
"disableAutoUpdate": true,
|
||||
"openDevTools": false
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
{
|
||||
"storageProfile": "test",
|
||||
"disableAutoUpdate": true,
|
||||
"openDevTools": false
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,158 @@
|
||||
/* vim: ts=4:sw=4:expandtab */
|
||||
var Internal = global.Internal || {};
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// Insert some bytes into the emscripten memory and return a pointer
|
||||
function _allocate(bytes) {
|
||||
var address = Module._malloc(bytes.length);
|
||||
Module.HEAPU8.set(bytes, address);
|
||||
|
||||
return address;
|
||||
}
|
||||
|
||||
function _readBytes(address, length, array) {
|
||||
array.set(Module.HEAPU8.subarray(address, address + length));
|
||||
}
|
||||
|
||||
var basepoint = new Uint8Array(32);
|
||||
basepoint[0] = 9;
|
||||
|
||||
Internal.curve25519 = {
|
||||
keyPair: function(privKey) {
|
||||
var priv = new Uint8Array(privKey);
|
||||
priv[0] &= 248;
|
||||
priv[31] &= 127;
|
||||
priv[31] |= 64;
|
||||
|
||||
// Where to store the result
|
||||
var publicKey_ptr = Module._malloc(32);
|
||||
|
||||
// Get a pointer to the private key
|
||||
var privateKey_ptr = _allocate(priv);
|
||||
|
||||
// The basepoint for generating public keys
|
||||
var basepoint_ptr = _allocate(basepoint);
|
||||
|
||||
// The return value is just 0, the operation is done in place
|
||||
var err = Module._curve25519_donna(
|
||||
publicKey_ptr,
|
||||
privateKey_ptr,
|
||||
basepoint_ptr
|
||||
);
|
||||
|
||||
var res = new Uint8Array(32);
|
||||
_readBytes(publicKey_ptr, 32, res);
|
||||
|
||||
Module._free(publicKey_ptr);
|
||||
Module._free(privateKey_ptr);
|
||||
Module._free(basepoint_ptr);
|
||||
|
||||
return { pubKey: res.buffer, privKey: priv.buffer };
|
||||
},
|
||||
sharedSecret: function(pubKey, privKey) {
|
||||
// Where to store the result
|
||||
var sharedKey_ptr = Module._malloc(32);
|
||||
|
||||
// Get a pointer to our private key
|
||||
var privateKey_ptr = _allocate(new Uint8Array(privKey));
|
||||
|
||||
// Get a pointer to their public key, the basepoint when you're
|
||||
// generating a shared secret
|
||||
var basepoint_ptr = _allocate(new Uint8Array(pubKey));
|
||||
|
||||
// Return value is 0 here too of course
|
||||
var err = Module._curve25519_donna(
|
||||
sharedKey_ptr,
|
||||
privateKey_ptr,
|
||||
basepoint_ptr
|
||||
);
|
||||
|
||||
var res = new Uint8Array(32);
|
||||
_readBytes(sharedKey_ptr, 32, res);
|
||||
|
||||
Module._free(sharedKey_ptr);
|
||||
Module._free(privateKey_ptr);
|
||||
Module._free(basepoint_ptr);
|
||||
|
||||
return res.buffer;
|
||||
},
|
||||
sign: function(privKey, message) {
|
||||
// Where to store the result
|
||||
var signature_ptr = Module._malloc(64);
|
||||
|
||||
// Get a pointer to our private key
|
||||
var privateKey_ptr = _allocate(new Uint8Array(privKey));
|
||||
|
||||
// Get a pointer to the message
|
||||
var message_ptr = _allocate(new Uint8Array(message));
|
||||
|
||||
var err = Module._curve25519_sign(
|
||||
signature_ptr,
|
||||
privateKey_ptr,
|
||||
message_ptr,
|
||||
message.byteLength
|
||||
);
|
||||
|
||||
var res = new Uint8Array(64);
|
||||
_readBytes(signature_ptr, 64, res);
|
||||
|
||||
Module._free(signature_ptr);
|
||||
Module._free(privateKey_ptr);
|
||||
Module._free(message_ptr);
|
||||
|
||||
return res.buffer;
|
||||
},
|
||||
verify: function(pubKey, message, sig) {
|
||||
// Get a pointer to their public key
|
||||
var publicKey_ptr = _allocate(new Uint8Array(pubKey));
|
||||
|
||||
// Get a pointer to the signature
|
||||
var signature_ptr = _allocate(new Uint8Array(sig));
|
||||
|
||||
// Get a pointer to the message
|
||||
var message_ptr = _allocate(new Uint8Array(message));
|
||||
|
||||
var res = Module._curve25519_verify(
|
||||
signature_ptr,
|
||||
publicKey_ptr,
|
||||
message_ptr,
|
||||
message.byteLength
|
||||
);
|
||||
|
||||
Module._free(publicKey_ptr);
|
||||
Module._free(signature_ptr);
|
||||
Module._free(message_ptr);
|
||||
|
||||
return res !== 0;
|
||||
},
|
||||
};
|
||||
|
||||
Internal.curve25519_async = {
|
||||
keyPair: function(privKey) {
|
||||
return new Promise(function(resolve) {
|
||||
resolve(Internal.curve25519.keyPair(privKey));
|
||||
});
|
||||
},
|
||||
sharedSecret: function(pubKey, privKey) {
|
||||
return new Promise(function(resolve) {
|
||||
resolve(Internal.curve25519.sharedSecret(pubKey, privKey));
|
||||
});
|
||||
},
|
||||
sign: function(privKey, message) {
|
||||
return new Promise(function(resolve) {
|
||||
resolve(Internal.curve25519.sign(privKey, message));
|
||||
});
|
||||
},
|
||||
verify: function(pubKey, message, sig) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
if (Internal.curve25519.verify(pubKey, message, sig)) {
|
||||
reject(new Error('Invalid signature'));
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
})();
|
@ -0,0 +1,65 @@
|
||||
// eslint-disable-next-line func-names
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
window.Whisper = window.Whisper || {};
|
||||
|
||||
const messageLookup = Object.create(null);
|
||||
|
||||
const SECOND = 1000;
|
||||
const MINUTE = SECOND * 60;
|
||||
const FIVE_MINUTES = MINUTE * 5;
|
||||
const HOUR = MINUTE * 60;
|
||||
|
||||
function register(id, message) {
|
||||
const existing = messageLookup[id];
|
||||
if (existing) {
|
||||
messageLookup[id] = {
|
||||
message: existing.message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
return existing.message;
|
||||
}
|
||||
|
||||
messageLookup[id] = {
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function unregister(id) {
|
||||
delete messageLookup[id];
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
const messages = Object.values(messageLookup);
|
||||
const now = Date.now();
|
||||
|
||||
for (let i = 0, max = messages.length; i < max; i += 1) {
|
||||
const { message, timestamp } = messages[i];
|
||||
const conversation = message.getConversation();
|
||||
|
||||
if (
|
||||
now - timestamp > FIVE_MINUTES &&
|
||||
(!conversation || !conversation.messageCollection.length)
|
||||
) {
|
||||
delete messageLookup[message.id];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _get() {
|
||||
return messageLookup;
|
||||
}
|
||||
|
||||
setInterval(cleanup, HOUR);
|
||||
|
||||
window.MessageController = {
|
||||
register,
|
||||
unregister,
|
||||
cleanup,
|
||||
_get,
|
||||
};
|
||||
})();
|
@ -0,0 +1,77 @@
|
||||
import { assert } from 'chai';
|
||||
|
||||
import { getUpdateFileName, getVersion } from '../../updater/common';
|
||||
|
||||
describe('updater/signatures', () => {
|
||||
const windows = `version: 1.23.2
|
||||
files:
|
||||
- url: signal-desktop-win-1.23.2.exe
|
||||
sha512: hhK+cVAb+QOK/Ln0RBcq8Rb1iPcUC0KZeT4NwLB25PMGoPmakY27XE1bXq4QlkASJN1EkYTbKf3oUJtcllziyQ==
|
||||
size: 92020776
|
||||
path: signal-desktop-win-1.23.2.exe
|
||||
sha512: hhK+cVAb+QOK/Ln0RBcq8Rb1iPcUC0KZeT4NwLB25PMGoPmakY27XE1bXq4QlkASJN1EkYTbKf3oUJtcllziyQ==
|
||||
releaseDate: '2019-03-29T16:58:08.210Z'
|
||||
`;
|
||||
const mac = `version: 1.23.2
|
||||
files:
|
||||
- url: signal-desktop-mac-1.23.2.zip
|
||||
sha512: f4pPo3WulTVi9zBWGsJPNIlvPOTCxPibPPDmRFDoXMmFm6lqJpXZQ9DSWMJumfc4BRp4y/NTQLGYI6b4WuJwhg==
|
||||
size: 105179791
|
||||
blockMapSize: 111109
|
||||
path: signal-desktop-mac-1.23.2.zip
|
||||
sha512: f4pPo3WulTVi9zBWGsJPNIlvPOTCxPibPPDmRFDoXMmFm6lqJpXZQ9DSWMJumfc4BRp4y/NTQLGYI6b4WuJwhg==
|
||||
releaseDate: '2019-03-29T16:57:16.997Z'
|
||||
`;
|
||||
const windowsBeta = `version: 1.23.2-beta.1
|
||||
files:
|
||||
- url: signal-desktop-beta-win-1.23.2-beta.1.exe
|
||||
sha512: ZHM1F3y/Y6ulP5NhbFuh7t2ZCpY4lD9BeBhPV+g2B/0p/66kp0MJDeVxTgjR49OakwpMAafA1d6y2QBail4hSQ==
|
||||
size: 92028656
|
||||
path: signal-desktop-beta-win-1.23.2-beta.1.exe
|
||||
sha512: ZHM1F3y/Y6ulP5NhbFuh7t2ZCpY4lD9BeBhPV+g2B/0p/66kp0MJDeVxTgjR49OakwpMAafA1d6y2QBail4hSQ==
|
||||
releaseDate: '2019-03-29T01:56:00.544Z'
|
||||
`;
|
||||
const macBeta = `version: 1.23.2-beta.1
|
||||
files:
|
||||
- url: signal-desktop-beta-mac-1.23.2-beta.1.zip
|
||||
sha512: h/01N0DD5Jw2Q6M1n4uLGLTCrMFxcn8QOPtLR3HpABsf3w9b2jFtKb56/2cbuJXP8ol8TkTDWKnRV6mnqnLBDw==
|
||||
size: 105182398
|
||||
blockMapSize: 110894
|
||||
path: signal-desktop-beta-mac-1.23.2-beta.1.zip
|
||||
sha512: h/01N0DD5Jw2Q6M1n4uLGLTCrMFxcn8QOPtLR3HpABsf3w9b2jFtKb56/2cbuJXP8ol8TkTDWKnRV6mnqnLBDw==
|
||||
releaseDate: '2019-03-29T01:53:23.881Z'
|
||||
`;
|
||||
|
||||
describe('#getVersion', () => {
|
||||
it('successfully gets version', () => {
|
||||
const expected = '1.23.2';
|
||||
assert.strictEqual(getVersion(windows), expected);
|
||||
assert.strictEqual(getVersion(mac), expected);
|
||||
|
||||
const expectedBeta = '1.23.2-beta.1';
|
||||
assert.strictEqual(getVersion(windowsBeta), expectedBeta);
|
||||
assert.strictEqual(getVersion(macBeta), expectedBeta);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#getUpdateFileName', () => {
|
||||
it('successfully gets version', () => {
|
||||
assert.strictEqual(
|
||||
getUpdateFileName(windows),
|
||||
'signal-desktop-win-1.23.2.exe'
|
||||
);
|
||||
assert.strictEqual(
|
||||
getUpdateFileName(mac),
|
||||
'signal-desktop-mac-1.23.2.zip'
|
||||
);
|
||||
assert.strictEqual(
|
||||
getUpdateFileName(windowsBeta),
|
||||
'signal-desktop-beta-win-1.23.2-beta.1.exe'
|
||||
);
|
||||
assert.strictEqual(
|
||||
getUpdateFileName(macBeta),
|
||||
'signal-desktop-beta-mac-1.23.2-beta.1.zip'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
@ -0,0 +1,14 @@
|
||||
import { assert } from 'chai';
|
||||
|
||||
import { keyPair, sign, verify } from '../../updater/curve';
|
||||
|
||||
describe('updater/curve', () => {
|
||||
it('roundtrips', () => {
|
||||
const message = Buffer.from('message');
|
||||
const { publicKey, privateKey } = keyPair();
|
||||
const signature = sign(privateKey, message);
|
||||
const verified = verify(publicKey, message, signature);
|
||||
|
||||
assert.strictEqual(verified, true);
|
||||
});
|
||||
});
|
@ -0,0 +1,206 @@
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { assert } from 'chai';
|
||||
import { copy } from 'fs-extra';
|
||||
|
||||
import {
|
||||
_getFileHash,
|
||||
getSignaturePath,
|
||||
loadHexFromPath,
|
||||
verifySignature,
|
||||
writeHexToPath,
|
||||
writeSignature,
|
||||
} from '../../updater/signature';
|
||||
import { createTempDir, deleteTempDir } from '../../updater/common';
|
||||
import { keyPair } from '../../updater/curve';
|
||||
|
||||
describe('updater/signatures', () => {
|
||||
it('_getFileHash returns correct hash', async () => {
|
||||
const filePath = join(__dirname, '../../../fixtures/ghost-kitty.mp4');
|
||||
const expected =
|
||||
'7bc77f27d92d00b4a1d57c480ca86dacc43d57bc318339c92119d1fbf6b557a5';
|
||||
|
||||
const hash = await _getFileHash(filePath);
|
||||
|
||||
assert.strictEqual(expected, Buffer.from(hash).toString('hex'));
|
||||
});
|
||||
|
||||
it('roundtrips binary file writes', async () => {
|
||||
let tempDir;
|
||||
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
|
||||
const path = join(tempDir, 'something.bin');
|
||||
const { publicKey } = keyPair();
|
||||
|
||||
await writeHexToPath(path, publicKey);
|
||||
|
||||
const fromDisk = await loadHexFromPath(path);
|
||||
|
||||
assert.strictEqual(
|
||||
Buffer.from(fromDisk).compare(Buffer.from(publicKey)),
|
||||
0
|
||||
);
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('roundtrips signature', async () => {
|
||||
let tempDir;
|
||||
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
|
||||
const version = 'v1.23.2';
|
||||
const sourcePath = join(__dirname, '../../../fixtures/ghost-kitty.mp4');
|
||||
const updatePath = join(tempDir, 'ghost-kitty.mp4');
|
||||
await copy(sourcePath, updatePath);
|
||||
|
||||
const privateKeyPath = join(tempDir, 'private.key');
|
||||
const { publicKey, privateKey } = keyPair();
|
||||
await writeHexToPath(privateKeyPath, privateKey);
|
||||
|
||||
await writeSignature(updatePath, version, privateKeyPath);
|
||||
|
||||
const signaturePath = getSignaturePath(updatePath);
|
||||
assert.strictEqual(existsSync(signaturePath), true);
|
||||
|
||||
const verified = await verifySignature(updatePath, version, publicKey);
|
||||
assert.strictEqual(verified, true);
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('fails signature verification if version changes', async () => {
|
||||
let tempDir;
|
||||
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
|
||||
const version = 'v1.23.2';
|
||||
const brokenVersion = 'v1.23.3';
|
||||
|
||||
const sourcePath = join(__dirname, '../../../fixtures/ghost-kitty.mp4');
|
||||
const updatePath = join(tempDir, 'ghost-kitty.mp4');
|
||||
await copy(sourcePath, updatePath);
|
||||
|
||||
const privateKeyPath = join(tempDir, 'private.key');
|
||||
const { publicKey, privateKey } = keyPair();
|
||||
await writeHexToPath(privateKeyPath, privateKey);
|
||||
|
||||
await writeSignature(updatePath, version, privateKeyPath);
|
||||
|
||||
const verified = await verifySignature(
|
||||
updatePath,
|
||||
brokenVersion,
|
||||
publicKey
|
||||
);
|
||||
assert.strictEqual(verified, false);
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('fails signature verification if signature tampered with', async () => {
|
||||
let tempDir;
|
||||
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
|
||||
const version = 'v1.23.2';
|
||||
|
||||
const sourcePath = join(__dirname, '../../../fixtures/ghost-kitty.mp4');
|
||||
const updatePath = join(tempDir, 'ghost-kitty.mp4');
|
||||
await copy(sourcePath, updatePath);
|
||||
|
||||
const privateKeyPath = join(tempDir, 'private.key');
|
||||
const { publicKey, privateKey } = keyPair();
|
||||
await writeHexToPath(privateKeyPath, privateKey);
|
||||
|
||||
await writeSignature(updatePath, version, privateKeyPath);
|
||||
|
||||
const signaturePath = getSignaturePath(updatePath);
|
||||
const signature = Buffer.from(await loadHexFromPath(signaturePath));
|
||||
signature[4] += 3;
|
||||
await writeHexToPath(signaturePath, signature);
|
||||
|
||||
const verified = await verifySignature(updatePath, version, publicKey);
|
||||
assert.strictEqual(verified, false);
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('fails signature verification if binary file tampered with', async () => {
|
||||
let tempDir;
|
||||
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
|
||||
const version = 'v1.23.2';
|
||||
|
||||
const sourcePath = join(__dirname, '../../../fixtures/ghost-kitty.mp4');
|
||||
const updatePath = join(tempDir, 'ghost-kitty.mp4');
|
||||
await copy(sourcePath, updatePath);
|
||||
|
||||
const privateKeyPath = join(tempDir, 'private.key');
|
||||
const { publicKey, privateKey } = keyPair();
|
||||
await writeHexToPath(privateKeyPath, privateKey);
|
||||
|
||||
await writeSignature(updatePath, version, privateKeyPath);
|
||||
|
||||
const brokenSourcePath = join(
|
||||
__dirname,
|
||||
'../../../fixtures/pixabay-Soap-Bubble-7141.mp4'
|
||||
);
|
||||
await copy(brokenSourcePath, updatePath);
|
||||
|
||||
const verified = await verifySignature(updatePath, version, publicKey);
|
||||
assert.strictEqual(verified, false);
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('fails signature verification if signed by different key', async () => {
|
||||
let tempDir;
|
||||
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
|
||||
const version = 'v1.23.2';
|
||||
|
||||
const sourcePath = join(__dirname, '../../../fixtures/ghost-kitty.mp4');
|
||||
const updatePath = join(tempDir, 'ghost-kitty.mp4');
|
||||
await copy(sourcePath, updatePath);
|
||||
|
||||
const privateKeyPath = join(tempDir, 'private.key');
|
||||
const { publicKey } = keyPair();
|
||||
const { privateKey } = keyPair();
|
||||
await writeHexToPath(privateKeyPath, privateKey);
|
||||
|
||||
await writeSignature(updatePath, version, privateKeyPath);
|
||||
|
||||
const verified = await verifySignature(updatePath, version, publicKey);
|
||||
assert.strictEqual(verified, false);
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
@ -0,0 +1,323 @@
|
||||
import {
|
||||
createWriteStream,
|
||||
statSync,
|
||||
writeFile as writeFileCallback,
|
||||
} from 'fs';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
|
||||
// @ts-ignore
|
||||
import { createParser } from 'dashdash';
|
||||
// @ts-ignore
|
||||
import ProxyAgent from 'proxy-agent';
|
||||
import { FAILSAFE_SCHEMA, safeLoad } from 'js-yaml';
|
||||
import { gt } from 'semver';
|
||||
import { get as getFromConfig } from 'config';
|
||||
import { get, GotOptions, stream } from 'got';
|
||||
import { v4 as getGuid } from 'uuid';
|
||||
import pify from 'pify';
|
||||
import mkdirp from 'mkdirp';
|
||||
import rimraf from 'rimraf';
|
||||
import { app, BrowserWindow, dialog } from 'electron';
|
||||
|
||||
// @ts-ignore
|
||||
import * as packageJson from '../../package.json';
|
||||
import { getSignatureFileName } from './signature';
|
||||
|
||||
export type MessagesType = {
|
||||
[key: string]: {
|
||||
message: string;
|
||||
description?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type LogFunction = (...args: Array<any>) => void;
|
||||
|
||||
export type LoggerType = {
|
||||
fatal: LogFunction;
|
||||
error: LogFunction;
|
||||
warn: LogFunction;
|
||||
info: LogFunction;
|
||||
debug: LogFunction;
|
||||
trace: LogFunction;
|
||||
};
|
||||
|
||||
const writeFile = pify(writeFileCallback);
|
||||
const mkdirpPromise = pify(mkdirp);
|
||||
const rimrafPromise = pify(rimraf);
|
||||
const { platform } = process;
|
||||
|
||||
export async function checkForUpdates(
|
||||
logger: LoggerType
|
||||
): Promise<{
|
||||
fileName: string;
|
||||
version: string;
|
||||
} | null> {
|
||||
const yaml = await getUpdateYaml();
|
||||
const version = getVersion(yaml);
|
||||
|
||||
if (!version) {
|
||||
logger.warn('checkForUpdates: no version extracted from downloaded yaml');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isVersionNewer(version)) {
|
||||
logger.info(`checkForUpdates: found newer version ${version}`);
|
||||
|
||||
return {
|
||||
fileName: getUpdateFileName(yaml),
|
||||
version,
|
||||
};
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`checkForUpdates: ${version} is not newer; no new update available`
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function downloadUpdate(
|
||||
fileName: string,
|
||||
logger: LoggerType
|
||||
): Promise<string> {
|
||||
const baseUrl = getUpdatesBase();
|
||||
const updateFileUrl = `${baseUrl}/${fileName}`;
|
||||
|
||||
const signatureFileName = getSignatureFileName(fileName);
|
||||
const signatureUrl = `${baseUrl}/${signatureFileName}`;
|
||||
|
||||
let tempDir;
|
||||
try {
|
||||
tempDir = await createTempDir();
|
||||
const targetUpdatePath = join(tempDir, fileName);
|
||||
const targetSignaturePath = join(tempDir, getSignatureFileName(fileName));
|
||||
|
||||
logger.info(`downloadUpdate: Downloading ${signatureUrl}`);
|
||||
const { body } = await get(signatureUrl, getGotOptions());
|
||||
await writeFile(targetSignaturePath, body);
|
||||
|
||||
logger.info(`downloadUpdate: Downloading ${updateFileUrl}`);
|
||||
const downloadStream = stream(updateFileUrl, getGotOptions());
|
||||
const writeStream = createWriteStream(targetUpdatePath);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
downloadStream.on('error', error => {
|
||||
reject(error);
|
||||
});
|
||||
downloadStream.on('end', () => {
|
||||
resolve();
|
||||
});
|
||||
|
||||
writeStream.on('error', error => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
downloadStream.pipe(writeStream);
|
||||
});
|
||||
|
||||
return targetUpdatePath;
|
||||
} catch (error) {
|
||||
if (tempDir) {
|
||||
await deleteTempDir(tempDir);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function showUpdateDialog(
|
||||
mainWindow: BrowserWindow,
|
||||
messages: MessagesType
|
||||
): Promise<boolean> {
|
||||
const RESTART_BUTTON = 0;
|
||||
const LATER_BUTTON = 1;
|
||||
const options = {
|
||||
type: 'info',
|
||||
buttons: [
|
||||
messages.autoUpdateRestartButtonLabel.message,
|
||||
messages.autoUpdateLaterButtonLabel.message,
|
||||
],
|
||||
title: messages.autoUpdateNewVersionTitle.message,
|
||||
message: messages.autoUpdateNewVersionMessage.message,
|
||||
detail: messages.autoUpdateNewVersionInstructions.message,
|
||||
defaultId: LATER_BUTTON,
|
||||
cancelId: RESTART_BUTTON,
|
||||
};
|
||||
|
||||
return new Promise(resolve => {
|
||||
dialog.showMessageBox(mainWindow, options, response => {
|
||||
if (response === RESTART_BUTTON) {
|
||||
// It's key to delay any install calls here because they don't seem to work inside this
|
||||
// callback - but only if the message box has a parent window.
|
||||
// Fixes this: https://github.com/signalapp/Signal-Desktop/issues/1864
|
||||
resolve(true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function showCannotUpdateDialog(
|
||||
mainWindow: BrowserWindow,
|
||||
messages: MessagesType
|
||||
): Promise<boolean> {
|
||||
const options = {
|
||||
type: 'error',
|
||||
buttons: [messages.ok.message],
|
||||
title: messages.cannotUpdate.message,
|
||||
message: messages.cannotUpdateDetail.message,
|
||||
};
|
||||
|
||||
return new Promise(resolve => {
|
||||
dialog.showMessageBox(mainWindow, options, () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
export function getUpdateCheckUrl(): string {
|
||||
return `${getUpdatesBase()}/${getUpdatesFileName()}`;
|
||||
}
|
||||
|
||||
export function getUpdatesBase(): string {
|
||||
return getFromConfig('updatesUrl');
|
||||
}
|
||||
export function getCertificateAuthority(): string {
|
||||
return getFromConfig('certificateAuthority');
|
||||
}
|
||||
export function getProxyUrl(): string | undefined {
|
||||
return process.env.HTTPS_PROXY || process.env.https_proxy;
|
||||
}
|
||||
|
||||
export function getUpdatesFileName(): string {
|
||||
const prefix = isBetaChannel() ? 'beta' : 'latest';
|
||||
|
||||
if (platform === 'darwin') {
|
||||
return `${prefix}-mac.yml`;
|
||||
} else {
|
||||
return `${prefix}.yml`;
|
||||
}
|
||||
}
|
||||
|
||||
const hasBeta = /beta/i;
|
||||
function isBetaChannel(): boolean {
|
||||
return hasBeta.test(packageJson.version);
|
||||
}
|
||||
|
||||
function isVersionNewer(newVersion: string): boolean {
|
||||
const { version } = packageJson;
|
||||
|
||||
return gt(newVersion, version);
|
||||
}
|
||||
|
||||
export function getVersion(yaml: string): string | undefined {
|
||||
const info = parseYaml(yaml);
|
||||
|
||||
if (info && info.version) {
|
||||
return info.version;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
export function getUpdateFileName(yaml: string) {
|
||||
const info = parseYaml(yaml);
|
||||
|
||||
if (info && info.path) {
|
||||
return info.path;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
function parseYaml(yaml: string): any {
|
||||
return safeLoad(yaml, { schema: FAILSAFE_SCHEMA, json: true });
|
||||
}
|
||||
|
||||
async function getUpdateYaml(): Promise<string> {
|
||||
const targetUrl = getUpdateCheckUrl();
|
||||
const { body } = await get(targetUrl, getGotOptions());
|
||||
|
||||
if (!body) {
|
||||
throw new Error('Got unexpected response back from update check');
|
||||
}
|
||||
|
||||
return body.toString('utf8');
|
||||
}
|
||||
|
||||
function getGotOptions(): GotOptions<null> {
|
||||
const ca = getCertificateAuthority();
|
||||
const proxyUrl = getProxyUrl();
|
||||
const agent = proxyUrl ? new ProxyAgent(proxyUrl) : undefined;
|
||||
|
||||
return {
|
||||
agent,
|
||||
ca,
|
||||
headers: {
|
||||
'Cache-Control': 'no-cache',
|
||||
'User-Agent': 'Signal Desktop (+https://signal.org/download)',
|
||||
},
|
||||
useElectronNet: false,
|
||||
};
|
||||
}
|
||||
|
||||
function getBaseTempDir() {
|
||||
// We only use tmpdir() when this code is run outside of an Electron app (as in: tests)
|
||||
return app ? join(app.getPath('userData'), 'temp') : tmpdir();
|
||||
}
|
||||
|
||||
export async function createTempDir() {
|
||||
const baseTempDir = getBaseTempDir();
|
||||
const uniqueName = getGuid();
|
||||
const targetDir = join(baseTempDir, uniqueName);
|
||||
await mkdirpPromise(targetDir);
|
||||
|
||||
return targetDir;
|
||||
}
|
||||
|
||||
export async function deleteTempDir(targetDir: string) {
|
||||
const pathInfo = statSync(targetDir);
|
||||
if (!pathInfo.isDirectory()) {
|
||||
throw new Error(
|
||||
`deleteTempDir: Cannot delete path '${targetDir}' because it is not a directory`
|
||||
);
|
||||
}
|
||||
|
||||
const baseTempDir = getBaseTempDir();
|
||||
if (!targetDir.startsWith(baseTempDir)) {
|
||||
throw new Error(
|
||||
`deleteTempDir: Cannot delete path '${targetDir}' since it is not within base temp dir`
|
||||
);
|
||||
}
|
||||
|
||||
await rimrafPromise(targetDir);
|
||||
}
|
||||
|
||||
export function getPrintableError(error: Error) {
|
||||
return error && error.stack ? error.stack : error;
|
||||
}
|
||||
|
||||
export async function deleteBaseTempDir() {
|
||||
const baseTempDir = getBaseTempDir();
|
||||
await rimrafPromise(baseTempDir);
|
||||
}
|
||||
|
||||
export function getCliOptions<T>(options: any): T {
|
||||
const parser = createParser({ options });
|
||||
const cliOptions = parser.parse(process.argv);
|
||||
|
||||
if (cliOptions.help) {
|
||||
const help = parser.help().trimRight();
|
||||
// tslint:disable-next-line:no-console
|
||||
console.log(help);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
return cliOptions;
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
const g = global as any;
|
||||
|
||||
// Because curve wrapper will populate this
|
||||
g.Internal = {};
|
||||
|
||||
// Because curve wrapper uses 'Module' to get at curve-provided functionality
|
||||
// tslint:disable-next-line
|
||||
g.Module = require('../../js/curve/curve25519_compiled');
|
||||
// tslint:disable-next-line
|
||||
require('../../js/curve/curve25519_wrapper');
|
||||
|
||||
export type BinaryType = Uint8Array | Buffer;
|
||||
|
||||
interface CurveType {
|
||||
keyPair: (
|
||||
privateKey: BinaryType
|
||||
) => {
|
||||
pubKey: BinaryType;
|
||||
privKey: BinaryType;
|
||||
};
|
||||
sign: (privateKey: BinaryType, message: BinaryType) => BinaryType;
|
||||
verify: (
|
||||
publicKey: BinaryType,
|
||||
message: BinaryType,
|
||||
signature: BinaryType
|
||||
) => boolean;
|
||||
}
|
||||
|
||||
const {
|
||||
keyPair: internalKeyPair,
|
||||
sign: internalSign,
|
||||
verify: internalVerify,
|
||||
} = g.Internal.curve25519 as CurveType;
|
||||
|
||||
export function keyPair() {
|
||||
const privateKey = randomBytes(32);
|
||||
const { pubKey, privKey } = internalKeyPair(privateKey);
|
||||
|
||||
return {
|
||||
publicKey: pubKey,
|
||||
privateKey: privKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function sign(privateKey: BinaryType, message: BinaryType) {
|
||||
return internalSign(privateKey, message);
|
||||
}
|
||||
|
||||
export function verify(
|
||||
publicKey: BinaryType,
|
||||
message: BinaryType,
|
||||
signature: BinaryType
|
||||
) {
|
||||
const failed = internalVerify(publicKey, message, signature);
|
||||
|
||||
return !failed;
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
import { getCliOptions, getPrintableError } from './common';
|
||||
import { keyPair } from './curve';
|
||||
import { writeHexToPath } from './signature';
|
||||
|
||||
/* tslint:disable:no-console */
|
||||
|
||||
const OPTIONS = [
|
||||
{
|
||||
names: ['help', 'h'],
|
||||
type: 'bool',
|
||||
help: 'Print this help and exit.',
|
||||
},
|
||||
{
|
||||
names: ['key', 'k'],
|
||||
type: 'string',
|
||||
help: 'Path where public key will go',
|
||||
default: 'public.key',
|
||||
},
|
||||
{
|
||||
names: ['private', 'p'],
|
||||
type: 'string',
|
||||
help: 'Path where private key will go',
|
||||
default: 'private.key',
|
||||
},
|
||||
];
|
||||
|
||||
type OptionsType = {
|
||||
key: string;
|
||||
private: string;
|
||||
};
|
||||
|
||||
const cliOptions = getCliOptions<OptionsType>(OPTIONS);
|
||||
go(cliOptions).catch(error => {
|
||||
console.error('Something went wrong!', getPrintableError(error));
|
||||
});
|
||||
|
||||
async function go(options: OptionsType) {
|
||||
const { key: publicKeyPath, private: privateKeyPath } = options;
|
||||
const { publicKey, privateKey } = keyPair();
|
||||
|
||||
await Promise.all([
|
||||
writeHexToPath(publicKeyPath, publicKey),
|
||||
writeHexToPath(privateKeyPath, privateKey),
|
||||
]);
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
import { join, resolve } from 'path';
|
||||
import { readdir as readdirCallback } from 'fs';
|
||||
|
||||
import pify from 'pify';
|
||||
|
||||
import { getCliOptions, getPrintableError } from './common';
|
||||
import { writeSignature } from './signature';
|
||||
|
||||
// @ts-ignore
|
||||
import * as packageJson from '../../package.json';
|
||||
|
||||
const readdir = pify(readdirCallback);
|
||||
|
||||
/* tslint:disable:no-console */
|
||||
|
||||
const OPTIONS = [
|
||||
{
|
||||
names: ['help', 'h'],
|
||||
type: 'bool',
|
||||
help: 'Print this help and exit.',
|
||||
},
|
||||
{
|
||||
names: ['private', 'p'],
|
||||
type: 'string',
|
||||
help: 'Path to private key file (default: ./private.key)',
|
||||
default: 'private.key',
|
||||
},
|
||||
{
|
||||
names: ['update', 'u'],
|
||||
type: 'string',
|
||||
help: 'Path to the update package (default: the .exe or .zip in ./release)',
|
||||
},
|
||||
{
|
||||
names: ['version', 'v'],
|
||||
type: 'string',
|
||||
help: `Version number of this package (default: ${packageJson.version})`,
|
||||
default: packageJson.version,
|
||||
},
|
||||
];
|
||||
|
||||
type OptionsType = {
|
||||
private: string;
|
||||
update: string;
|
||||
version: string;
|
||||
};
|
||||
|
||||
const cliOptions = getCliOptions<OptionsType>(OPTIONS);
|
||||
go(cliOptions).catch(error => {
|
||||
console.error('Something went wrong!', getPrintableError(error));
|
||||
});
|
||||
|
||||
async function go(options: OptionsType) {
|
||||
const { private: privateKeyPath, version } = options;
|
||||
let { update: updatePath } = options;
|
||||
|
||||
if (!updatePath) {
|
||||
updatePath = await findUpdatePath();
|
||||
}
|
||||
|
||||
console.log('Signing with...');
|
||||
console.log(` version: ${version}`);
|
||||
console.log(` update file: ${updatePath}`);
|
||||
console.log(` private key file: ${privateKeyPath}`);
|
||||
|
||||
await writeSignature(updatePath, version, privateKeyPath);
|
||||
}
|
||||
|
||||
const IS_EXE = /\.exe$/;
|
||||
const IS_ZIP = /\.zip$/;
|
||||
async function findUpdatePath(): Promise<string> {
|
||||
const releaseDir = resolve('release');
|
||||
const files: Array<string> = await readdir(releaseDir);
|
||||
|
||||
const max = files.length;
|
||||
for (let i = 0; i < max; i += 1) {
|
||||
const file = files[i];
|
||||
const fullPath = join(releaseDir, file);
|
||||
|
||||
if (IS_EXE.test(file) || IS_ZIP.test(file)) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("No suitable file found in 'release' folder!");
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
import { get as getFromConfig } from 'config';
|
||||
import { BrowserWindow } from 'electron';
|
||||
|
||||
import { start as startMacOS } from './macos';
|
||||
import { start as startWindows } from './windows';
|
||||
import {
|
||||
deleteBaseTempDir,
|
||||
getPrintableError,
|
||||
LoggerType,
|
||||
MessagesType,
|
||||
} from './common';
|
||||
|
||||
let initialized = false;
|
||||
|
||||
export async function start(
|
||||
getMainWindow: () => BrowserWindow,
|
||||
messages?: MessagesType,
|
||||
logger?: LoggerType
|
||||
) {
|
||||
const { platform } = process;
|
||||
|
||||
if (initialized) {
|
||||
throw new Error('updater/start: Updates have already been initialized!');
|
||||
}
|
||||
initialized = true;
|
||||
|
||||
if (!messages) {
|
||||
throw new Error('updater/start: Must provide messages!');
|
||||
}
|
||||
if (!logger) {
|
||||
throw new Error('updater/start: Must provide logger!');
|
||||
}
|
||||
|
||||
if (autoUpdateDisabled()) {
|
||||
logger.info(
|
||||
'updater/start: Updates disabled - not starting new version checks'
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteBaseTempDir();
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
'updater/start: Error deleting temp dir:',
|
||||
getPrintableError(error)
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === 'win32') {
|
||||
await startWindows(getMainWindow, messages, logger);
|
||||
} else if (platform === 'darwin') {
|
||||
await startMacOS(getMainWindow, messages, logger);
|
||||
} else {
|
||||
throw new Error('updater/start: Unsupported platform');
|
||||
}
|
||||
}
|
||||
|
||||
function autoUpdateDisabled() {
|
||||
return (
|
||||
process.platform === 'linux' ||
|
||||
process.mas ||
|
||||
!getFromConfig('updatesEnabled')
|
||||
);
|
||||
}
|
@ -0,0 +1,324 @@
|
||||
import { createReadStream, statSync } from 'fs';
|
||||
import { createServer, IncomingMessage, Server, ServerResponse } from 'http';
|
||||
import { AddressInfo } from 'net';
|
||||
import { dirname } from 'path';
|
||||
|
||||
import { v4 as getGuid } from 'uuid';
|
||||
import { app, autoUpdater, BrowserWindow, dialog } from 'electron';
|
||||
import { get as getFromConfig } from 'config';
|
||||
import { gt } from 'semver';
|
||||
|
||||
import {
|
||||
checkForUpdates,
|
||||
deleteTempDir,
|
||||
downloadUpdate,
|
||||
getPrintableError,
|
||||
LoggerType,
|
||||
MessagesType,
|
||||
showCannotUpdateDialog,
|
||||
showUpdateDialog,
|
||||
} from './common';
|
||||
import { hexToBinary, verifySignature } from './signature';
|
||||
import { markShouldQuit } from '../../app/window_state';
|
||||
|
||||
let isChecking = false;
|
||||
const SECOND = 1000;
|
||||
const MINUTE = SECOND * 60;
|
||||
const INTERVAL = MINUTE * 30;
|
||||
|
||||
export async function start(
|
||||
getMainWindow: () => BrowserWindow,
|
||||
messages: MessagesType,
|
||||
logger: LoggerType
|
||||
) {
|
||||
logger.info('macos/start: starting checks...');
|
||||
|
||||
loggerForQuitHandler = logger;
|
||||
app.once('quit', quitHandler);
|
||||
|
||||
setInterval(async () => {
|
||||
try {
|
||||
await checkDownloadAndInstall(getMainWindow, messages, logger);
|
||||
} catch (error) {
|
||||
logger.error('macos/start: error:', getPrintableError(error));
|
||||
}
|
||||
}, INTERVAL);
|
||||
|
||||
await checkDownloadAndInstall(getMainWindow, messages, logger);
|
||||
}
|
||||
|
||||
let fileName: string;
|
||||
let version: string;
|
||||
let updateFilePath: string;
|
||||
let loggerForQuitHandler: LoggerType;
|
||||
|
||||
async function checkDownloadAndInstall(
|
||||
getMainWindow: () => BrowserWindow,
|
||||
messages: MessagesType,
|
||||
logger: LoggerType
|
||||
) {
|
||||
if (isChecking) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info('checkDownloadAndInstall: checking for update...');
|
||||
try {
|
||||
isChecking = true;
|
||||
|
||||
const result = await checkForUpdates(logger);
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { fileName: newFileName, version: newVersion } = result;
|
||||
if (fileName !== newFileName || !version || gt(newVersion, version)) {
|
||||
deleteCache(updateFilePath, logger);
|
||||
fileName = newFileName;
|
||||
version = newVersion;
|
||||
updateFilePath = await downloadUpdate(fileName, logger);
|
||||
}
|
||||
|
||||
const publicKey = hexToBinary(getFromConfig('updatesPublicKey'));
|
||||
const verified = verifySignature(updateFilePath, version, 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(
|
||||
`checkDownloadAndInstall: Downloaded update did not pass signature verification (version: '${version}'; fileName: '${fileName}')`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await handToAutoUpdate(updateFilePath, logger);
|
||||
} catch (error) {
|
||||
const readOnly = 'Cannot update while running on a read-only volume';
|
||||
const message: string = error.message || '';
|
||||
if (message.includes(readOnly)) {
|
||||
logger.info('checkDownloadAndInstall: showing read-only dialog...');
|
||||
await showReadOnlyDialog(getMainWindow(), messages);
|
||||
} else {
|
||||
logger.info(
|
||||
'checkDownloadAndInstall: showing general update failure dialog...'
|
||||
);
|
||||
await showCannotUpdateDialog(getMainWindow(), messages);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
// At this point, closing the app will cause the update to be installed automatically
|
||||
// because Squirrel has cached the update file and will do the right thing.
|
||||
|
||||
logger.info('checkDownloadAndInstall: showing update dialog...');
|
||||
const shouldUpdate = await showUpdateDialog(getMainWindow(), messages);
|
||||
if (!shouldUpdate) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info('checkDownloadAndInstall: calling quitAndInstall...');
|
||||
markShouldQuit();
|
||||
autoUpdater.quitAndInstall();
|
||||
} catch (error) {
|
||||
logger.error('checkDownloadAndInstall: error', getPrintableError(error));
|
||||
} finally {
|
||||
isChecking = false;
|
||||
}
|
||||
}
|
||||
|
||||
function quitHandler() {
|
||||
deleteCache(updateFilePath, loggerForQuitHandler);
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
function deleteCache(filePath: string | null, logger: LoggerType) {
|
||||
if (filePath) {
|
||||
const tempDir = dirname(filePath);
|
||||
deleteTempDir(tempDir).catch(error => {
|
||||
logger.error(
|
||||
'quitHandler: error deleting temporary directory:',
|
||||
getPrintableError(error)
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handToAutoUpdate(
|
||||
filePath: string,
|
||||
logger: LoggerType
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const updateFileUrl = generateFileUrl();
|
||||
const server = createServer();
|
||||
let serverUrl: string;
|
||||
|
||||
server.on('error', (error: Error) => {
|
||||
logger.error(
|
||||
'handToAutoUpdate: server had error',
|
||||
getPrintableError(error)
|
||||
);
|
||||
shutdown(server, logger);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
server.on(
|
||||
'request',
|
||||
(request: IncomingMessage, response: ServerResponse) => {
|
||||
const { url } = request;
|
||||
|
||||
if (url === '/') {
|
||||
const absoluteUrl = `${serverUrl}${updateFileUrl}`;
|
||||
writeJSONResponse(absoluteUrl, response);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!url || !url.startsWith(updateFileUrl)) {
|
||||
write404(url, response, logger);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
pipeUpdateToSquirrel(filePath, server, response, logger, reject);
|
||||
}
|
||||
);
|
||||
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
serverUrl = getServerUrl(server);
|
||||
|
||||
autoUpdater.on('error', (error: Error) => {
|
||||
logger.error('autoUpdater: error', getPrintableError(error));
|
||||
reject(error);
|
||||
});
|
||||
autoUpdater.on('update-downloaded', () => {
|
||||
logger.info('autoUpdater: update-downloaded event fired');
|
||||
shutdown(server, logger);
|
||||
resolve();
|
||||
});
|
||||
|
||||
autoUpdater.setFeedURL({
|
||||
url: serverUrl,
|
||||
headers: { 'Cache-Control': 'no-cache' },
|
||||
});
|
||||
autoUpdater.checkForUpdates();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function pipeUpdateToSquirrel(
|
||||
filePath: string,
|
||||
server: Server,
|
||||
response: ServerResponse,
|
||||
logger: LoggerType,
|
||||
reject: (error: Error) => void
|
||||
) {
|
||||
const updateFileSize = getFileSize(filePath);
|
||||
const readStream = createReadStream(filePath);
|
||||
|
||||
response.on('error', (error: Error) => {
|
||||
logger.error(
|
||||
'pipeUpdateToSquirrel: update file download request had an error',
|
||||
getPrintableError(error)
|
||||
);
|
||||
shutdown(server, logger);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
readStream.on('error', (error: Error) => {
|
||||
logger.error(
|
||||
'pipeUpdateToSquirrel: read stream error response:',
|
||||
getPrintableError(error)
|
||||
);
|
||||
shutdown(server, logger, response);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
response.writeHead(200, {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Length': updateFileSize,
|
||||
});
|
||||
|
||||
readStream.pipe(response);
|
||||
}
|
||||
|
||||
function writeJSONResponse(url: string, response: ServerResponse) {
|
||||
const data = Buffer.from(
|
||||
JSON.stringify({
|
||||
url,
|
||||
})
|
||||
);
|
||||
response.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': data.byteLength,
|
||||
});
|
||||
response.end(data);
|
||||
}
|
||||
|
||||
function write404(
|
||||
url: string | undefined,
|
||||
response: ServerResponse,
|
||||
logger: LoggerType
|
||||
) {
|
||||
logger.error(`write404: Squirrel requested unexpected url '${url}'`);
|
||||
response.writeHead(404);
|
||||
response.end();
|
||||
}
|
||||
|
||||
function getServerUrl(server: Server) {
|
||||
const address = server.address() as AddressInfo;
|
||||
|
||||
// tslint:disable-next-line:no-http-string
|
||||
return `http://127.0.0.1:${address.port}`;
|
||||
}
|
||||
function generateFileUrl(): string {
|
||||
return `/${getGuid()}.zip`;
|
||||
}
|
||||
|
||||
function getFileSize(targetPath: string): number {
|
||||
const { size } = statSync(targetPath);
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
function shutdown(
|
||||
server: Server,
|
||||
logger: LoggerType,
|
||||
response?: ServerResponse
|
||||
) {
|
||||
try {
|
||||
if (server) {
|
||||
server.close();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('shutdown: Error closing server', getPrintableError(error));
|
||||
}
|
||||
|
||||
try {
|
||||
if (response) {
|
||||
response.end();
|
||||
}
|
||||
} catch (endError) {
|
||||
logger.error(
|
||||
"shutdown: couldn't end response",
|
||||
getPrintableError(endError)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function showReadOnlyDialog(
|
||||
mainWindow: BrowserWindow,
|
||||
messages: MessagesType
|
||||
): Promise<void> {
|
||||
const options = {
|
||||
type: 'warning',
|
||||
buttons: [messages.ok.message],
|
||||
title: messages.cannotUpdate.message,
|
||||
message: messages.readOnlyVolume.message,
|
||||
};
|
||||
|
||||
return new Promise(resolve => {
|
||||
dialog.showMessageBox(mainWindow, options, () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue