diff --git a/Gruntfile.js b/Gruntfile.js index 0a97452..835d5da 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -135,7 +135,8 @@ module.exports = function(grunt) { 'imap-client/node_modules/mimelib/node_modules/encoding/node_modules/iconv-lite/src/*.js', 'imap-client/node_modules/mimelib/node_modules/encoding/node_modules/mime/src/*.js', 'imap-client/node_modules/mailparser/src/*.js', - 'imap-client/node_modules/mailparser/node_modules/mime/src/mime.js' + 'imap-client/node_modules/mailparser/node_modules/mime/src/mime.js', + 'smtp-client/src-gen/*.js' ], dest: 'src/lib/' }, diff --git a/res/copy-deps.sh b/res/copy-deps.sh index 0480159..043ce60 100755 --- a/res/copy-deps.sh +++ b/res/copy-deps.sh @@ -8,7 +8,7 @@ cd .. # build imap/smtp modules and copy cd ./node_modules/smtp-client/ -node build.js && cp ./src-gen/*.js ../../src/lib/ +node build.js cd ../../ echo "\n--> finished building dependencies.\n" diff --git a/src/img/icon.png b/src/img/icon.png new file mode 100644 index 0000000..a3e3860 Binary files /dev/null and b/src/img/icon.png differ diff --git a/src/img/mail-128.png b/src/img/mail-128.png deleted file mode 100755 index cafb49e..0000000 Binary files a/src/img/mail-128.png and /dev/null differ diff --git a/src/js/app-controller.js b/src/js/app-controller.js index ee1f0a3..95c7a84 100644 --- a/src/js/app-controller.js +++ b/src/js/app-controller.js @@ -10,6 +10,8 @@ define(function(require) { EmailDAO = require('js/dao/email-dao'), KeychainDAO = require('js/dao/keychain-dao'), cloudstorage = require('js/dao/cloudstorage-dao'), + DeviceStorageDAO = require('js/dao/devicestorage-dao'), + Crypto = require('js/crypto/crypto'), config = require('js/app-config').config; require('cordova'); @@ -66,7 +68,7 @@ define(function(require) { self.login = function(userId, password, token, callback) { var auth, imapOptions, smtpOptions, - keychain, imapClient, smtpClient; + keychain, imapClient, smtpClient, crypto, deviceStorage; // create mail credentials objects for imap/smtp auth = { @@ -93,7 +95,9 @@ define(function(require) { keychain = new KeychainDAO(cloudstorage); imapClient = new ImapClient(imapOptions); smtpClient = new SmtpClient(smtpOptions); - self._emailDao = new EmailDAO(keychain, imapClient, smtpClient); + crypto = new Crypto(); + deviceStorage = new DeviceStorageDAO(); + self._emailDao = new EmailDAO(keychain, imapClient, smtpClient, crypto, deviceStorage); // init email dao var account = { diff --git a/src/js/controller/mail-list.js b/src/js/controller/mail-list.js index df0a537..681400b 100644 --- a/src/js/controller/mail-list.js +++ b/src/js/controller/mail-list.js @@ -3,10 +3,13 @@ define(function(require) { var _ = require('underscore'), appController = require('js/app-controller'), - moment = require('moment'), emailDao; var MailListCtrl = function($scope) { + var offset = -6, + num = 0; + + // show inbox at the beginning $scope.folder = 'INBOX'; emailDao = appController._emailDao; @@ -17,72 +20,83 @@ define(function(require) { $scope.$parent.selected = $scope.selected; }; + // production... in chrome packaged app if (window.chrome && chrome.identity) { - fetchList($scope.folder, function(emails) { - $scope.emails = emails; - $scope.select($scope.emails[0]); - $scope.$apply(); - }); + initList(); return; } + // development createDummyMails(function(emails) { $scope.emails = emails; $scope.select($scope.emails[0]); }); - }; - function fetchList(folder, callback) { - // fetch imap folder's message list - emailDao.imapListMessages({ - folder: folder, - offset: -6, - num: 0 - }, function(err, emails) { - if (err) { - console.log(err); - return; - } - - // fetch message bodies - fetchBodies(emails, folder, function(messages) { - addDisplayDate(messages); - callback(messages); + function initList() { + // list messaged from local db + listLocalMessages({ + folder: $scope.folder, + offset: offset, + num: num + }, function() { + // sync from imap to local db + syncImapFolder({ + folder: $scope.folder, + offset: offset, + num: num + }, function() { + // list again from local db after syncing + listLocalMessages({ + folder: $scope.folder, + offset: offset, + num: num + }, function() { + console.log('syncing ' + $scope.folder + ' complete'); + }); + }); }); - }); - } + } - function fetchBodies(messageList, folder, callback) { - var emails = []; - - var after = _.after(messageList.length, function() { - callback(emails); - }); - - _.each(messageList, function(messageItem) { - emailDao.imapGetMessage({ - folder: folder, - uid: messageItem.uid - }, function(err, message) { + function syncImapFolder(options, callback) { + // sync if emails are empty + emailDao.imapSync(options, function(err) { if (err) { console.log(err); return; } - emails.push(message); - after(); + callback(); }); - }); - } + } - function addDisplayDate(emails) { - emails.forEach(function(email) { - // set display date - email.displayDate = moment(email.sentDate).format('DD.MM.YY'); - }); + function listLocalMessages(options, callback) { + emailDao.listMessages(options, function(err, emails) { + if (err) { + console.log(err); + return; + } + // add display dates + displayEmails(emails); - return emails; - } + callback(emails); + }); + } + + function displayEmails(emails) { + if (!emails || emails.length < 1) { + return; + } + + // sort by uid + emails = _.sortBy(emails, function(e) { + return -e.uid; + }); + + $scope.emails = emails; + $scope.select($scope.emails[0]); + $scope.$apply(); + } + }; function createDummyMails(callback) { var Email = function(unread, attachments, replied) { @@ -97,8 +111,7 @@ define(function(require) { this.attachments = (attachments) ? [true] : undefined; this.unread = unread; this.replied = replied; - this.displayDate = '23.08.13'; - this.longDisplayDate = 'Wednesday, 23.08.2013 19:23'; + this.sentDate = new Date('Thu Sep 19 2013 20:41:23 GMT+0200 (CEST)'); this.subject = "Welcome Max"; // Subject line this.body = "Hi Max,\n\n" + "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n\n" + diff --git a/src/js/crypto/crypto.js b/src/js/crypto/crypto.js index 588709f..e764da4 100644 --- a/src/js/crypto/crypto.js +++ b/src/js/crypto/crypto.js @@ -12,16 +12,21 @@ define(function(require) { pbkdf2 = require('js/crypto/pbkdf2'), config = require('js/app-config').config; - var self = {}, - passBasedKey, + var passBasedKey, BATCH_WORKER = '/crypto/crypto-batch-worker.js', PBKDF2_WORKER = '/crypto/pbkdf2-worker.js'; + var Crypto = function() { + + }; + /** * Initializes the crypto modules by fetching the user's * encrypted secret key from storage and storing it in memory. */ - self.init = function(args, callback) { + Crypto.prototype.init = function(args, callback) { + var self = this; + // valdiate input if (!args.emailAddress || !args.keySize || !args.rsaKeySize) { callback({ @@ -119,7 +124,7 @@ define(function(require) { /** * Do PBKDF2 key derivation in a WebWorker thread */ - self.deriveKey = function(password, keySize, callback) { + Crypto.prototype.deriveKey = function(password, keySize, callback) { startWorker({ script: PBKDF2_WORKER, args: { @@ -137,8 +142,9 @@ define(function(require) { // En/Decrypt a list of items with AES in a WebWorker thread // - self.symEncryptList = function(list, callback) { - var key, envelope, envelopes = []; + Crypto.prototype.symEncryptList = function(list, callback) { + var self = this, + key, envelope, envelopes = []; // generate single secret key shared for all list items key = util.random(self.keySize); @@ -173,7 +179,7 @@ define(function(require) { }); }; - self.symDecryptList = function(list, keys, callback) { + Crypto.prototype.symDecryptList = function(list, keys, callback) { startWorker({ script: BATCH_WORKER, args: { @@ -192,8 +198,9 @@ define(function(require) { // En/Decrypt something speficially using the user's secret key // - self.encryptListForUser = function(list, receiverPubkeys, callback) { - var envelope, envelopes = []; + Crypto.prototype.encryptListForUser = function(list, receiverPubkeys, callback) { + var self = this, + envelope, envelopes = []; if (!receiverPubkeys || receiverPubkeys.length !== 1) { callback({ @@ -235,7 +242,7 @@ define(function(require) { }); }; - self.decryptListForUser = function(list, senderPubkeys, callback) { + Crypto.prototype.decryptListForUser = function(list, senderPubkeys, callback) { if (!senderPubkeys || senderPubkeys < 1) { callback({ errMsg: 'Sender public keys must be set!' @@ -268,7 +275,7 @@ define(function(require) { // Re-encrypt keys item and items seperately // - self.reencryptListKeysForUser = function(list, senderPubkeys, callback) { + Crypto.prototype.reencryptListKeysForUser = function(list, senderPubkeys, callback) { var keypair = rsa.exportKeys(); var receiverPrivkey = { _id: keypair._id, @@ -291,7 +298,7 @@ define(function(require) { }); }; - self.decryptKeysAndList = function(list, callback) { + Crypto.prototype.decryptKeysAndList = function(list, callback) { startWorker({ script: BATCH_WORKER, args: { @@ -351,5 +358,5 @@ define(function(require) { options.callback(null, result); } - return self; + return Crypto; }); \ No newline at end of file diff --git a/src/js/dao/devicestorage-dao.js b/src/js/dao/devicestorage-dao.js index 300ba41..24fd2f5 100644 --- a/src/js/dao/devicestorage-dao.js +++ b/src/js/dao/devicestorage-dao.js @@ -4,17 +4,26 @@ * through transparent encryption. If not, the crypto API is * used to encrypt data on the fly before persisting via a JSON store. */ -define(['cryptoLib/util', 'js/crypto/crypto', 'js/dao/lawnchair-dao'], function(util, crypto, jsonDao) { +define(function(require) { 'use strict'; - var self = {}; + var util = require('cryptoLib/util'), + jsonDao = require('js/dao/lawnchair-dao'); + + var DeviceStorageDAO = function() { + + }; + + DeviceStorageDAO.prototype.init = function(emailAddress, callback) { + jsonDao.init(emailAddress, callback); + }; /** * Stores a list of encrypted items in the object store * @param list [Array] The list of items to be persisted * @param type [String] The type of item to be persisted e.g. 'email' */ - self.storeEcryptedList = function(list, type, callback) { + DeviceStorageDAO.prototype.storeEcryptedList = function(list, type, callback) { var date, key, items = []; // nothing to store @@ -25,9 +34,10 @@ define(['cryptoLib/util', 'js/crypto/crypto', 'js/dao/lawnchair-dao'], function( // format items for batch storing in dao list.forEach(function(i) { - - // put date in key if available... for easy querying - if (i.sentDate) { + // put uid in key if available... for easy querying + if (i.uid) { + key = type + '_' + i.uid; + } else if (i.sentDate) { date = util.parseDate(i.sentDate); key = type + '_' + i.sentDate + '_' + i.id; } else { @@ -38,7 +48,6 @@ define(['cryptoLib/util', 'js/crypto/crypto', 'js/dao/lawnchair-dao'], function( key: key, object: i }); - }); jsonDao.batch(items, function() { @@ -52,7 +61,7 @@ define(['cryptoLib/util', 'js/crypto/crypto', 'js/dao/lawnchair-dao'], function( * @param offset [Number] The offset of items to fetch (0 is the last stored item) * @param num [Number] The number of items to fetch (null means fetch all) */ - self.listEncryptedItems = function(type, offset, num, callback) { + DeviceStorageDAO.prototype.listEncryptedItems = function(type, offset, num, callback) { // fetch all items of a certain type from the data-store jsonDao.list(type, offset, num, function(encryptedList) { @@ -63,9 +72,9 @@ define(['cryptoLib/util', 'js/crypto/crypto', 'js/dao/lawnchair-dao'], function( /** * Clear the whole device data-store */ - self.clear = function(callback) { + DeviceStorageDAO.prototype.clear = function(callback) { jsonDao.clear(callback); }; - return self; + return DeviceStorageDAO; }); \ No newline at end of file diff --git a/src/js/dao/email-dao.js b/src/js/dao/email-dao.js index 2a5302d..fb22578 100644 --- a/src/js/dao/email-dao.js +++ b/src/js/dao/email-dao.js @@ -3,20 +3,20 @@ define(function(require) { var _ = require('underscore'), util = require('cryptoLib/util'), - crypto = require('js/crypto/crypto'), - jsonDB = require('js/dao/lawnchair-dao'), str = require('js/app-config').string; /** * A high-level Data-Access Api for handling Email synchronization * between the cloud service and the device's local storage */ - var EmailDAO = function(keychain, imapClient, smtpClient) { + var EmailDAO = function(keychain, imapClient, smtpClient, crypto, devicestorage) { var self = this; self._keychain = keychain; self._imapClient = imapClient; self._smtpClient = smtpClient; + self._crypto = crypto; + self._devicestorage = devicestorage; }; /** @@ -51,21 +51,21 @@ define(function(require) { function initKeychain() { // init user's local database - jsonDB.init(emailAddress); - - // call getUserKeyPair to read/sync keypair with devicestorage/cloud - self._keychain.getUserKeyPair(emailAddress, function(err, storedKeypair) { - if (err) { - callback(err); - return; - } - // init crypto - initCrypto(storedKeypair); + self._devicestorage.init(emailAddress, function() { + // call getUserKeyPair to read/sync keypair with devicestorage/cloud + self._keychain.getUserKeyPair(emailAddress, function(err, storedKeypair) { + if (err) { + callback(err); + return; + } + // init crypto + initCrypto(storedKeypair); + }); }); } function initCrypto(storedKeypair) { - crypto.init({ + self._crypto.init({ emailAddress: emailAddress, password: password, keySize: self._account.symKeySize, @@ -144,8 +144,11 @@ define(function(require) { // validate public key if (!receiverPubkey) { + callback({ + errMsg: 'User has no public key yet!' + }); // user hasn't registered a public key yet... invite - self.encryptForNewUser(email, callback); + //self.encryptForNewUser(email, callback); return; } @@ -163,7 +166,7 @@ define(function(require) { receiverPubkeys = [receiverPubkey]; // encrypt the email - crypto.encryptListForUser(ptItems, receiverPubkeys, function(err, encryptedList) { + self._crypto.encryptListForUser(ptItems, receiverPubkeys, function(err, encryptedList) { if (err) { callback(err); return; @@ -183,7 +186,7 @@ define(function(require) { var self = this, ptItems = bundleForEncryption(email); - crypto.symEncryptList(ptItems, function(err, result) { + self._crypto.symEncryptList(ptItems, function(err, result) { if (err) { callback(err); return; @@ -295,6 +298,168 @@ define(function(require) { self._imapClient.unreadMessages(path, callback); }; + /** + * Fetch a list of emails from the device's local storage + */ + EmailDAO.prototype.listMessages = function(options, callback) { + var self = this, + encryptedList = []; + + // validate options + if (!options.folder || typeof options.offset === 'undefined' || typeof options.num === 'undefined') { + callback({ + errMsg: 'Invalid options!' + }); + return; + } + + // fetch items from device storage + self._devicestorage.listEncryptedItems('email_' + options.folder, options.offset, options.num, function(err, emails) { + if (err) { + callback(err); + return; + } + if (emails.length === 0) { + callback(null, []); + return; + } + + // find encrypted items + emails.forEach(function(i) { + if (i.body.indexOf(str.cryptPrefix) !== -1 && i.body.indexOf(str.cryptSuffix) !== -1) { + // parse ct object from ascii armored message block + encryptedList.push(parseMessageBlock(i)); + } + }); + + // decrypt items + decryptList(encryptedList, function(err, decryptedList) { + // return only decrypted items + callback(null, decryptedList); + }); + }); + + function parseMessageBlock(email) { + var ctMessageBase64, ctMessageJson, ctMessage; + + // parse email body for encrypted message block + try { + // get base64 encoded message block + ctMessageBase64 = email.body.split(str.cryptPrefix)[1].split(str.cryptSuffix)[0].trim(); + // decode bae64 + ctMessageJson = atob(ctMessageBase64); + // parse json string to get ciphertext object + ctMessage = JSON.parse(ctMessageJson); + } catch (e) { + callback({ + errMsg: 'Error parsing encrypted message block!' + }); + return; + } + + return ctMessage; + } + + function decryptList(encryptedList, callback) { + var already, pubkeyIds = []; + + // gather public key ids required to verify signatures + encryptedList.forEach(function(i) { + already = null; + already = _.findWhere(pubkeyIds, { + _id: i.senderPk + }); + if (!already) { + pubkeyIds.push({ + _id: i.senderPk + }); + } + }); + + // fetch public keys from keychain + self._keychain.getPublicKeys(pubkeyIds, function(err, senderPubkeys) { + if (err) { + callback(err); + return; + } + + // verfiy signatures and re-encrypt item keys + self._crypto.decryptListForUser(encryptedList, senderPubkeys, function(err, decryptedList) { + if (err) { + callback(err); + return; + } + + callback(null, decryptedList); + }); + }); + } + }; + + /** + * High level sync operation for the delta from the user's IMAP inbox + */ + EmailDAO.prototype.imapSync = function(options, callback) { + var self = this; + + // validate options + if (!options.folder || typeof options.offset === 'undefined' || typeof options.num === 'undefined') { + callback({ + errMsg: 'Invalid options!' + }); + return; + } + + fetchList(options, function(emails) { + // persist encrypted list in device storage + self._devicestorage.storeEcryptedList(emails, 'email_' + options.folder, function() { + callback(); + }); + }); + + function fetchList(folder, callback) { + // fetch imap folder's message list + self.imapListMessages({ + folder: options.folder, + offset: options.offset, + num: options.num + }, function(err, emails) { + if (err) { + console.log(err); + return; + } + + // fetch message bodies + fetchBodies(emails, folder, function(messages) { + callback(messages); + }); + }); + } + + function fetchBodies(messageList, folder, callback) { + var emails = []; + + var after = _.after(messageList.length, function() { + callback(emails); + }); + + _.each(messageList, function(messageItem) { + self.imapGetMessage({ + folder: folder, + uid: messageItem.uid + }, function(err, message) { + if (err) { + console.log(err); + return; + } + + emails.push(message); + after(); + }); + }); + } + }; + /** * List messages from an imap folder. This will not yet fetch the email body. * @param {String} options.folderName The name of the imap folder. @@ -337,16 +502,6 @@ define(function(require) { return; } - // try fetching from cache before doing a roundtrip - message = self.readCache(options.folder, options.uid); - if (message) { - // message was fetched from cache successfully - callback(null, message); - return; - } - - /* message was not found in cache... fetch from imap server */ - function messageReady(err, gottenMessage) { message = gottenMessage; itemCounter++; @@ -358,68 +513,12 @@ define(function(require) { return; } - // decrypt Message body - if (message.body.indexOf(str.cryptPrefix) !== -1 && message.body.indexOf(str.cryptSuffix) !== -1) { - decryptBody(message, function(err, ptMessage) { - message = ptMessage; - // return decrypted message - callback(err, message); - }); - return; - } - - // return unencrypted message + // return message callback(null, message); //check(); } - function decryptBody(email, callback) { - var ctMessageBase64, ctMessageJson, ctMessage, pubkeyIds; - - // parse email body for encrypted message block - try { - // get base64 encoded message block - ctMessageBase64 = email.body.split(str.cryptPrefix)[1].split(str.cryptSuffix)[0].trim(); - // decode bae64 - ctMessageJson = atob(ctMessageBase64); - // parse json string to get ciphertext object - ctMessage = JSON.parse(ctMessageJson); - } catch (e) { - callback({ - errMsg: 'Error parsing encrypted message block!' - }); - return; - } - - // gather public key ids required to verify signatures - pubkeyIds = [{ - _id: ctMessage.senderPk - }]; - - // fetch public keys from keychain - self._keychain.getPublicKeys(pubkeyIds, function(err, senderPubkeys) { - if (err) { - callback(err); - return; - } - - // verfiy signatures and re-encrypt item keys - crypto.decryptListForUser([ctMessage], senderPubkeys, function(err, decryptedList) { - if (err) { - callback(err); - return; - } - - var ptEmail = decryptedList[0]; - email.body = ptEmail.body; - email.subject = ptEmail.subject; - - callback(null, email); - }); - }); - } - // function attachmentReady(err, gottenAttachment) { // attachments.push(gottenAttachment); // itemCounter++; diff --git a/src/js/dao/lawnchair-dao.js b/src/js/dao/lawnchair-dao.js index e8637ed..1623d8d 100644 --- a/src/js/dao/lawnchair-dao.js +++ b/src/js/dao/lawnchair-dao.js @@ -7,17 +7,22 @@ define(['lawnchair', 'lawnchairSQL', 'lawnchairIDB'], function(Lawnchair) { var self = {}, db; - self.init = function(dbName) { + self.init = function(dbName, callback) { + var temp; + if (!dbName) { throw new Error('Lawnchair DB name must be specified!'); } - db = new Lawnchair({ + temp = new Lawnchair({ name: dbName }, function(lc) { if (!lc) { throw new Error('Lawnchair init failed!'); } + + db = lc; + callback(); }); }; diff --git a/src/lib/moment/moment.min.js b/src/lib/moment/moment.min.js deleted file mode 100644 index 62b1697..0000000 --- a/src/lib/moment/moment.min.js +++ /dev/null @@ -1,6 +0,0 @@ -// moment.js -// version : 2.1.0 -// author : Tim Wood -// license : MIT -// momentjs.com -!function(t){function e(t,e){return function(n){return u(t.call(this,n),e)}}function n(t,e){return function(n){return this.lang().ordinal(t.call(this,n),e)}}function s(){}function i(t){a(this,t)}function r(t){var e=t.years||t.year||t.y||0,n=t.months||t.month||t.M||0,s=t.weeks||t.week||t.w||0,i=t.days||t.day||t.d||0,r=t.hours||t.hour||t.h||0,a=t.minutes||t.minute||t.m||0,o=t.seconds||t.second||t.s||0,u=t.milliseconds||t.millisecond||t.ms||0;this._input=t,this._milliseconds=u+1e3*o+6e4*a+36e5*r,this._days=i+7*s,this._months=n+12*e,this._data={},this._bubble()}function a(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}function o(t){return 0>t?Math.ceil(t):Math.floor(t)}function u(t,e){for(var n=t+"";n.lengthn;n++)~~t[n]!==~~e[n]&&r++;return r+i}function f(t){return t?ie[t]||t.toLowerCase().replace(/(.)s$/,"$1"):t}function l(t,e){return e.abbr=t,x[t]||(x[t]=new s),x[t].set(e),x[t]}function _(t){if(!t)return H.fn._lang;if(!x[t]&&A)try{require("./lang/"+t)}catch(e){return H.fn._lang}return x[t]}function m(t){return t.match(/\[.*\]/)?t.replace(/^\[|\]$/g,""):t.replace(/\\/g,"")}function y(t){var e,n,s=t.match(E);for(e=0,n=s.length;n>e;e++)s[e]=ue[s[e]]?ue[s[e]]:m(s[e]);return function(i){var r="";for(e=0;n>e;e++)r+=s[e]instanceof Function?s[e].call(i,t):s[e];return r}}function M(t,e){function n(e){return t.lang().longDateFormat(e)||e}for(var s=5;s--&&N.test(e);)e=e.replace(N,n);return re[e]||(re[e]=y(e)),re[e](t)}function g(t,e){switch(t){case"DDDD":return V;case"YYYY":return X;case"YYYYY":return $;case"S":case"SS":case"SSS":case"DDD":return I;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return R;case"a":case"A":return _(e._l)._meridiemParse;case"X":return B;case"Z":case"ZZ":return j;case"T":return q;case"MM":case"DD":case"YY":case"HH":case"hh":case"mm":case"ss":case"M":case"D":case"d":case"H":case"h":case"m":case"s":return J;default:return new RegExp(t.replace("\\",""))}}function p(t){var e=(j.exec(t)||[])[0],n=(e+"").match(ee)||["-",0,0],s=+(60*n[1])+~~n[2];return"+"===n[0]?-s:s}function D(t,e,n){var s,i=n._a;switch(t){case"M":case"MM":i[1]=null==e?0:~~e-1;break;case"MMM":case"MMMM":s=_(n._l).monthsParse(e),null!=s?i[1]=s:n._isValid=!1;break;case"D":case"DD":case"DDD":case"DDDD":null!=e&&(i[2]=~~e);break;case"YY":i[0]=~~e+(~~e>68?1900:2e3);break;case"YYYY":case"YYYYY":i[0]=~~e;break;case"a":case"A":n._isPm=_(n._l).isPM(e);break;case"H":case"HH":case"h":case"hh":i[3]=~~e;break;case"m":case"mm":i[4]=~~e;break;case"s":case"ss":i[5]=~~e;break;case"S":case"SS":case"SSS":i[6]=~~(1e3*("0."+e));break;case"X":n._d=new Date(1e3*parseFloat(e));break;case"Z":case"ZZ":n._useUTC=!0,n._tzm=p(e)}null==e&&(n._isValid=!1)}function Y(t){var e,n,s=[];if(!t._d){for(e=0;7>e;e++)t._a[e]=s[e]=null==t._a[e]?2===e?1:0:t._a[e];s[3]+=~~((t._tzm||0)/60),s[4]+=~~((t._tzm||0)%60),n=new Date(0),t._useUTC?(n.setUTCFullYear(s[0],s[1],s[2]),n.setUTCHours(s[3],s[4],s[5],s[6])):(n.setFullYear(s[0],s[1],s[2]),n.setHours(s[3],s[4],s[5],s[6])),t._d=n}}function w(t){var e,n,s=t._f.match(E),i=t._i;for(t._a=[],e=0;eo&&(u=o,s=n);a(t,s)}function v(t){var e,n=t._i,s=K.exec(n);if(s){for(t._f="YYYY-MM-DD"+(s[2]||" "),e=0;4>e;e++)if(te[e][1].exec(n)){t._f+=te[e][0];break}j.exec(n)&&(t._f+=" Z"),w(t)}else t._d=new Date(n)}function T(e){var n=e._i,s=G.exec(n);n===t?e._d=new Date:s?e._d=new Date(+s[1]):"string"==typeof n?v(e):d(n)?(e._a=n.slice(0),Y(e)):e._d=n instanceof Date?new Date(+n):new Date(n)}function b(t,e,n,s,i){return i.relativeTime(e||1,!!n,t,s)}function S(t,e,n){var s=W(Math.abs(t)/1e3),i=W(s/60),r=W(i/60),a=W(r/24),o=W(a/365),u=45>s&&["s",s]||1===i&&["m"]||45>i&&["mm",i]||1===r&&["h"]||22>r&&["hh",r]||1===a&&["d"]||25>=a&&["dd",a]||45>=a&&["M"]||345>a&&["MM",W(a/30)]||1===o&&["y"]||["yy",o];return u[2]=e,u[3]=t>0,u[4]=n,b.apply({},u)}function F(t,e,n){var s,i=n-e,r=n-t.day();return r>i&&(r-=7),i-7>r&&(r+=7),s=H(t).add("d",r),{week:Math.ceil(s.dayOfYear()/7),year:s.year()}}function O(t){var e=t._i,n=t._f;return null===e||""===e?null:("string"==typeof e&&(t._i=e=_().preparse(e)),H.isMoment(e)?(t=a({},e),t._d=new Date(+e._d)):n?d(n)?k(t):w(t):T(t),new i(t))}function z(t,e){H.fn[t]=H.fn[t+"s"]=function(t){var n=this._isUTC?"UTC":"";return null!=t?(this._d["set"+n+e](t),H.updateOffset(this),this):this._d["get"+n+e]()}}function C(t){H.duration.fn[t]=function(){return this._data[t]}}function L(t,e){H.duration.fn["as"+t]=function(){return+this/e}}for(var H,P,U="2.1.0",W=Math.round,x={},A="undefined"!=typeof module&&module.exports,G=/^\/?Date\((\-?\d+)/i,Z=/(\-)?(\d*)?\.?(\d+)\:(\d+)\:(\d+)\.?(\d{3})?/,E=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g,N=/(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,J=/\d\d?/,I=/\d{1,3}/,V=/\d{3}/,X=/\d{1,4}/,$=/[+\-]?\d{1,6}/,R=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,j=/Z|[\+\-]\d\d:?\d\d/i,q=/T/i,B=/[\+\-]?\d+(\.\d{1,3})?/,K=/^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,Q="YYYY-MM-DDTHH:mm:ssZ",te=[["HH:mm:ss.S",/(T| )\d\d:\d\d:\d\d\.\d{1,3}/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],ee=/([\+\-]|\d\d)/gi,ne="Date|Hours|Minutes|Seconds|Milliseconds".split("|"),se={Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6},ie={ms:"millisecond",s:"second",m:"minute",h:"hour",d:"day",w:"week",M:"month",y:"year"},re={},ae="DDD w W M D d".split(" "),oe="M D H h m s w W".split(" "),ue={M:function(){return this.month()+1},MMM:function(t){return this.lang().monthsShort(this,t)},MMMM:function(t){return this.lang().months(this,t)},D:function(){return this.date()},DDD:function(){return this.dayOfYear()},d:function(){return this.day()},dd:function(t){return this.lang().weekdaysMin(this,t)},ddd:function(t){return this.lang().weekdaysShort(this,t)},dddd:function(t){return this.lang().weekdays(this,t)},w:function(){return this.week()},W:function(){return this.isoWeek()},YY:function(){return u(this.year()%100,2)},YYYY:function(){return u(this.year(),4)},YYYYY:function(){return u(this.year(),5)},gg:function(){return u(this.weekYear()%100,2)},gggg:function(){return this.weekYear()},ggggg:function(){return u(this.weekYear(),5)},GG:function(){return u(this.isoWeekYear()%100,2)},GGGG:function(){return this.isoWeekYear()},GGGGG:function(){return u(this.isoWeekYear(),5)},e:function(){return this.weekday()},E:function(){return this.isoWeekday()},a:function(){return this.lang().meridiem(this.hours(),this.minutes(),!0)},A:function(){return this.lang().meridiem(this.hours(),this.minutes(),!1)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return~~(this.milliseconds()/100)},SS:function(){return u(~~(this.milliseconds()/10),2)},SSS:function(){return u(this.milliseconds(),3)},Z:function(){var t=-this.zone(),e="+";return 0>t&&(t=-t,e="-"),e+u(~~(t/60),2)+":"+u(~~t%60,2)},ZZ:function(){var t=-this.zone(),e="+";return 0>t&&(t=-t,e="-"),e+u(~~(10*t/6),4)},z:function(){return this.zoneAbbr()},zz:function(){return this.zoneName()},X:function(){return this.unix()}};ae.length;)P=ae.pop(),ue[P+"o"]=n(ue[P],P);for(;oe.length;)P=oe.pop(),ue[P+P]=e(ue[P],2);for(ue.DDDD=e(ue.DDD,3),s.prototype={set:function(t){var e,n;for(n in t)e=t[n],"function"==typeof e?this[n]=e:this["_"+n]=e},_months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),months:function(t){return this._months[t.month()]},_monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),monthsShort:function(t){return this._monthsShort[t.month()]},monthsParse:function(t){var e,n,s;for(this._monthsParse||(this._monthsParse=[]),e=0;12>e;e++)if(this._monthsParse[e]||(n=H([2e3,e]),s="^"+this.months(n,"")+"|^"+this.monthsShort(n,""),this._monthsParse[e]=new RegExp(s.replace(".",""),"i")),this._monthsParse[e].test(t))return e},_weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdays:function(t){return this._weekdays[t.day()]},_weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysShort:function(t){return this._weekdaysShort[t.day()]},_weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),weekdaysMin:function(t){return this._weekdaysMin[t.day()]},weekdaysParse:function(t){var e,n,s;for(this._weekdaysParse||(this._weekdaysParse=[]),e=0;7>e;e++)if(this._weekdaysParse[e]||(n=H([2e3,1]).day(e),s="^"+this.weekdays(n,"")+"|^"+this.weekdaysShort(n,"")+"|^"+this.weekdaysMin(n,""),this._weekdaysParse[e]=new RegExp(s.replace(".",""),"i")),this._weekdaysParse[e].test(t))return e},_longDateFormat:{LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D YYYY",LLL:"MMMM D YYYY LT",LLLL:"dddd, MMMM D YYYY LT"},longDateFormat:function(t){var e=this._longDateFormat[t];return!e&&this._longDateFormat[t.toUpperCase()]&&(e=this._longDateFormat[t.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(t){return t.slice(1)}),this._longDateFormat[t]=e),e},isPM:function(t){return"p"===(t+"").toLowerCase()[0]},_meridiemParse:/[ap]\.?m?\.?/i,meridiem:function(t,e,n){return t>11?n?"pm":"PM":n?"am":"AM"},_calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},calendar:function(t,e){var n=this._calendar[t];return"function"==typeof n?n.apply(e):n},_relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},relativeTime:function(t,e,n,s){var i=this._relativeTime[n];return"function"==typeof i?i(t,e,n,s):i.replace(/%d/i,t)},pastFuture:function(t,e){var n=this._relativeTime[t>0?"future":"past"];return"function"==typeof n?n(e):n.replace(/%s/i,e)},ordinal:function(t){return this._ordinal.replace("%d",t)},_ordinal:"%d",preparse:function(t){return t},postformat:function(t){return t},week:function(t){return F(t,this._week.dow,this._week.doy).week},_week:{dow:0,doy:6}},H=function(t,e,n){return O({_i:t,_f:e,_l:n,_isUTC:!1})},H.utc=function(t,e,n){return O({_useUTC:!0,_isUTC:!0,_l:n,_i:t,_f:e})},H.unix=function(t){return H(1e3*t)},H.duration=function(t,e){var n,s,i=H.isDuration(t),a="number"==typeof t,o=i?t._input:a?{}:t,u=Z.exec(t);return a?e?o[e]=t:o.milliseconds=t:u&&(n="-"===u[1]?-1:1,o={y:0,d:~~u[2]*n,h:~~u[3]*n,m:~~u[4]*n,s:~~u[5]*n,ms:~~u[6]*n}),s=new r(o),i&&t.hasOwnProperty("_lang")&&(s._lang=t._lang),s},H.version=U,H.defaultFormat=Q,H.updateOffset=function(){},H.lang=function(t,e){return t?(e?l(t,e):x[t]||_(t),H.duration.fn._lang=H.fn._lang=_(t),void 0):H.fn._lang._abbr},H.langData=function(t){return t&&t._lang&&t._lang._abbr&&(t=t._lang._abbr),_(t)},H.isMoment=function(t){return t instanceof i},H.isDuration=function(t){return t instanceof r},H.fn=i.prototype={clone:function(){return H(this)},valueOf:function(){return+this._d+6e4*(this._offset||0)},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){return M(H(this).utc(),"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},toArray:function(){var t=this;return[t.year(),t.month(),t.date(),t.hours(),t.minutes(),t.seconds(),t.milliseconds()]},isValid:function(){return null==this._isValid&&(this._isValid=this._a?!c(this._a,(this._isUTC?H.utc(this._a):H(this._a)).toArray()):!isNaN(this._d.getTime())),!!this._isValid},utc:function(){return this.zone(0)},local:function(){return this.zone(0),this._isUTC=!1,this},format:function(t){var e=M(this,t||H.defaultFormat);return this.lang().postformat(e)},add:function(t,e){var n;return n="string"==typeof t?H.duration(+e,t):H.duration(t,e),h(this,n,1),this},subtract:function(t,e){var n;return n="string"==typeof t?H.duration(+e,t):H.duration(t,e),h(this,n,-1),this},diff:function(t,e,n){var s,i,r=this._isUTC?H(t).zone(this._offset||0):H(t).local(),a=6e4*(this.zone()-r.zone());return e=f(e),"year"===e||"month"===e?(s=432e5*(this.daysInMonth()+r.daysInMonth()),i=12*(this.year()-r.year())+(this.month()-r.month()),i+=(this-H(this).startOf("month")-(r-H(r).startOf("month")))/s,i-=6e4*(this.zone()-H(this).startOf("month").zone()-(r.zone()-H(r).startOf("month").zone()))/s,"year"===e&&(i/=12)):(s=this-r,i="second"===e?s/1e3:"minute"===e?s/6e4:"hour"===e?s/36e5:"day"===e?(s-a)/864e5:"week"===e?(s-a)/6048e5:s),n?i:o(i)},from:function(t,e){return H.duration(this.diff(t)).lang(this.lang()._abbr).humanize(!e)},fromNow:function(t){return this.from(H(),t)},calendar:function(){var t=this.diff(H().startOf("day"),"days",!0),e=-6>t?"sameElse":-1>t?"lastWeek":0>t?"lastDay":1>t?"sameDay":2>t?"nextDay":7>t?"nextWeek":"sameElse";return this.format(this.lang().calendar(e,this))},isLeapYear:function(){var t=this.year();return 0===t%4&&0!==t%100||0===t%400},isDST:function(){return this.zone()+H(t).startOf(e)},isBefore:function(t,e){return e="undefined"!=typeof e?e:"millisecond",+this.clone().startOf(e)<+H(t).startOf(e)},isSame:function(t,e){return e="undefined"!=typeof e?e:"millisecond",+this.clone().startOf(e)===+H(t).startOf(e)},min:function(t){return t=H.apply(null,arguments),this>t?this:t},max:function(t){return t=H.apply(null,arguments),t>this?this:t},zone:function(t){var e=this._offset||0;return null==t?this._isUTC?e:this._d.getTimezoneOffset():("string"==typeof t&&(t=p(t)),Math.abs(t)<16&&(t=60*t),this._offset=t,this._isUTC=!0,e!==t&&h(this,H.duration(e-t,"m"),1,!0),this)},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},daysInMonth:function(){return H.utc([this.year(),this.month()+1,0]).date()},dayOfYear:function(t){var e=W((H(this).startOf("day")-H(this).startOf("year"))/864e5)+1;return null==t?e:this.add("d",t-e)},weekYear:function(t){var e=F(this,this.lang()._week.dow,this.lang()._week.doy).year;return null==t?e:this.add("y",t-e)},isoWeekYear:function(t){var e=F(this,1,4).year;return null==t?e:this.add("y",t-e)},week:function(t){var e=this.lang().week(this);return null==t?e:this.add("d",7*(t-e))},isoWeek:function(t){var e=F(this,1,4).week;return null==t?e:this.add("d",7*(t-e))},weekday:function(t){var e=(this._d.getDay()+7-this.lang()._week.dow)%7;return null==t?e:this.add("d",t-e)},isoWeekday:function(t){return null==t?this.day()||7:this.day(this.day()%7?t:t-7)},lang:function(e){return e===t?this._lang:(this._lang=_(e),this)}},P=0;P{{email.from[0].name || email.from[0].address}}

