diff --git a/index.js b/index.js index 874306a3..09f3b153 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,10 @@ var PouchPromise = require('pouchdb-promise'); var configId = '_local/crypto'; var transform = require('transform-pouch').transform; var uuid = require('node-uuid'); +function InvalidPasswordError () { + this.name = 'InvalidPasswordError'; + this.message = 'unable to authenticate' +} function genKey(password, salt) { return new PouchPromise(function (resolve, reject) { pbkdf2.pbkdf2(password, salt, 1000, 256 / 8, function (err, key) { @@ -26,7 +30,7 @@ function cryptoInit(password, options) { if (options && options.ignore) { ignore = ignore.concat(options.ignore) } - + var pending = db.get(configId).then(function (doc){ if (!doc.salt) { throw { @@ -70,7 +74,11 @@ function cryptoInit(password, options) { }, outgoing: function (doc) { return pending.then(function () { - return decrypt(doc); + try { + return decrypt(doc); + } catch (err) { + throw new InvalidPasswordError(); + } }); } }); diff --git a/test.js b/test.js index 956fb823..3f5643e0 100644 --- a/test.js +++ b/test.js @@ -113,3 +113,17 @@ test('throws error when document has attachments', function (t) { t.ok(/Attachments cannot be encrypted/.test(e.message), 'throws error'); }) }) +test('wrong password', function (t) { + t.plan(1); + var dbName = 'nine'; + var db = new PouchDB(dbName, {db: memdown}); + db.crypto('correct') + db.put({foo: 'bar'}, 'baz').then(function () { + db.crypto('wrong') + return db.get('baz'); + }).then(function (doc) { + t.fail('retrieved document with bad password') + }).catch(function (err) { + t.equals(err.name, 'InvalidPasswordError', 'returns correct error.') + }) +});