From 2f6f9ce9f941f34085b2886be093595da732fd89 Mon Sep 17 00:00:00 2001
From: blavenie <benoit.lavenier@e-is.pro>
Date: Mon, 1 Apr 2019 19:30:04 +0200
Subject: [PATCH] [fix] Fix secure storage, and EWIF scan - fix #818

---
 platforms/desktop                       |  2 +-
 www/i18n/locale-fr-FR.json              |  3 +-
 www/js/controllers/login-controllers.js |  1 +
 www/js/platform.js                      | 12 ++++--
 www/js/services/crypto-services.js      | 35 ++++++++--------
 www/js/services/storage-services.js     | 55 ++++++++++++++++---------
 6 files changed, 66 insertions(+), 42 deletions(-)

diff --git a/platforms/desktop b/platforms/desktop
index 473c109b..e4eebd2e 160000
--- a/platforms/desktop
+++ b/platforms/desktop
@@ -1 +1 @@
-Subproject commit 473c109b8e46634378c5f932702a86be060cfa46
+Subproject commit e4eebd2e152b44e0ef5037a9fa8b14066c490e72
diff --git a/www/i18n/locale-fr-FR.json b/www/i18n/locale-fr-FR.json
index 784c0db1..ddc262e7 100644
--- a/www/i18n/locale-fr-FR.json
+++ b/www/i18n/locale-fr-FR.json
@@ -633,7 +633,8 @@
           "PASSWORD_HELP": "Phrase secrète"
         },
         "ERROR": {
-          "BAD_PASSWORD": "Phrase secrète incorrecte"
+          "BAD_PASSWORD": "Phrase secrète incorrecte",
+          "BAD_CHECKSUM": "Somme de contrôle incorrecte"
         }
       }
     },
diff --git a/www/js/controllers/login-controllers.js b/www/js/controllers/login-controllers.js
index 2878bf32..744b9cb9 100644
--- a/www/js/controllers/login-controllers.js
+++ b/www/js/controllers/login-controllers.js
@@ -376,6 +376,7 @@ function LoginModalController($scope, $timeout, $q, $ionicPopover, CryptoUtils,
           });
       })
       .then(function(data) {
+        if (!data) return;
         // Parse success: continue
         if (data && data.pubkey) return data;
 
diff --git a/www/js/platform.js b/www/js/platform.js
index cfda3b04..52fa3d0a 100644
--- a/www/js/platform.js
+++ b/www/js/platform.js
@@ -77,12 +77,18 @@ angular.module('cesium.platform', ['ngIdle', 'cesium.config', 'cesium.services']
     IdleProvider.timeout(csConfig.logoutTimeout||15); // display warning during 15s
   })
 
-  .factory('$exceptionHandler', function() {
+  .factory('$exceptionHandler', function($log) {
     'ngInject';
 
+    function stacktrace(f) {
+      return !f ? [] :
+        stacktrace(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + Array.prototype.slice.call(f.arguments).join(',') + ')']);
+    }
+
     return function(exception, cause) {
-      if (cause) console.error(exception, cause);
-      else console.error(exception);
+      //console.error(stacktrace(arguments.callee.caller));
+      if (cause) $log.error(exception, cause);
+      else $log.error(exception);
     };
   })
 
diff --git a/www/js/services/crypto-services.js b/www/js/services/crypto-services.js
index c0e9a4f5..6d78bff7 100644
--- a/www/js/services/crypto-services.js
+++ b/www/js/services/crypto-services.js
@@ -801,11 +801,11 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
 
       // Use Cordova plugin implementation, when exists
       if (isDevice && window.plugins && window.plugins.MiniSodium && crypto && crypto.getRandomValues) {
-        console.debug('[crypto] Loading Cordova MiniSodium implementation...');
+        console.debug('[crypto] Loading \'MiniSodium\' implementation...');
         serviceImpl = new CordovaServiceFactory();
       }
       else {
-        console.debug('[crypto] Loading FullJS implementation...');
+        console.debug('[crypto] Loading \'FullJS\' implementation...');
         serviceImpl = new FullJSServiceFactory();
       }
 
@@ -822,7 +822,6 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
 
     });
 
-
     return service;
   })
 
@@ -831,7 +830,7 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
      Crypto advanced service for Cesium
    */
 