{{email.subject}}

- +

{{email.body}}

diff --git a/src/tpl/read.html b/src/tpl/read.html index ed79dd8..fedb4eb 100644 --- a/src/tpl/read.html +++ b/src/tpl/read.html @@ -7,7 +7,7 @@

{{selected.subject}}

-

{{selected.longDisplayDate}}

+

{{selected.sentDate | date:'EEEE, MMM d, yyyy h:mm a'}}

From: {{selected.from[0].name || selected.from[0].address}}

To: {{t.address}}

diff --git a/test/new-unit/email-dao-test.js b/test/new-unit/email-dao-test.js index 70ae2ec..4283d8f 100644 --- a/test/new-unit/email-dao-test.js +++ b/test/new-unit/email-dao-test.js @@ -3,8 +3,10 @@ define(function(require) { var KeychainDAO = require('js/dao/keychain-dao'), EmailDAO = require('js/dao/email-dao'), + DeviceStorageDAO = require('js/dao/devicestorage-dao'), SmtpClient = require('smtp-client'), ImapClient = require('imap-client'), + Crypto = require('js/crypto/crypto'), app = require('js/app-config'), expect = chai.expect; @@ -19,12 +21,12 @@ define(function(require) { var publicKey = "-----BEGIN PUBLIC KEY-----\r\n" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxy+Te5dyeWd7g0P+8LNO7fZDQ\r\n" + "g96xTb1J6pYE/pPTMlqhB6BRItIYjZ1US5q2vk5Zk/5KasBHAc9RbCqvh9v4XFEY\r\n" + "JVmTXC4p8ft1LYuNWIaDk+R3dyYXmRNct/JC4tks2+8fD3aOvpt0WNn3R75/FGBt\r\n" + "h4BgojAXDE+PRQtcVQIDAQAB\r\n" + "-----END PUBLIC KEY-----"; describe('Email DAO unit tests', function() { - this.timeout(20000); var emailDao, account, - keychainStub, imapClientStub, smtpClientStub; + keychainStub, imapClientStub, smtpClientStub, cryptoStub, devicestorageStub; beforeEach(function() { + // init dummy object dummyMail = { from: [{ name: 'Whiteout Test', @@ -47,8 +49,10 @@ define(function(require) { keychainStub = sinon.createStubInstance(KeychainDAO); imapClientStub = sinon.createStubInstance(ImapClient); smtpClientStub = sinon.createStubInstance(SmtpClient); + cryptoStub = sinon.createStubInstance(Crypto); + devicestorageStub = sinon.createStubInstance(DeviceStorageDAO); - emailDao = new EmailDAO(keychainStub, imapClientStub, smtpClientStub); + emailDao = new EmailDAO(keychainStub, imapClientStub, smtpClientStub, cryptoStub, devicestorageStub); }); afterEach(function() {}); @@ -65,9 +69,11 @@ define(function(require) { it('should fail due to error in getUserKeyPair', function(done) { imapClientStub.login.yields(); + devicestorageStub.init.yields(); keychainStub.getUserKeyPair.yields(42); emailDao.init(account, emaildaoTest.passphrase, function(err) { + expect(devicestorageStub.init.calledOnce).to.be.true; expect(imapClientStub.login.calledOnce).to.be.true; expect(err).to.equal(42); done(); @@ -76,12 +82,16 @@ define(function(require) { it('should init with new keygen', function(done) { imapClientStub.login.yields(); + devicestorageStub.init.yields(); keychainStub.getUserKeyPair.yields(); + cryptoStub.init.yields(null, {}); keychainStub.putUserKeyPair.yields(); emailDao.init(account, emaildaoTest.passphrase, function(err) { expect(imapClientStub.login.calledOnce).to.be.true; + expect(devicestorageStub.init.calledOnce).to.be.true; expect(keychainStub.getUserKeyPair.calledOnce).to.be.true; + expect(cryptoStub.init.calledOnce).to.be.true; expect(keychainStub.putUserKeyPair.calledOnce).to.be.true; expect(err).to.not.exist; done(); @@ -92,12 +102,16 @@ define(function(require) { describe('IMAP/SMTP tests', function() { beforeEach(function(done) { imapClientStub.login.yields(); + devicestorageStub.init.yields(); keychainStub.getUserKeyPair.yields(); + cryptoStub.init.yields(null, {}); keychainStub.putUserKeyPair.yields(); emailDao.init(account, emaildaoTest.passphrase, function(err) { expect(imapClientStub.login.calledOnce).to.be.true; + expect(devicestorageStub.init.calledOnce).to.be.true; expect(keychainStub.getUserKeyPair.calledOnce).to.be.true; + expect(cryptoStub.init.calledOnce).to.be.true; expect(keychainStub.putUserKeyPair.calledOnce).to.be.true; expect(err).to.not.exist; done(); @@ -141,11 +155,11 @@ define(function(require) { emailDao.smtpSend(dummyMail, function(err) { expect(keychainStub.getReveiverPublicKey.calledOnce).to.be.true; - expect(smtpClientStub.send.calledOnce).to.be.true; - smtpClientStub.send.calledWith(sinon.match(function(o) { - return typeof o.attachments === 'undefined'; - })); - expect(err).to.not.exist; + // expect(smtpClientStub.send.called).to.be.true; + // smtpClientStub.send.calledWith(sinon.match(function(o) { + // return typeof o.attachments === 'undefined'; + // })); + expect(err).to.exist; done(); }); }); @@ -157,6 +171,7 @@ define(function(require) { publicKey: publicKey }); smtpClientStub.send.yields(); + cryptoStub.encryptListForUser.yields(null, []); emailDao.smtpSend(dummyMail, function(err) { expect(keychainStub.getReveiverPublicKey.calledOnce).to.be.true; @@ -181,6 +196,7 @@ define(function(require) { publicKey: publicKey }); smtpClientStub.send.yields(); + cryptoStub.encryptListForUser.yields(null, [{}, {}]); emailDao.smtpSend(dummyMail, function(err) { expect(keychainStub.getReveiverPublicKey.calledOnce).to.be.true; @@ -344,6 +360,61 @@ define(function(require) { // }); // }); }); + + describe('IMAP: sync messages to local storage', function() { + it('should work', function(done) { + imapClientStub.listMessages.yields(null, [{ + uid: 413, + }, { + uid: 414, + }]); + imapClientStub.getMessage.yields(null, { + body: 'asdf' + }); + devicestorageStub.storeEcryptedList.yields(); + + emailDao.imapSync({ + folder: 'INBOX', + offset: 0, + num: 2 + }, function(err) { + expect(err).to.not.exist; + expect(imapClientStub.listMessages.calledOnce).to.be.true; + expect(imapClientStub.getMessage.calledTwice).to.be.true; + expect(devicestorageStub.storeEcryptedList.calledOnce).to.be.true; + done(); + }); + }); + }); + + describe('IMAP: list messages from local storage', function() { + it('should work', function(done) { + + devicestorageStub.listEncryptedItems.yields(null, [{ + body: '' + }]); + keychainStub.getPublicKeys.yields(null, [{ + _id: "fcf8b4aa-5d09-4089-8b4f-e3bc5091daf3", + userId: "safewithme.testuser@gmail.com", + publicKey: publicKey + }]); + cryptoStub.decryptListForUser.yields(null, []); + + emailDao.listMessages({ + folder: 'INBOX', + offset: 0, + num: 2 + }, function(err, emails) { + expect(devicestorageStub.listEncryptedItems.calledOnce).to.be.true; + expect(keychainStub.getPublicKeys.calledOnce).to.be.true; + expect(cryptoStub.decryptListForUser.calledOnce).to.be.true; + expect(err).to.not.exist; + expect(emails.length).to.equal(0); + done(); + }); + }); + }); + }); }); diff --git a/test/unit/crypto-test.js b/test/unit/crypto-test.js index 4aa1276..8b75d72 100644 --- a/test/unit/crypto-test.js +++ b/test/unit/crypto-test.js @@ -1,4 +1,4 @@ -define(['js/crypto/crypto', 'cryptoLib/util', 'test/test-data'], function(crypto, util, testData) { +define(['js/crypto/crypto', 'cryptoLib/util', 'test/test-data'], function(Crypto, util, testData) { 'use strict'; module("Crypto Api"); @@ -11,7 +11,10 @@ define(['js/crypto/crypto', 'cryptoLib/util', 'test/test-data'], function(crypto rsaKeySize: 1024 }; + var crypto; + asyncTest("Init without keypair", 4, function() { + crypto = new Crypto(); // init dependencies ok(crypto, 'Crypto'); diff --git a/test/unit/devicestorage-dao-test.js b/test/unit/devicestorage-dao-test.js index becddd0..5e6ace3 100644 --- a/test/unit/devicestorage-dao-test.js +++ b/test/unit/devicestorage-dao-test.js @@ -1,94 +1,97 @@ -define(['underscore', 'cryptoLib/util', 'js/crypto/crypto', 'js/dao/lawnchair-dao', - 'js/dao/devicestorage-dao', 'test/test-data' -], function(_, util, crypto, jsonDao, storage, testData) { - 'use strict'; +define(['underscore', 'cryptoLib/util', 'js/crypto/crypto', 'js/dao/devicestorage-dao', 'test/test-data'], function(_, util, Crypto, DeviceStorageDAO, testData) { + 'use strict'; - module("DeviceStorage"); + module("DeviceStorage"); - var devicestorageTest = { - user: 'devicestorage_test@example.com', - password: 'Password', - keySize: 128, - ivSize: 128, - rsaKeySize: 1024 - }; + var devicestorageTest = { + user: 'devicestorage_test@example.com', + password: 'Password', + keySize: 128, + ivSize: 128, + rsaKeySize: 1024 + }; - asyncTest("Init", 3, function() { - // init dependencies - jsonDao.init(devicestorageTest.user); - ok(storage, 'DeviceStorageDAO'); + var crypto, storage; - // generate test data - devicestorageTest.list = testData.getEmailCollection(100); + asyncTest("Init", 3, function() { + // init dependencies + storage = new DeviceStorageDAO(); + storage.init(devicestorageTest.user, function() { + ok(storage, 'DeviceStorageDAO'); - // init crypto - crypto.init({ - emailAddress: devicestorageTest.user, - password: devicestorageTest.password, - keySize: devicestorageTest.keySize, - rsaKeySize: devicestorageTest.rsaKeySize - }, function(err, generatedKeypair) { - ok(!err && generatedKeypair, 'Init crypto'); - devicestorageTest.generatedKeypair = generatedKeypair; + // generate test data + devicestorageTest.list = testData.getEmailCollection(100); - // clear db before tests - jsonDao.clear(function(err) { - ok(!err, 'DB cleared. Error status: ' + err); + // init crypto + crypto = new Crypto(); + crypto.init({ + emailAddress: devicestorageTest.user, + password: devicestorageTest.password, + keySize: devicestorageTest.keySize, + rsaKeySize: devicestorageTest.rsaKeySize + }, function(err, generatedKeypair) { + ok(!err && generatedKeypair, 'Init crypto'); + devicestorageTest.generatedKeypair = generatedKeypair; - start(); - }); + // clear db before tests + storage.clear(function(err) { + ok(!err, 'DB cleared. Error status: ' + err); - }); - }); + start(); + }); - asyncTest("Encrypt list for user", 2, function() { - var receiverPubkeys = [devicestorageTest.generatedKeypair.publicKey]; + }); + }); + }); - crypto.encryptListForUser(devicestorageTest.list, receiverPubkeys, function(err, encryptedList) { - ok(!err); - equal(encryptedList.length, devicestorageTest.list.length, 'Encrypt list'); + asyncTest("Encrypt list for user", 2, function() { + var receiverPubkeys = [devicestorageTest.generatedKeypair.publicKey]; - encryptedList.forEach(function(i) { - i.sentDate = _.findWhere(devicestorageTest.list, { - id: i.id - }).sentDate; - }); + crypto.encryptListForUser(devicestorageTest.list, receiverPubkeys, function(err, encryptedList) { + ok(!err); + equal(encryptedList.length, devicestorageTest.list.length, 'Encrypt list'); - devicestorageTest.encryptedList = encryptedList; - start(); - }); - }); + encryptedList.forEach(function(i) { + i.sentDate = _.findWhere(devicestorageTest.list, { + id: i.id + }).sentDate; + }); - asyncTest("Store encrypted list", 1, function() { - storage.storeEcryptedList(devicestorageTest.encryptedList, 'email_inbox', function() { - ok(true, 'Store encrypted list'); + devicestorageTest.encryptedList = encryptedList; + start(); + }); + }); - start(); - }); - }); + asyncTest("Store encrypted list", 1, function() { + storage.storeEcryptedList(devicestorageTest.encryptedList, 'email_inbox', function() { + ok(true, 'Store encrypted list'); - asyncTest("List items", 4, function() { + start(); + }); + }); - var senderPubkeys = [devicestorageTest.generatedKeypair.publicKey]; + asyncTest("List items", 4, function() { - var offset = 2, - num = 6; + var senderPubkeys = [devicestorageTest.generatedKeypair.publicKey]; - // list encrypted items from storage - storage.listEncryptedItems('email_inbox', offset, num, function(err, encryptedList) { - ok(!err); + var offset = 2, + num = 6; - // decrypt list - crypto.decryptListForUser(encryptedList, senderPubkeys, function(err, decryptedList) { - ok(!err); - equal(decryptedList.length, num, 'Found ' + decryptedList.length + ' items in store (and decrypted)'); + // list encrypted items from storage + storage.listEncryptedItems('email_inbox', offset, num, function(err, encryptedList) { + ok(!err); - var origSet = devicestorageTest.list.splice(92, num); - deepEqual(decryptedList, origSet, 'Messages decrypted correctly'); + // decrypt list + crypto.decryptListForUser(encryptedList, senderPubkeys, function(err, decryptedList) { + ok(!err); + equal(decryptedList.length, num, 'Found ' + decryptedList.length + ' items in store (and decrypted)'); - start(); - }); - }); - }); + var origSet = devicestorageTest.list.splice(92, num); + deepEqual(decryptedList, origSet, 'Messages decrypted correctly'); + + start(); + }); + }); + }); }); \ No newline at end of file diff --git a/test/unit/keychain-dao-test.js b/test/unit/keychain-dao-test.js index 8d4a4cc..8424c3b 100644 --- a/test/unit/keychain-dao-test.js +++ b/test/unit/keychain-dao-test.js @@ -28,11 +28,12 @@ define(['js/dao/keychain-dao', 'js/dao/lawnchair-dao'], function(KeychainDAO, js ok(keychaindaoTest.keychainDao); // init and clear db before test - jsonDao.init(keychaindaoTest.user); - jsonDao.clear(function() { - ok(true, 'cleared db'); + jsonDao.init(keychaindaoTest.user, function() { + jsonDao.clear(function() { + ok(true, 'cleared db'); - start(); + start(); + }); }); }); @@ -70,9 +71,8 @@ define(['js/dao/keychain-dao', 'js/dao/lawnchair-dao'], function(KeychainDAO, js asyncTest("Get Public Keys", 2, function() { var pubkeyIds = [{ - _id: keychaindaoTest.keypair.publicKey._id - } - ]; + _id: keychaindaoTest.keypair.publicKey._id + }]; keychaindaoTest.keychainDao.getPublicKeys(pubkeyIds, function(err, pubkeys) { ok(!err); deepEqual(pubkeys[0], keychaindaoTest.keypair.publicKey, "Fetch public key"); diff --git a/test/unit/lawnchair-dao-test.js b/test/unit/lawnchair-dao-test.js index 1ed9675..ec9b72a 100644 --- a/test/unit/lawnchair-dao-test.js +++ b/test/unit/lawnchair-dao-test.js @@ -9,14 +9,15 @@ define(['js/dao/lawnchair-dao'], function(jsonDao) { asyncTest("Init", 2, function() { // init dependencies - jsonDao.init(lawnchairdaoTest.user); - ok(jsonDao, 'LanwchairDAO'); + jsonDao.init(lawnchairdaoTest.user, function() { + ok(true, 'init db'); - // clear db before test - jsonDao.clear(function() { - ok(true, 'cleared db'); + // clear db before test + jsonDao.clear(function() { + ok(true, 'cleared db'); - start(); + start(); + }); }); });