-  .factory('csCrypto', function($q, $rootScope, CryptoUtils, UIUtils, Modals) {
+  .factory('csCrypto', function($q, $rootScope, $timeout, CryptoUtils, UIUtils, Modals) {
     'ngInject';
 
     function test(regexpContent) {
@@ -989,8 +988,8 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
     function parseWIF_or_EWIF(data_base58, options) {
       options = options || {};
 
-      var data_int8 = CryptoUtils.base58.decode(data_base58);
-      if (data_int8.length != constants.EWIF.DATA_LENGTH && data_int8.length != constants.WIF.DATA_LENGTH) {
+      var data_int8 = data_base58 && CryptoUtils.base58.decode(data_base58);
+      if (!data_int8 || data_int8.length != constants.EWIF.DATA_LENGTH && data_int8.length != constants.WIF.DATA_LENGTH) {
         return $q.reject('Invalid WIF or EWIF format (invalid bytes count).');
       }
 
@@ -1121,13 +1120,13 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
           // Check salt
           var expectedSalt = CryptoUtils.util.crypto_hash_sha256(CryptoUtils.util.crypto_hash_sha256(keypair.signPk)).slice(0,4);
           if(CryptoUtils.util.encode_base58(salt) !== CryptoUtils.util.encode_base58(expectedSalt)) {
-            throw {ucode: errorCodes.BAD_PASSWORD, message: 'ERROR.BAD_PASSWORD'};
+            throw {ucode: errorCodes.BAD_PASSWORD, message: 'ACCOUNT.SECURITY.KEYFILE.ERROR.BAD_PASSWORD'};
           }
 
           // Check checksum
           var expectedChecksum = CryptoUtils.util.crypto_hash_sha256(CryptoUtils.util.crypto_hash_sha256(ewif_int8_no_checksum)).slice(0,2);
           if (CryptoUtils.util.encode_base58(checksum) != CryptoUtils.util.encode_base58(expectedChecksum)) {
-            throw {ucode: errorCodes.BAD_CHECKSUM, message: 'ERROR.BAD_CHECKSUM'};
+            throw {ucode: errorCodes.BAD_CHECKSUM, message: 'ACCOUNT.SECURITY.KEYFILE.ERROR.BAD_CHECKSUM'};
           }
 
           return keypair;
@@ -1408,13 +1407,15 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
       options.withSecret = angular.isDefined(options.withSecret) ? options.withSecret : true;
       options.silent = angular.isDefined(options.withSecret) ? options.silent : false;
       options.password = function() {
-        UIUtils.loading.hide();
-        return Modals.showPassword({
-          title: 'ACCOUNT.SECURITY.KEYFILE.PASSWORD_POPUP.TITLE',
-          subTitle: 'ACCOUNT.SECURITY.KEYFILE.PASSWORD_POPUP.HELP',
-          error: options.error,
-          scope: $scope
-        })
+        return UIUtils.loading.hide(100)
+          .then(function() {
+            return Modals.showPassword({
+              title: 'ACCOUNT.SECURITY.KEYFILE.PASSWORD_POPUP.TITLE',
+              subTitle: 'ACCOUNT.SECURITY.KEYFILE.PASSWORD_POPUP.HELP',
+              error: options.error,
+              scope: options.scope
+            })
+          })
           .then(function(password) {
             // Timeout is need to force popup to be hide
             return $timeout(function() {
@@ -1433,8 +1434,8 @@ angular.module('cesium.crypto.services', ['cesium.utils.services'])
           return res;
         })
         .catch(function(err) {
-          if (err && err == 'CANCELLED') return;
-          if (err && err.ucode == csCrypto.errorCodes.BAD_PASSWORD) {
+          if (err && err === 'CANCELLED') return;
+          if (err && err.ucode == errorCodes.BAD_PASSWORD) {
             // recursive call
             return parseKeyFileData(data, {withSecret: options.withSecret, error: 'ACCOUNT.SECURITY.KEYFILE.ERROR.BAD_PASSWORD'});
           }
diff --git a/www/js/services/storage-services.js b/www/js/services/storage-services.js
index bc13a90c..7517e6c1 100644
--- a/www/js/services/storage-services.js
+++ b/www/js/services/storage-services.js
@@ -30,7 +30,7 @@ angular.module('cesium.storage.services', [ 'cesium.config'])
     return exports;
   })
 
-  .factory('localStorage', function($window, $q, sessionStorage) {
+  .factory('localStorage', function($window, $q, $log, sessionStorage) {
     'ngInject';
 
     var
@@ -100,32 +100,48 @@ angular.module('cesium.storage.services', [ 'cesium.config'])
 
     // Get a value from the secure storage
     exports.secure.get = function(key, defaultValue) {
-      var deferred = $q.defer();
-      exports.secure.storage.get(
-        function (value) {
-          if (!value && defaultValue) {
-            deferred.resolve(defaultValue);
-          }
-          else {
-            deferred.resolve(value);
-          }
-        },
-        function (err) { deferred.reject(err); },
-        key);
-      return deferred.promise;
+      return $q(function(resolve, reject) {
+        exports.secure.storage.get(
+          function (value) {
+            if (!value && defaultValue) {
+              resolve(defaultValue);
+            }
+            else {
+              resolve(value);
+            }
+          },
+          function (err) {
+            $log.error(err);
+            resolve(); // Error = not found
+          },
+          key);
+      });
     };
 
     // Set a object to the secure storage
     exports.secure.setObject = function(key, value) {
-      return exports.secure.put(key, value ? JSON.stringify(value) : undefined);
+      $log.debug("[storage] Setting object into secure storage, using key=" + key);
+      return $q(function(resolve, reject){
+        exports.secure.storage.set(
+          resolve,
+          reject,
+          key,
+          value ? JSON.stringify(value) : undefined);
+      });
     };
 
     // Get a object from the secure storage
     exports.secure.getObject = function(key) {
-      return exports.secure.storage.get(key)
-        .then(function(value) {
-          return JSON.parse(value||'null');
-        });
+      $log.debug("[storage] Getting object from secure storage, using key=" + key);
+      return $q(function(resolve, reject){
+        exports.secure.storage.get(
+          function(value) {resolve(JSON.parse(value||'null'));},
+          function(err) {
+            $log.error(err);
+            resolve(); // Error = not found
+          },
+          key);
+      });
     };
 
     function initStandardStorage() {
@@ -196,7 +212,6 @@ angular.module('cesium.storage.services', [ 'cesium.config'])
 
       // Use Cordova secure storage plugin
       if (isDevice) {
-        console.debug("[storage] Starting secure storage...");
         startPromise = initSecureStorage();
       }
 
-- 
GitLab