From 0e510d1838162e2cb50f7712ae263542e2f8c525 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 14 Feb 2016 12:28:15 +0100 Subject: [PATCH 001/124] version 1.0.0 on npm --- .npmignore | 2 + .travis.yml | 3 ++ LICENSE | 21 +++++++++ README.md | 21 +++++++++ lesspass.js | 12 +++++ package.json | 35 ++++++++++++++ password-generator.js | 44 ++++++++++++++++++ tests/lesspass.tests.js | 52 +++++++++++++++++++++ tests/password-generator.tests.js | 97 +++++++++++++++++++++++++++++++++++++++ tests/text.tests.js | 34 ++++++++++++++ text.js | 45 ++++++++++++++++++ 11 files changed, 366 insertions(+) create mode 100644 .npmignore create mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 lesspass.js create mode 100644 package.json create mode 100644 password-generator.js create mode 100644 tests/lesspass.tests.js create mode 100644 tests/password-generator.tests.js create mode 100644 tests/text.tests.js create mode 100644 text.js diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..6bd575e --- /dev/null +++ b/.npmignore @@ -0,0 +1,2 @@ +.travis.yml +tests \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..92a1e92 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 4 \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d10fcd8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Guillaume Vincent + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7644a21 --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +# LessPass Core + +LessPass npm module use to generate unique password + +## Install + + npm install lesspass + +## Usage + + var lesspass = require('lesspass'); + var entry = { + site: 'lesspass', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + var masterPassword = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + passwordGenerator.generatePassword(masterPassword, entry); diff --git a/lesspass.js b/lesspass.js new file mode 100644 index 0000000..d70a208 --- /dev/null +++ b/lesspass.js @@ -0,0 +1,12 @@ +var text = require('./text'); +var passwordGenerator = require('./password-generator'); + +module.exports = { + createPassword: createPassword +}; + +function createPassword(masterPassword, entry) { + var hash = passwordGenerator._createHash(masterPassword, entry); + var template = passwordGenerator._getTemplate(entry.password.settings); + return text._encode(hash, template); +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..91726ae --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "lesspass", + "version": "1.0.0", + "description": "node.js stateless password management solution", + "main": "index.js", + "scripts": { + "test": "mocha --compilers js:babel-core/register tests", + "test:watch": "npm run test -- -w" + }, + "keywords": [ + "password", + "lesspass" + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com:oslab-fr/lesspass-npm.git" + }, + "author": "Guillaume Vincent", + "license": "MIT", + "bugs": { + "url": "https://github.com/oslab-fr/lesspass-npm/issues" + }, + "homepage": "https://github.com/oslab-fr/lesspass-npm#readme", + "devDependencies": { + "babel-core": "^6.5.2", + "babel-preset-es2015": "^6.5.0", + "mocha": "^2.4.5", + "webpack": "^1.12.13" + }, + "babel": { + "presets": [ + "es2015" + ] + } +} diff --git a/password-generator.js b/password-generator.js new file mode 100644 index 0000000..da4b113 --- /dev/null +++ b/password-generator.js @@ -0,0 +1,44 @@ +var crypto = require('crypto'); + +module.exports = { + createMasterPassword: createMasterPassword, + _getTemplate: _getTemplate, + _createHash:_createHash +}; + + +function createMasterPassword(email, password) { + return new Promise((resolve, reject) => { + var iterations = 8192; + var keylen = 32; + crypto.pbkdf2(password, email, iterations, keylen, 'sha256', function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); +} + +function _getTemplate(passwordTypes = ['strong']) { + var passwordTypesInfo = { + lowercase: {value: 'vc', order: 1}, + uppercase: {value: 'VC', order: 2}, + numbers: {value: 'n', order: 3}, + symbols: {value: 's', order: 4}, + strong: {value: 'Cvcvns', order: 5} + }; + return passwordTypes + .map(passwordType => passwordTypesInfo[passwordType]) + .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) + .map(passwordType => passwordType.value) + .join(''); +} + + +function _createHash(masterPassword, {site, password={length: 12, counter: 1}}) { + var salt = site + password.counter.toString(); + var hash = crypto.createHmac('sha256', masterPassword).update(salt).digest('hex'); + return hash.substring(0, password.length); +} \ No newline at end of file diff --git a/tests/lesspass.tests.js b/tests/lesspass.tests.js new file mode 100644 index 0000000..c3aafbf --- /dev/null +++ b/tests/lesspass.tests.js @@ -0,0 +1,52 @@ +var assert = require('assert'); +var lesspass = require('../lesspass'); + +describe('lesspass', function () { + it('should create password', function () { + var masterPassword = "password"; + var entry = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + assert.equal('iwIQ8[acYT4&oc', lesspass.createPassword(masterPassword, entry)); + }); + it('should create password 2', function () { + var masterPassword = "password"; + var entry = { + site: 'facebook', + password: { + length: 12, + settings: ['strong'], + counter: 1 + } + }; + assert.equal('Vexu8[Syce4&', lesspass.createPassword(masterPassword, entry)); + }); + it('should create 2 passwords different if counter different', function () { + var masterPassword = "password"; + var entry = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + var entry2 = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 2 + } + }; + assert.notEqual( + lesspass.createPassword(masterPassword, entry), + lesspass.createPassword(masterPassword, entry2) + ); + }); +}); diff --git a/tests/password-generator.tests.js b/tests/password-generator.tests.js new file mode 100644 index 0000000..6e1991f --- /dev/null +++ b/tests/password-generator.tests.js @@ -0,0 +1,97 @@ +var assert = require('assert'); +var passwordGenerator = require('../password-generator'); + +describe('passwordGenerator', function () { + describe('master password', function () { + it('should create master password with pbkdf2 (8192 iterations and sha 256)', function (done) { + var email = 'test@lesspass.com'; + var password = "password"; + + passwordGenerator.createMasterPassword(email, password).then(function (masterPassword) { + assert.equal("90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d", masterPassword); + done(); + }); + }); + it('should create 64 char length master password', function (done) { + var email = 'test@lesspass.com'; + var password = "password"; + + passwordGenerator.createMasterPassword(email, password).then(function (masterPassword) { + assert.equal(64, masterPassword.length); + done(); + }); + }); + }); + describe('password templates password', function () { + it('should get default template from password type', function () { + assert.equal('Cvcvns', passwordGenerator._getTemplate()); + }); + it('should get template from password type', function () { + assert.equal('vc', passwordGenerator._getTemplate(['lowercase'])); + assert.equal('VC', passwordGenerator._getTemplate(['uppercase'])); + assert.equal('n', passwordGenerator._getTemplate(['numbers'])); + assert.equal('s', passwordGenerator._getTemplate(['symbols'])); + }); + it('should concatenate template if two password password_types', function () { + assert.equal('vcVC', passwordGenerator._getTemplate(['lowercase', 'uppercase'])); + assert.equal('vcns', passwordGenerator._getTemplate(['lowercase', 'numbers', 'symbols'])); + }); + it('should not care about order of type in password password_types', function () { + assert.equal( + passwordGenerator._getTemplate(['uppercase', 'lowercase']), + passwordGenerator._getTemplate(['lowercase', 'uppercase']) + ); + }); + }); + describe('hash', function () { + it('should have default length of 12', function () { + var masterPassword = 'password'; + var entry = {'site': 'facebook'}; + assert.equal(12, passwordGenerator._createHash(masterPassword, entry).length); + }); + it('should allow to change default length', function () { + var masterPassword = 'password'; + var entry = { + site: 'lesspass', + password: { + length: 10, + counter: 1 + } + }; + assert.equal(10, passwordGenerator._createHash(masterPassword, entry).length); + }); + it('should return two different passwords if site different', function () { + var masterPassword = 'password'; + var entry = {site: 'facebook'}; + var entry2 = {site: 'google'}; + assert.notEqual( + passwordGenerator._createHash(masterPassword, entry), + passwordGenerator._createHash(masterPassword, entry2) + ); + }); + it('should return two different passwords if counter different', function () { + var masterPassword = 'password'; + var entry = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + var entry2 = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 2 + } + }; + assert.notEqual( + passwordGenerator._createHash(masterPassword, entry), + passwordGenerator._createHash(masterPassword, entry2) + ); + }); + }); + +}); diff --git a/tests/text.tests.js b/tests/text.tests.js new file mode 100644 index 0000000..b567ded --- /dev/null +++ b/tests/text.tests.js @@ -0,0 +1,34 @@ +var assert = require('assert'); +var text = require('../text'); + +describe('crypto', function () { + it('should return char inside a string based on modulo of the index', function () { + var template = 'cv'; + assert.equal('c', text._getCharType(template, 0)); + assert.equal('v', text._getCharType(template, 1)); + assert.equal('c', text._getCharType(template, 10)); + }); + it('should convert a string into an array of char code', function () { + var charCodes = text._string2charCodes('ab40f6ee71'); + assert.equal(97, charCodes[0]); + assert.equal(98, charCodes[1]); + assert.equal(10, charCodes.length); + }); + it('must return a string of the same length as the input', function () { + var hash = 'Y2Vi2a112A'; + assert.equal(hash.length, text._encode(hash, 'cv').length); + }); + it('should return different values if strings different', function () { + var hash = 'a'; + assert.notEqual(text._encode(hash, 'cv'), text._encode(hash, 'vc')); + }); + it('should get password char based on its type and index', function () { + var typeVowel = 'V'; + assert.equal('A', text._getPasswordChar(typeVowel, 0)); + }); + it('should modulo if overflow', function () { + var typeVowel = 'V'; + assert.equal('E', text._getPasswordChar(typeVowel, 1)); + assert.equal('E', text._getPasswordChar(typeVowel, 7)); + }); +}); diff --git a/text.js b/text.js new file mode 100644 index 0000000..a394370 --- /dev/null +++ b/text.js @@ -0,0 +1,45 @@ +module.exports = { + _getCharType: _getCharType, + _getPasswordChar: _getPasswordChar, + _encode: _encode, + _string2charCodes: _string2charCodes +}; + +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + var passwordsChars = { + V: "AEIOUY", + C: "BCDFGHJKLMNPQRSTVWXZ", + v: "aeiouy", + c: "bcdfghjklmnpqrstvwxz", + A: "AEIOUYBCDFGHJKLMNPQRSTVWXZ", + a: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz", + n: "0123456789", + s: "@&%?,=[]_:-+*$#!'^~;()/.", + x: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!'^~;()/." + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function _encode(hash, template) { + var password = ''; + _string2charCodes(hash).map( + (charCode, index) => { + let charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + } + ); + return password; +} + +function _string2charCodes(text) { + var charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} \ No newline at end of file From c86eaefaf859e4af1812347852c2344d5a7dda02 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 14 Feb 2016 13:32:39 +0100 Subject: [PATCH 002/124] update documentation --- .gitignore | 1 + README.md | 4 +++- package.json | 10 ++++++---- 3 files changed, 10 insertions(+), 5 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a510caa --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +distribution \ No newline at end of file diff --git a/README.md b/README.md index 7644a21..95eb8f2 100644 --- a/README.md +++ b/README.md @@ -18,4 +18,6 @@ LessPass npm module use to generate unique password } }; var masterPassword = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - passwordGenerator.generatePassword(masterPassword, entry); + var password = lesspass.createPassword(masterPassword, entry); + console.log(password); // ubUB4[yqAD3?od + diff --git a/package.json b/package.json index 91726ae..1638ce4 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,13 @@ { "name": "lesspass", - "version": "1.0.0", + "version": "1.0.3", "description": "node.js stateless password management solution", - "main": "index.js", + "main": "distribution/lesspass.js", "scripts": { "test": "mocha --compilers js:babel-core/register tests", - "test:watch": "npm run test -- -w" + "test:watch": "npm run test -- -w", + "build": "babel lesspass.js text.js password-generator.js --presets babel-preset-es2015 --out-dir distribution", + "prepublish": "npm test && npm run build" }, "keywords": [ "password", @@ -22,7 +24,7 @@ }, "homepage": "https://github.com/oslab-fr/lesspass-npm#readme", "devDependencies": { - "babel-core": "^6.5.2", + "babel-cli": "^6.5.1", "babel-preset-es2015": "^6.5.0", "mocha": "^2.4.5", "webpack": "^1.12.13" From e30574ca92b8b643391f09ab73a614226e0e550a Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 14 Feb 2016 14:45:23 +0100 Subject: [PATCH 003/124] modify API --- .gitignore | 2 +- README.md | 2 ++ lesspass.js | 3 ++- package.json | 4 ++-- tests/password-generator.tests.js | 5 +++-- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index a510caa..53c37a1 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -distribution \ No newline at end of file +dist \ No newline at end of file diff --git a/README.md b/README.md index 95eb8f2..de26a5b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![Build Status](https://travis-ci.org/oslab-fr/lesspass-npm.svg?branch=master)](https://travis-ci.org/oslab-fr/lesspass-npm) + # LessPass Core LessPass npm module use to generate unique password diff --git a/lesspass.js b/lesspass.js index d70a208..b1dd30c 100644 --- a/lesspass.js +++ b/lesspass.js @@ -2,7 +2,8 @@ var text = require('./text'); var passwordGenerator = require('./password-generator'); module.exports = { - createPassword: createPassword + createPassword: createPassword, + createMasterPassword: passwordGenerator.createMasterPassword }; function createPassword(masterPassword, entry) { diff --git a/package.json b/package.json index 1638ce4..2e95ef0 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name": "lesspass", - "version": "1.0.3", + "version": "1.1.0", "description": "node.js stateless password management solution", "main": "distribution/lesspass.js", "scripts": { "test": "mocha --compilers js:babel-core/register tests", "test:watch": "npm run test -- -w", - "build": "babel lesspass.js text.js password-generator.js --presets babel-preset-es2015 --out-dir distribution", + "build": "babel lesspass.js text.js password-generator.js --presets babel-preset-es2015 --out-dir dist", "prepublish": "npm test && npm run build" }, "keywords": [ diff --git a/tests/password-generator.tests.js b/tests/password-generator.tests.js index 6e1991f..ab50fe0 100644 --- a/tests/password-generator.tests.js +++ b/tests/password-generator.tests.js @@ -1,5 +1,6 @@ var assert = require('assert'); var passwordGenerator = require('../password-generator'); +var lesspass = require('../lesspass'); describe('passwordGenerator', function () { describe('master password', function () { @@ -7,7 +8,7 @@ describe('passwordGenerator', function () { var email = 'test@lesspass.com'; var password = "password"; - passwordGenerator.createMasterPassword(email, password).then(function (masterPassword) { + lesspass.createMasterPassword(email, password).then(function (masterPassword) { assert.equal("90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d", masterPassword); done(); }); @@ -16,7 +17,7 @@ describe('passwordGenerator', function () { var email = 'test@lesspass.com'; var password = "password"; - passwordGenerator.createMasterPassword(email, password).then(function (masterPassword) { + lesspass.createMasterPassword(email, password).then(function (masterPassword) { assert.equal(64, masterPassword.length); done(); }); From 1948f1eecba600c5c953fc9bbe02ab41e49bc033 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 14 Feb 2016 14:50:57 +0100 Subject: [PATCH 004/124] add missing node module --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 2e95ef0..922c1d0 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "homepage": "https://github.com/oslab-fr/lesspass-npm#readme", "devDependencies": { "babel-cli": "^6.5.1", + "babel-core": "^6.5.2", "babel-preset-es2015": "^6.5.0", "mocha": "^2.4.5", "webpack": "^1.12.13" From dce645da599e47a9b4d6e50929e4e9bb4a7bd45d Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 14 Feb 2016 15:00:15 +0100 Subject: [PATCH 005/124] fix error in entry point --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 922c1d0..a36b4a3 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "lesspass", - "version": "1.1.0", + "version": "1.1.1", "description": "node.js stateless password management solution", - "main": "distribution/lesspass.js", + "main": "dist/lesspass.js", "scripts": { "test": "mocha --compilers js:babel-core/register tests", "test:watch": "npm run test -- -w", From 8f693048c92c2ab10b31bbd087eb0d74ddcda365 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 17 Feb 2016 21:09:37 +0100 Subject: [PATCH 006/124] update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index de26a5b..ecf27c1 100644 --- a/README.md +++ b/README.md @@ -23,3 +23,6 @@ LessPass npm module use to generate unique password var password = lesspass.createPassword(masterPassword, entry); console.log(password); // ubUB4[yqAD3?od +## Test + + npm run test \ No newline at end of file From da233fb253b79e1421848210af7374e73194d182 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 18 Feb 2016 09:23:04 +0100 Subject: [PATCH 007/124] update travis image link --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ecf27c1..73f95ad 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![Build Status](https://travis-ci.org/oslab-fr/lesspass-npm.svg?branch=master)](https://travis-ci.org/oslab-fr/lesspass-npm) +[![Build Status](https://travis-ci.org/lesspass/core.svg?branch=master)](https://travis-ci.org/lesspass/core) # LessPass Core @@ -25,4 +25,4 @@ LessPass npm module use to generate unique password ## Test - npm run test \ No newline at end of file + npm run test From 5d5d8a046d4c78450236e0f6449cb8912fcbf137 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 17 May 2016 15:56:51 +0200 Subject: [PATCH 008/124] standardization of sub modules --- LICENSE | 21 --------------------- README.md | 28 ---------------------------- license | 21 +++++++++++++++++++++ readme.md | 30 ++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 49 deletions(-) delete mode 100644 LICENSE delete mode 100644 README.md create mode 100644 license create mode 100644 readme.md diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d10fcd8..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Guillaume Vincent - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 73f95ad..0000000 --- a/README.md +++ /dev/null @@ -1,28 +0,0 @@ -[![Build Status](https://travis-ci.org/lesspass/core.svg?branch=master)](https://travis-ci.org/lesspass/core) - -# LessPass Core - -LessPass npm module use to generate unique password - -## Install - - npm install lesspass - -## Usage - - var lesspass = require('lesspass'); - var entry = { - site: 'lesspass', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 - } - }; - var masterPassword = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - var password = lesspass.createPassword(masterPassword, entry); - console.log(password); // ubUB4[yqAD3?od - -## Test - - npm run test diff --git a/license b/license new file mode 100644 index 0000000..6a8501b --- /dev/null +++ b/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Guillaume Vincent (guillaumevincent.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..2e0f02f --- /dev/null +++ b/readme.md @@ -0,0 +1,30 @@ +[![Build Status](https://travis-ci.org/lesspass/core.svg?branch=master)](https://travis-ci.org/lesspass/core) + +# LessPass Core + +LessPass npm module use to generate unique password + +## Install + + npm install lesspass + +## Usage + + var lesspass = require('lesspass'); + var entry = { + site: 'lesspass', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + var masterPassword = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + var password = lesspass.createPassword(masterPassword, entry); + console.log(password); // ubUB4[yqAD3?od + +## Test + + npm run test + +[lesspass submodule](https://github.com/lesspass/lesspass) \ No newline at end of file From f8250016dcb7e4805eea956177923a28ea66087e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 18 May 2016 12:03:34 +0200 Subject: [PATCH 009/124] simplify API for password creation --- .gitignore | 3 +- lesspass.js | 13 --- package.json | 52 +++++++++-- password-generator.js | 44 --------- readme.md | 40 +++++--- src/encryption.js | 58 ++++++++++++ src/lesspass.js | 7 ++ src/render.js | 60 ++++++++++++ tests/encryption.tests.js | 82 ++++++++++++++++ tests/legacy.tests.js | 50 ++++++++++ tests/lesspass.tests.js | 192 ++++++++++++++++++++++++++++---------- tests/password-generator.tests.js | 98 ------------------- tests/render.tests.js | 60 ++++++++++++ tests/text.tests.js | 34 ------- text.js | 45 --------- 15 files changed, 530 insertions(+), 308 deletions(-) delete mode 100644 lesspass.js delete mode 100644 password-generator.js create mode 100644 src/encryption.js create mode 100644 src/lesspass.js create mode 100644 src/render.js create mode 100644 tests/encryption.tests.js create mode 100644 tests/legacy.tests.js delete mode 100644 tests/password-generator.tests.js create mode 100644 tests/render.tests.js delete mode 100644 tests/text.tests.js delete mode 100644 text.js diff --git a/.gitignore b/.gitignore index 53c37a1..a9f4ed5 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -dist \ No newline at end of file +lib +node_modules \ No newline at end of file diff --git a/lesspass.js b/lesspass.js deleted file mode 100644 index b1dd30c..0000000 --- a/lesspass.js +++ /dev/null @@ -1,13 +0,0 @@ -var text = require('./text'); -var passwordGenerator = require('./password-generator'); - -module.exports = { - createPassword: createPassword, - createMasterPassword: passwordGenerator.createMasterPassword -}; - -function createPassword(masterPassword, entry) { - var hash = passwordGenerator._createHash(masterPassword, entry); - var template = passwordGenerator._getTemplate(entry.password.settings); - return text._encode(hash, template); -} \ No newline at end of file diff --git a/package.json b/package.json index a36b4a3..e0fe81f 100644 --- a/package.json +++ b/package.json @@ -2,11 +2,10 @@ "name": "lesspass", "version": "1.1.1", "description": "node.js stateless password management solution", - "main": "dist/lesspass.js", + "main": "lib/lesspass.js", "scripts": { - "test": "mocha --compilers js:babel-core/register tests", - "test:watch": "npm run test -- -w", - "build": "babel lesspass.js text.js password-generator.js --presets babel-preset-es2015 --out-dir dist", + "test": "ava --require babel-core/register && xo", + "build": "babel src --out-dir lib", "prepublish": "npm test && npm run build" }, "keywords": [ @@ -17,22 +16,55 @@ "type": "git", "url": "git+ssh://git@github.com:oslab-fr/lesspass-npm.git" }, - "author": "Guillaume Vincent", + "author": { + "name": "Guillaume Vincent", + "email": "guillaume@oslab.fr", + "url": "guillaumevincent.com" + }, + "engines": { + "node": ">=4.2.6" + }, "license": "MIT", "bugs": { "url": "https://github.com/oslab-fr/lesspass-npm/issues" }, "homepage": "https://github.com/oslab-fr/lesspass-npm#readme", "devDependencies": { - "babel-cli": "^6.5.1", - "babel-core": "^6.5.2", - "babel-preset-es2015": "^6.5.0", - "mocha": "^2.4.5", - "webpack": "^1.12.13" + "ava": "^0.14.0", + "babel-cli": "^6.9.0", + "babel-core": "^6.9.0", + "babel-preset-es2015": "^6.9.0", + "xo": "^0.15.1" }, "babel": { "presets": [ "es2015" ] + }, + "browserify": { + "transform": [ + "babelify" + ] + }, + "xo": { + "esnext": true, + "space": true, + "envs": [ + "browser", + "webextensions", + "shared-node-browser", + "es6" + ], + "ignores": [ + "lib/**" + ] + }, + "ava": { + "files": [ + "tests/*.js" + ], + "source": [ + "src/*.js" + ] } } diff --git a/password-generator.js b/password-generator.js deleted file mode 100644 index da4b113..0000000 --- a/password-generator.js +++ /dev/null @@ -1,44 +0,0 @@ -var crypto = require('crypto'); - -module.exports = { - createMasterPassword: createMasterPassword, - _getTemplate: _getTemplate, - _createHash:_createHash -}; - - -function createMasterPassword(email, password) { - return new Promise((resolve, reject) => { - var iterations = 8192; - var keylen = 32; - crypto.pbkdf2(password, email, iterations, keylen, 'sha256', function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }); -} - -function _getTemplate(passwordTypes = ['strong']) { - var passwordTypesInfo = { - lowercase: {value: 'vc', order: 1}, - uppercase: {value: 'VC', order: 2}, - numbers: {value: 'n', order: 3}, - symbols: {value: 's', order: 4}, - strong: {value: 'Cvcvns', order: 5} - }; - return passwordTypes - .map(passwordType => passwordTypesInfo[passwordType]) - .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) - .map(passwordType => passwordType.value) - .join(''); -} - - -function _createHash(masterPassword, {site, password={length: 12, counter: 1}}) { - var salt = site + password.counter.toString(); - var hash = crypto.createHmac('sha256', masterPassword).update(salt).digest('hex'); - return hash.substring(0, password.length); -} \ No newline at end of file diff --git a/readme.md b/readme.md index 2e0f02f..9ac2b9d 100644 --- a/readme.md +++ b/readme.md @@ -2,7 +2,11 @@ # LessPass Core -LessPass npm module use to generate unique password +LessPass node module use to generate unique password + +# requirements + + * node 4.2.x ## Install @@ -10,21 +14,31 @@ LessPass npm module use to generate unique password ## Usage - var lesspass = require('lesspass'); - var entry = { - site: 'lesspass', + import lesspass from 'lesspass'; + + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] } }; - var masterPassword = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - var password = lesspass.createPassword(masterPassword, entry); - console.log(password); // ubUB4[yqAD3?od + lesspass.generatePassword(login, masterPassword, site, options).then(password => { + console.log(password) //azYS7,olOL2] + }); + +## API + +### `generatePassword(login, masterPassword, site, options)` + +generate unique password based on login, masterPassword, site and options. + -## Test +## Tests - npm run test + npm test -[lesspass submodule](https://github.com/lesspass/lesspass) \ No newline at end of file +see [lesspass](https://github.com/lesspass/lesspass) project \ No newline at end of file diff --git a/src/encryption.js b/src/encryption.js new file mode 100644 index 0000000..5487987 --- /dev/null +++ b/src/encryption.js @@ -0,0 +1,58 @@ +import crypto from 'crypto'; +import render from './render'; + +module.exports = { + createPassword: _createPassword, + generatePassword: _generatePassword, + encryptLogin: _encryptLogin, + deriveHash: _deriveHash +}; + +function _encryptLogin(login, masterPassword) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword) { + reject('encryptLogin parameter could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); +} + +function _deriveHash(hash, site, {password = {length: 12}, counter = 1} = {}) { + const salt = site + counter.toString(); + const derivedHash = crypto.createHmac('sha256', hash).update(salt).digest('hex'); + return derivedHash.substring(0, password.length); +} + +function _createPassword(hash, entry) { + // createPassword is deprecated use generatePassword instead + const options = { + counter: entry.password.counter || 1, + password: entry.password + }; + const site = entry.site; + const derivedHash = _deriveHash(hash, site, options); + const template = render.getTemplate(options.password.settings); + return render.prettyPrint(derivedHash, template); +} + +function _generatePassword(login, masterPassword, site, options) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword || !site) { + reject('generatePassword invalid parameter'); + } + + _encryptLogin(login, masterPassword).then(hash => { + const derivedHash = _deriveHash(hash, site, options); + const template = render.getTemplate(options.password.settings); + resolve(render.prettyPrint(derivedHash, template)); + }); + }); +} diff --git a/src/lesspass.js b/src/lesspass.js new file mode 100644 index 0000000..e98b333 --- /dev/null +++ b/src/lesspass.js @@ -0,0 +1,7 @@ +import encryption from './encryption'; + +module.exports = { + generatePassword: encryption.generatePassword, + createPassword: encryption.createPassword, + createMasterPassword: encryption.encryptLogin +}; diff --git a/src/render.js b/src/render.js new file mode 100644 index 0000000..e6de2f9 --- /dev/null +++ b/src/render.js @@ -0,0 +1,60 @@ +module.exports = { + prettyPrint: _prettyPrint, + getTemplate: _getTemplate, + _getCharType, + _getPasswordChar, + _string2charCodes +}; + +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function _prettyPrint(hash, template) { + let password = ''; + + _string2charCodes(hash).forEach((charCode, index) => { + const charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; +} + +function _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function _getTemplate(passwordTypes = ['strong']) { + const passwordTypesInfo = { + lowercase: {value: 'vc', order: 1}, + uppercase: {value: 'VC', order: 2}, + numbers: {value: 'n', order: 3}, + symbols: {value: 's', order: 4}, + strong: {value: 'Cvcvns', order: 5} + }; + return passwordTypes + .map(passwordType => passwordTypesInfo[passwordType]) + .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) + .map(passwordType => passwordType.value) + .join(''); +} diff --git a/tests/encryption.tests.js b/tests/encryption.tests.js new file mode 100644 index 0000000..b3c06cf --- /dev/null +++ b/tests/encryption.tests.js @@ -0,0 +1,82 @@ +import test from 'ava'; +import {encryptLogin, deriveHash} from '../src/encryption'; + +test('should create encrypted hash with pbkdf2 (8192 iterations and sha 256)', t => { + const login = 'test@lesspass.com'; + const masterPassword = 'password'; + + return encryptLogin(login, masterPassword).then(hash => { + t.is('90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d', hash); + }); +}); + +test('should create encrypted hash with 64 chars length', t => { + const login = 'test@lesspass.com'; + const masterPassword = 'password'; + + return encryptLogin(login, masterPassword).then(hash => { + t.is(64, hash.length); + }); +}); + +test('should reject promise if no parameter', t => { + t.plan(1); + return encryptLogin('', '').catch(() => { + t.pass('promise rejected with empty parameter'); + }); +}); + +test('should derive hash with default length', t => { + const hash = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + t.is(12, deriveHash(hash, site).length); +}); + +test('should derive hash with default options', t => { + const hash = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + const site = 'lesspass.com'; + const option = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + t.is( + deriveHash(hash, site), + deriveHash(hash, site, option) + ); +}); + +test('should derive hash with defined length', t => { + const hash = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; + const site = 'lesspass.com'; + const option = { + counter: 1, + password: { + length: 10 + } + }; + t.is(10, deriveHash(hash, site, option).length); +}); + +test('should return two different passwords if site different', t => { + const hash = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'google.com'; + const site2 = 'facebook.com'; + t.not( + deriveHash(hash, site), + deriveHash(hash, site2) + ); +}); + +test('should return two different passwords if counter different', t => { + const hash = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option = {counter: 1}; + const option2 = {counter: 2}; + t.not( + deriveHash(hash, site, option), + deriveHash(hash, site, option2) + ); +}); diff --git a/tests/legacy.tests.js b/tests/legacy.tests.js new file mode 100644 index 0000000..542bc0e --- /dev/null +++ b/tests/legacy.tests.js @@ -0,0 +1,50 @@ +import test from 'ava'; +import lesspass from '../src/lesspass'; + +test('should create password', t => { + const masterPassword = 'password'; + const entry = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + t.is('iwIQ8[acYT4&oc', lesspass.createPassword(masterPassword, entry)); +}); +test('should create password 2', t => { + const masterPassword = 'password'; + const entry = { + site: 'facebook', + password: { + length: 12, + settings: ['strong'], + counter: 1 + } + }; + t.is('Vexu8[Syce4&', lesspass.createPassword(masterPassword, entry)); +}); +test('should create 2 passwords different if counter different', t => { + const masterPassword = 'password'; + const entry = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 1 + } + }; + const entry2 = { + site: 'facebook', + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], + counter: 2 + } + }; + t.not( + lesspass.createPassword(masterPassword, entry), + lesspass.createPassword(masterPassword, entry2) + ); +}); diff --git a/tests/lesspass.tests.js b/tests/lesspass.tests.js index c3aafbf..c3aff6a 100644 --- a/tests/lesspass.tests.js +++ b/tests/lesspass.tests.js @@ -1,52 +1,144 @@ -var assert = require('assert'); -var lesspass = require('../lesspass'); +import test from 'ava'; +import lesspass from '../src/lesspass'; -describe('lesspass', function () { - it('should create password', function () { - var masterPassword = "password"; - var entry = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 - } - }; - assert.equal('iwIQ8[acYT4&oc', lesspass.createPassword(masterPassword, entry)); - }); - it('should create password 2', function () { - var masterPassword = "password"; - var entry = { - site: 'facebook', - password: { - length: 12, - settings: ['strong'], - counter: 1 - } - }; - assert.equal('Vexu8[Syce4&', lesspass.createPassword(masterPassword, entry)); - }); - it('should create 2 passwords different if counter different', function () { - var masterPassword = "password"; - var entry = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 - } - }; - var entry2 = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 2 - } - }; - assert.notEqual( - lesspass.createPassword(masterPassword, entry), - lesspass.createPassword(masterPassword, entry2) - ); - }); +test('generate password', t => { + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + return lesspass.generatePassword(login, masterPassword, site, options).then(password => { + t.is(password, 'azYS7,olOL2]'); + }); +}); + +test('generate password2', t => { + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + return lesspass.generatePassword(login, masterPassword, site, options).then(password => { + t.is(password, 'azYS7,olOL2]'); + }); +}); + +test('generate password3', t => { + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + return lesspass.generatePassword(login, masterPassword, site, options).then(password => { + t.is(password, 'azYS7,olOL2]'); + }); +}); + +test('auto generated password', t => { + const promises = []; + const entries = [ + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'azYS7,olOL2]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 14, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'azYS7,olOL2]iz' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase']}}, + generatedPassword: 'azyseqololat' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'AZ3[EQ7@OL2]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['numbers', 'symbols']}}, + generatedPassword: '4?3[7,7@7@2]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['symbols']}}, + generatedPassword: '[?=[&,:@:@[]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers']}}, + generatedPassword: 'azYS7uwAW8at' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase']}}, + generatedPassword: 'azYSeqOLolAT' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 2, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'obYT2=olOV9=' + }, + { + login: 'lesspass', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'erOC1%imIW3,' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password2', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'uvUM5_ucUP5=' + } + ]; + + for (const entry of entries) { + promises.push(lesspass.generatePassword(entry.login, entry.masterPassword, entry.site, entry.options)); + } + + t.plan(entries.length); + return Promise.all(promises).then(values => { + for (let i = 0; i < values.length; i++) { + t.is(entries[i].generatedPassword, values[i], JSON.stringify(entries[i], null, 2)); + } + }); }); diff --git a/tests/password-generator.tests.js b/tests/password-generator.tests.js deleted file mode 100644 index ab50fe0..0000000 --- a/tests/password-generator.tests.js +++ /dev/null @@ -1,98 +0,0 @@ -var assert = require('assert'); -var passwordGenerator = require('../password-generator'); -var lesspass = require('../lesspass'); - -describe('passwordGenerator', function () { - describe('master password', function () { - it('should create master password with pbkdf2 (8192 iterations and sha 256)', function (done) { - var email = 'test@lesspass.com'; - var password = "password"; - - lesspass.createMasterPassword(email, password).then(function (masterPassword) { - assert.equal("90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d", masterPassword); - done(); - }); - }); - it('should create 64 char length master password', function (done) { - var email = 'test@lesspass.com'; - var password = "password"; - - lesspass.createMasterPassword(email, password).then(function (masterPassword) { - assert.equal(64, masterPassword.length); - done(); - }); - }); - }); - describe('password templates password', function () { - it('should get default template from password type', function () { - assert.equal('Cvcvns', passwordGenerator._getTemplate()); - }); - it('should get template from password type', function () { - assert.equal('vc', passwordGenerator._getTemplate(['lowercase'])); - assert.equal('VC', passwordGenerator._getTemplate(['uppercase'])); - assert.equal('n', passwordGenerator._getTemplate(['numbers'])); - assert.equal('s', passwordGenerator._getTemplate(['symbols'])); - }); - it('should concatenate template if two password password_types', function () { - assert.equal('vcVC', passwordGenerator._getTemplate(['lowercase', 'uppercase'])); - assert.equal('vcns', passwordGenerator._getTemplate(['lowercase', 'numbers', 'symbols'])); - }); - it('should not care about order of type in password password_types', function () { - assert.equal( - passwordGenerator._getTemplate(['uppercase', 'lowercase']), - passwordGenerator._getTemplate(['lowercase', 'uppercase']) - ); - }); - }); - describe('hash', function () { - it('should have default length of 12', function () { - var masterPassword = 'password'; - var entry = {'site': 'facebook'}; - assert.equal(12, passwordGenerator._createHash(masterPassword, entry).length); - }); - it('should allow to change default length', function () { - var masterPassword = 'password'; - var entry = { - site: 'lesspass', - password: { - length: 10, - counter: 1 - } - }; - assert.equal(10, passwordGenerator._createHash(masterPassword, entry).length); - }); - it('should return two different passwords if site different', function () { - var masterPassword = 'password'; - var entry = {site: 'facebook'}; - var entry2 = {site: 'google'}; - assert.notEqual( - passwordGenerator._createHash(masterPassword, entry), - passwordGenerator._createHash(masterPassword, entry2) - ); - }); - it('should return two different passwords if counter different', function () { - var masterPassword = 'password'; - var entry = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 - } - }; - var entry2 = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 2 - } - }; - assert.notEqual( - passwordGenerator._createHash(masterPassword, entry), - passwordGenerator._createHash(masterPassword, entry2) - ); - }); - }); - -}); diff --git a/tests/render.tests.js b/tests/render.tests.js new file mode 100644 index 0000000..33fe289 --- /dev/null +++ b/tests/render.tests.js @@ -0,0 +1,60 @@ +import test from 'ava'; +import render from '../src/render'; + +test('should print different password if templates different', t => { + const hash = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; + t.not(render.prettyPrint(hash, 'cv'), render.prettyPrint(hash, 'vc')); +}); + +test('must return a string of the same length as the input', t => { + const hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; + t.is(hash.length, render.prettyPrint(hash, 'cv').length); +}); + +test('should return char inside a string based on modulo of the index', t => { + const template = 'cv'; + t.is('c', render._getCharType(template, 0)); + t.is('v', render._getCharType(template, 1)); + t.is('c', render._getCharType(template, 10)); +}); + +test('should convert a string into an array of char code', t => { + const charCodes = render._string2charCodes('ab40f6ee71'); + t.is(97, charCodes[0]); + t.is(98, charCodes[1]); + t.is(10, charCodes.length); +}); + +test('should get password char based on its type and index', t => { + const typeVowel = 'V'; + t.is('A', render._getPasswordChar(typeVowel, 0)); +}); + +test('should modulo if overflow', t => { + const typeVowel = 'V'; + t.is('E', render._getPasswordChar(typeVowel, 1)); + t.is('E', render._getPasswordChar(typeVowel, 7)); +}); + +test('should get default template', t => { + t.is('Cvcvns', render.getTemplate()); +}); + +test('should get template from password setting', t => { + t.is('vc', render.getTemplate(['lowercase'])); + t.is('VC', render.getTemplate(['uppercase'])); + t.is('n', render.getTemplate(['numbers'])); + t.is('s', render.getTemplate(['symbols'])); +}); + +test('should concatenate template if two password settings', t => { + t.is('vcVC', render.getTemplate(['lowercase', 'uppercase'])); + t.is('vcns', render.getTemplate(['lowercase', 'numbers', 'symbols'])); +}); + +test('should not care about order of password settings', t => { + t.is( + render.getTemplate(['uppercase', 'lowercase']), + render.getTemplate(['lowercase', 'uppercase']) + ); +}); diff --git a/tests/text.tests.js b/tests/text.tests.js deleted file mode 100644 index b567ded..0000000 --- a/tests/text.tests.js +++ /dev/null @@ -1,34 +0,0 @@ -var assert = require('assert'); -var text = require('../text'); - -describe('crypto', function () { - it('should return char inside a string based on modulo of the index', function () { - var template = 'cv'; - assert.equal('c', text._getCharType(template, 0)); - assert.equal('v', text._getCharType(template, 1)); - assert.equal('c', text._getCharType(template, 10)); - }); - it('should convert a string into an array of char code', function () { - var charCodes = text._string2charCodes('ab40f6ee71'); - assert.equal(97, charCodes[0]); - assert.equal(98, charCodes[1]); - assert.equal(10, charCodes.length); - }); - it('must return a string of the same length as the input', function () { - var hash = 'Y2Vi2a112A'; - assert.equal(hash.length, text._encode(hash, 'cv').length); - }); - it('should return different values if strings different', function () { - var hash = 'a'; - assert.notEqual(text._encode(hash, 'cv'), text._encode(hash, 'vc')); - }); - it('should get password char based on its type and index', function () { - var typeVowel = 'V'; - assert.equal('A', text._getPasswordChar(typeVowel, 0)); - }); - it('should modulo if overflow', function () { - var typeVowel = 'V'; - assert.equal('E', text._getPasswordChar(typeVowel, 1)); - assert.equal('E', text._getPasswordChar(typeVowel, 7)); - }); -}); diff --git a/text.js b/text.js deleted file mode 100644 index a394370..0000000 --- a/text.js +++ /dev/null @@ -1,45 +0,0 @@ -module.exports = { - _getCharType: _getCharType, - _getPasswordChar: _getPasswordChar, - _encode: _encode, - _string2charCodes: _string2charCodes -}; - -function _getCharType(template, index) { - return template[index % template.length]; -} - -function _getPasswordChar(charType, index) { - var passwordsChars = { - V: "AEIOUY", - C: "BCDFGHJKLMNPQRSTVWXZ", - v: "aeiouy", - c: "bcdfghjklmnpqrstvwxz", - A: "AEIOUYBCDFGHJKLMNPQRSTVWXZ", - a: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz", - n: "0123456789", - s: "@&%?,=[]_:-+*$#!'^~;()/.", - x: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!'^~;()/." - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; -} - -function _encode(hash, template) { - var password = ''; - _string2charCodes(hash).map( - (charCode, index) => { - let charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - } - ); - return password; -} - -function _string2charCodes(text) { - var charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} \ No newline at end of file From 939732fa62101ab84334bc512d270ab8bba59356 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 18 May 2016 12:04:13 +0200 Subject: [PATCH 010/124] 2.0.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e0fe81f..c2feb1e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "1.1.1", + "version": "2.0.0", "description": "node.js stateless password management solution", "main": "lib/lesspass.js", "scripts": { From 0c2f1467f9b0534c9b015e87145a84b6fc729b53 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 18 May 2016 12:15:09 +0200 Subject: [PATCH 011/124] update github link in package.json --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index c2feb1e..03641e5 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ ], "repository": { "type": "git", - "url": "git+ssh://git@github.com:oslab-fr/lesspass-npm.git" + "url": "git+ssh://git@github.com:lesspass/core.git" }, "author": { "name": "Guillaume Vincent", @@ -26,9 +26,9 @@ }, "license": "MIT", "bugs": { - "url": "https://github.com/oslab-fr/lesspass-npm/issues" + "url": "https://github.com/lesspass/core/issues" }, - "homepage": "https://github.com/oslab-fr/lesspass-npm#readme", + "homepage": "https://github.com/lesspass/core#readme", "devDependencies": { "ava": "^0.14.0", "babel-cli": "^6.9.0", From 1d4369e72adf26cc3aa6fe68a5ac52677452266f Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 18 May 2016 12:15:12 +0200 Subject: [PATCH 012/124] 2.0.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 03641e5..a870a8c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "2.0.0", + "version": "2.0.1", "description": "node.js stateless password management solution", "main": "lib/lesspass.js", "scripts": { From 8a3d8ba5585eb7ba10eb23eb1a63f55d8d05f6bf Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sat, 4 Jun 2016 22:58:51 +0200 Subject: [PATCH 013/124] update readme --- readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 9ac2b9d..8bdaa6e 100644 --- a/readme.md +++ b/readme.md @@ -2,11 +2,11 @@ # LessPass Core -LessPass node module use to generate unique password +core library for LessPass password manager in node.js used to generate unique password -# requirements +## Requirements - * node 4.2.x + - node 4.x.x ## Install From 97fb229594229e4fd4c08fbe8a22729f503863f1 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 6 Jun 2016 08:48:59 +0200 Subject: [PATCH 014/124] update documentation --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 8bdaa6e..cc01a89 100644 --- a/readme.md +++ b/readme.md @@ -41,4 +41,4 @@ generate unique password based on login, masterPassword, site and options. npm test -see [lesspass](https://github.com/lesspass/lesspass) project \ No newline at end of file +see [LessPass](https://github.com/lesspass/lesspass) project \ No newline at end of file From d868c4a15c154e7568ea4379475981e96cdb3463 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 29 Jun 2016 13:55:30 +0200 Subject: [PATCH 015/124] make lesspass working as a standalone script --- dist/lesspass.min.js | 2 + package.json | 29 +++--- readme.md | 49 ++++++++-- src/encryption.js | 58 ------------ src/lesspass.js | 119 ++++++++++++++++++++++-- src/render.js | 60 ------------ tests/api.tests.js | 144 +++++++++++++++++++++++++++++ tests/encryption.tests.js | 82 ----------------- tests/index.html | 24 +++++ tests/legacy.tests.js | 50 ---------- tests/lesspass.tests.js | 229 ++++++++++++++++++++++------------------------ tests/render.tests.js | 60 ------------ webpack.config.js | 28 ++++++ 13 files changed, 475 insertions(+), 459 deletions(-) create mode 100644 dist/lesspass.min.js delete mode 100644 src/encryption.js delete mode 100644 src/render.js create mode 100644 tests/api.tests.js delete mode 100644 tests/encryption.tests.js create mode 100644 tests/index.html delete mode 100644 tests/legacy.tests.js delete mode 100644 tests/render.tests.js create mode 100644 webpack.config.js diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js new file mode 100644 index 0000000..46ba963 --- /dev/null +++ b/dist/lesspass.min.js @@ -0,0 +1,2 @@ +!function(t){function r(e){if(n[e])return n[e].exports;var i=n[e]={exports:{},id:e,loaded:!1};return t[e].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}var n={};return r.m=t,r.c=n,r.p="",r(0)}([function(t,r,n){t.exports=n(1)},function(t,r,n){"use strict";function e(t){return t&&t.__esModule?t:{"default":t}}var i=n(2),o=e(i);!function(){function r(t,r,o,u){return new Promise(function(a,h){t&&r&&o||h("generatePassword invalid parameter"),n(t,r).then(function(t){var r=e(t,o,u),n=i(u.password.settings);a(s(r,n))})})}function n(t,r){return new Promise(function(n,e){t&&r||e("encryptLogin parameter could not be empty");var i=8192,s=32;o["default"].pbkdf2(r,t,i,s,"sha256",function(t,r){t?e("error in pbkdf2"):n(r.toString("hex"))})})}function e(t,r){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],e=n.password,i=void 0===e?{length:12}:e,s=n.counter,u=void 0===s?1:s,a=r+u.toString(),h=o["default"].createHmac("sha256",t).update(a).digest("hex");return h.substring(0,i.length)}function i(){var t=arguments.length<=0||void 0===arguments[0]?["strong"]:arguments[0],r={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return t.map(function(t){return r[t]}).sort(function(t,r){return t.order>r.order}).map(function(t){return t.value}).join("")}function s(t,r){var n="";return u(t).forEach(function(t,e){var i=a(r,e);n+=h(i,t)}),n}function u(t){for(var r=[],n=0;n1?arguments[1]:"utf8"):a(this,r)):arguments.length>1?new t(r,arguments[1]):new t(r)}function s(r,n){if(r=g(r,n<0?0:0|y(n)),!t.TYPED_ARRAY_SUPPORT)for(var e=0;e>>1;return e&&(r.parent=K),r}function y(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function _(r,n){if(!(this instanceof _))return new _(r,n);var e=new t(r,n);return delete e.parent,e}function w(t,r){"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var e=!1;;)switch(r){case"ascii":case"binary":case"raw":case"raws":return n;case"utf8":case"utf-8":return H(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(t).length;default:if(e)return H(t).length;r=(""+r).toLowerCase(),e=!0}}function v(t,r,n){var e=!1;if(r=0|r,n=void 0===n||n===1/0?this.length:0|n,t||(t="utf8"),r<0&&(r=0),n>this.length&&(n=this.length),n<=r)return"";for(;;)switch(t){case"hex":return x(this,r,n);case"utf8":case"utf-8":return R(this,r,n);case"ascii":return P(this,r,n);case"binary":return T(this,r,n);case"base64":return S(this,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,r,n);default:if(e)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),e=!0}}function E(t,r,n,e){n=Number(n)||0;var i=t.length-n;e?(e=Number(e),e>i&&(e=i)):e=i;var o=r.length;if(o%2!==0)throw new Error("Invalid hex string");e>o/2&&(e=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+u<=n){var a,h,f,c;switch(u){case 1:o<128&&(s=o);break;case 2:a=t[i+1],128===(192&a)&&(c=(31&o)<<6|63&a,c>127&&(s=c));break;case 3:a=t[i+1],h=t[i+2],128===(192&a)&&128===(192&h)&&(c=(15&o)<<12|(63&a)<<6|63&h,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:a=t[i+1],h=t[i+2],f=t[i+3],128===(192&a)&&128===(192&h)&&128===(192&f)&&(c=(15&o)<<18|(63&a)<<12|(63&h)<<6|63&f,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,u=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|1023&s),e.push(s),i+=u}return U(e)}function U(t){var r=t.length;if(r<=Q)return String.fromCharCode.apply(String,t);for(var n="",e=0;ee)&&(n=e);for(var i="",o=r;on)throw new RangeError("Trying to access beyond buffer length")}function D(r,n,e,i,o,s){if(!t.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");if(n>o||nr.length)throw new RangeError("index out of range")}function k(t,r,n,e){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-n,2);i>>8*(e?i:1-i)}function Y(t,r,n,e){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-n,4);i>>8*(e?i:3-i)&255}function C(t,r,n,e,i,o){if(r>i||rt.length)throw new RangeError("index out of range");if(n<0)throw new RangeError("index out of range")}function M(t,r,n,e,i){return i||C(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),$.write(t,r,n,e,23,4),n+4}function z(t,r,n,e,i){return i||C(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),$.write(t,r,n,e,52,8),n+8}function j(t){if(t=N(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function N(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function F(t){return t<16?"0"+t.toString(16):t.toString(16)}function H(t,r){r=r||1/0;for(var n,e=t.length,i=null,o=[],s=0;s55295&&n<57344){if(!i){if(n>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(s+1===e){(r-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(r-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((r-=1)<0)break;o.push(n)}else if(n<2048){if((r-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((r-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function J(t){for(var r=[],n=0;n>8,i=n%256,o.push(i),o.push(e);return o}function q(t){return Z.toByteArray(j(t))}function G(t,r,n,e){for(var i=0;i=r.length||i>=t.length);i++)r[i+n]=t[i];return i}var Z=n(4),$=n(5),X=n(6);r.Buffer=t,r.SlowBuffer=_,r.INSPECT_MAX_BYTES=50,t.poolSize=8192;var K={};t.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:i(),t.TYPED_ARRAY_SUPPORT?(t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array):(t.prototype.length=void 0,t.prototype.parent=void 0),t.isBuffer=function(t){return!(null==t||!t._isBuffer)},t.compare=function(r,n){if(!t.isBuffer(r)||!t.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(r===n)return 0;for(var e=r.length,i=n.length,o=0,s=Math.min(e,i);o0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},t.prototype.compare=function(r){if(!t.isBuffer(r))throw new TypeError("Argument must be a Buffer");return this===r?0:t.compare(this,r)},t.prototype.indexOf=function(r,n){function e(t,r,n){for(var e=-1,i=0;n+i2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n>>=0,0===this.length)return-1;if(n>=this.length)return-1;if(n<0&&(n=Math.max(this.length+n,0)),"string"==typeof r)return 0===r.length?-1:String.prototype.indexOf.call(this,r,n);if(t.isBuffer(r))return e(this,r,n);if("number"==typeof r)return t.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,r,n):e(this,[r],n);throw new TypeError("val must be string, number or Buffer")},t.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},t.prototype.set=function(t,r){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,r)},t.prototype.write=function(t,r,n,e){if(void 0===r)e="utf8",n=this.length,r=0;else if(void 0===n&&"string"==typeof r)e=r,n=this.length,r=0;else if(isFinite(r))r=0|r,isFinite(n)?(n=0|n,void 0===e&&(e="utf8")):(e=n,n=void 0);else{var i=e;e=r,r=0|n,n=i}var o=this.length-r;if((void 0===n||n>o)&&(n=o),t.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("attempt to write outside buffer bounds");e||(e="utf8");for(var s=!1;;)switch(e){case"hex":return E(this,t,r,n);case"utf8":case"utf-8":return b(this,t,r,n);case"ascii":return m(this,t,r,n);case"binary":return B(this,t,r,n);case"base64":return A(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),s=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;t.prototype.slice=function(r,n){var e=this.length;r=~~r,n=void 0===n?e:~~n,r<0?(r+=e,r<0&&(r=0)):r>e&&(r=e),n<0?(n+=e,n<0&&(n=0)):n>e&&(n=e),n0&&(i*=256);)e+=this[t+--r]*i;return e},t.prototype.readUInt8=function(t,r){return r||O(t,1,this.length),this[t]},t.prototype.readUInt16LE=function(t,r){return r||O(t,2,this.length),this[t]|this[t+1]<<8},t.prototype.readUInt16BE=function(t,r){return r||O(t,2,this.length),this[t]<<8|this[t+1]},t.prototype.readUInt32LE=function(t,r){return r||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},t.prototype.readUInt32BE=function(t,r){return r||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},t.prototype.readIntLE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=this[t],i=1,o=0;++o=i&&(e-=Math.pow(2,8*r)),e},t.prototype.readIntBE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=r,i=1,o=this[t+--e];e>0&&(i*=256);)o+=this[t+--e]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*r)),o},t.prototype.readInt8=function(t,r){return r||O(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},t.prototype.readInt16LE=function(t,r){r||O(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(t,r){r||O(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(t,r){return r||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},t.prototype.readInt32BE=function(t,r){return r||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},t.prototype.readFloatLE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!0,23,4)},t.prototype.readFloatBE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!1,23,4)},t.prototype.readDoubleLE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!0,52,8)},t.prototype.readDoubleBE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!1,52,8)},t.prototype.writeUIntLE=function(t,r,n,e){t=+t,r=0|r,n=0|n,e||D(this,t,r,n,Math.pow(2,8*n),0);var i=1,o=0;for(this[r]=255&t;++o=0&&(o*=256);)this[r+i]=t/o&255;return r+n},t.prototype.writeUInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,255,0),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[n]=255&r,n+1},t.prototype.writeUInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeUInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeUInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n+3]=r>>>24,this[n+2]=r>>>16,this[n+1]=r>>>8,this[n]=255&r):Y(this,r,n,!0),n+4},t.prototype.writeUInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeIntLE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=0,s=1,u=t<0?1:0;for(this[r]=255&t;++o>0)-u&255;return r+n},t.prototype.writeIntBE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=n-1,s=1,u=t<0?1:0;for(this[r+o]=255&t;--o>=0&&(s*=256);)this[r+o]=(t/s>>0)-u&255;return r+n},t.prototype.writeInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,127,-128),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[n]=255&r,n+1},t.prototype.writeInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8,this[n+2]=r>>>16,this[n+3]=r>>>24):Y(this,r,n,!0),n+4},t.prototype.writeInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeFloatLE=function(t,r,n){return M(this,t,r,!0,n)},t.prototype.writeFloatBE=function(t,r,n){return M(this,t,r,!1,n)},t.prototype.writeDoubleLE=function(t,r,n){return z(this,t,r,!0,n)},t.prototype.writeDoubleBE=function(t,r,n){return z(this,t,r,!1,n)},t.prototype.copy=function(r,n,e,i){if(e||(e=0),i||0===i||(i=this.length),n>=r.length&&(n=r.length),n||(n=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),r.length-n=0;o--)r[o+n]=this[o+e];else if(s<1e3||!t.TYPED_ARRAY_SUPPORT)for(o=0;o=this.length)throw new RangeError("start out of bounds");if(n<0||n>this.length)throw new RangeError("end out of bounds");var e;if("number"==typeof t)for(e=r;e0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;a="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,h=new o(3*t.length/4-a),s=a>0?t.length-4:t.length;var c=0;for(e=0,i=0;e>16),n((65280&u)>>8),n(255&u);return 2===a?(u=r(t.charAt(e))<<2|r(t.charAt(e+1))>>4,n(255&u)):1===a&&(u=r(t.charAt(e))<<10|r(t.charAt(e+1))<<4|r(t.charAt(e+2))>>2,n(u>>8&255),n(255&u)),h}function i(t){function r(t){return e.charAt(t)}function n(t){return r(t>>18&63)+r(t>>12&63)+r(t>>6&63)+r(63&t)}var i,o,s,u=t.length%3,a="";for(i=0,s=t.length-u;i>2),a+=r(o<<4&63),a+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],a+=r(o>>10),a+=r(o>>4&63),a+=r(o<<2&63),a+="="}return a}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),u="/".charCodeAt(0),a="0".charCodeAt(0),h="a".charCodeAt(0),f="A".charCodeAt(0),c="-".charCodeAt(0),l="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}(r)},function(t,r){r.read=function(t,r,n,e,i){var o,s,u=8*i-e-1,a=(1<>1,f=-7,c=n?i-1:0,l=n?-1:1,p=t[r+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[r+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=e;f>0;s=256*s+t[r+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s+=Math.pow(2,e),o-=h}return(p?-1:1)*s*Math.pow(2,o-e)},r.write=function(t,r,n,e,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=e?0:o-1,d=e?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,s=f):(s=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-s))<1&&(s--,a*=2),r+=s+c>=1?l/a:l*Math.pow(2,1-c),r*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(r*a-1)*Math.pow(2,i),s+=c):(u=r*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[n+p]=255&s,p+=d,s/=256,h-=8);t[n+p-d]|=128*g}},function(t,r){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,r,n){(function(r,e){!function(){var i=("undefined"==typeof window?r:window)||{};_crypto=i.crypto||i.msCrypto||n(8),t.exports=function(t){if(_crypto.getRandomValues){var r=new e(t);return _crypto.getRandomValues(r),r}if(_crypto.randomBytes)return _crypto.randomBytes(t);throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}}()}).call(r,function(){return this}(),n(3).Buffer)},function(t,r){},function(t,r,n){(function(r){function e(t){return function(){var n=[],e={update:function(t,e){return r.isBuffer(t)||(t=new r(t,e)),n.push(t),this},digest:function(e){var i=r.concat(n),o=t(i);return n=null,e?o.toString(e):o}};return e}}var i=n(10),o=e(n(19)),s=e(n(21));t.exports=function(t){return"md5"===t?new o:"rmd160"===t?new s:i(t)}}).call(r,n(3).Buffer)},function(t,r,n){var r=t.exports=function(t){var n=r[t];if(!n)throw new Error(t+" is not supported (we accept pull requests)");return new n},e=n(3).Buffer,i=n(11)(e);r.sha1=n(12)(e,i),r.sha256=n(17)(e,i),r.sha512=n(18)(e,i)},function(t,r){t.exports=function(t){function r(r,n){this._block=new t(r),this._finalSize=n,this._blockSize=r,this._len=0,this._s=0}return r.prototype.init=function(){this._s=0,this._len=0},r.prototype.update=function(r,n){"string"==typeof r&&(n=n||"utf8",r=new t(r,n));for(var e=this._len+=r.length,i=this._s=this._s||0,o=0,s=this._block;i=8*this._finalSize&&(this._update(this._block),this._block.fill(0)),this._block.writeInt32BE(r,this._blockSize-4);var n=this._update(this._block)||this._hash();return t?n.toString(t):n},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},r}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){return d.length?d.pop().init():this instanceof n?(this._w=p,r.call(this,64,56),this._h=null,void this.init()):new n}function i(t,r,n,e){return t<20?r&n|~r&e:t<40?r^n^e:t<60?r&n|r&e|n&e:r^n^e}function o(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function s(t,r){return t+r|0}function u(t,r){return t<>>32-r}var a=0,h=4,f=8,c=12,l=16,p=new("undefined"==typeof Int32Array?Array:Int32Array)(80),d=[];return e(n,r),n.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,r.prototype.init.call(this),this},n.prototype._POOL=d,n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d;r=f=this._a,n=c=this._b,e=l=this._c,a=p=this._d,h=d=this._e;for(var g=this._w,y=0;y<80;y++){var _=g[y]=y<16?t.readInt32BE(4*y):u(g[y-3]^g[y-8]^g[y-14]^g[y-16],1),w=s(s(u(r,5),i(y,n,e,a)),s(s(h,_),o(y)));h=a,a=e,e=u(n,30),n=r,r=w}this._a=s(r,f),this._b=s(n,c),this._c=s(e,l),this._d=s(a,p),this._e=s(h,d)},n.prototype._hash=function(){d.length<100&&d.push(this);var r=new t(20);return r.writeInt32BE(0|this._a,a),r.writeInt32BE(0|this._b,h),r.writeInt32BE(0|this._c,f),r.writeInt32BE(0|this._d,c),r.writeInt32BE(0|this._e,l),r},n}},function(t,r,n){(function(t,e){function i(t,n){var e={seen:[],stylize:s};return arguments.length>=3&&(e.depth=arguments[2]),arguments.length>=4&&(e.colors=arguments[3]),g(n)?e.showHidden=n:n&&r._extend(e,n),b(e.showHidden)&&(e.showHidden=!1),b(e.depth)&&(e.depth=2),b(e.colors)&&(e.colors=!1),b(e.customInspect)&&(e.customInspect=!0),e.colors&&(e.stylize=o),a(e,t,e.depth)}function o(t,r){var n=i.styles[r];return n?"["+i.colors[n][0]+"m"+t+"["+i.colors[n][1]+"m":t}function s(t,r){return t}function u(t){var r={};return t.forEach(function(t,n){r[t]=!0}),r}function a(t,n,e){if(t.customInspect&&n&&S(n.inspect)&&n.inspect!==r.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(e,t);return v(i)||(i=a(t,i,e)),i}var o=h(t,n);if(o)return o;var s=Object.keys(n),g=u(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(n)),I(n)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return f(n);if(0===s.length){if(S(n)){var y=n.name?": "+n.name:"";return t.stylize("[Function"+y+"]","special")}if(m(n))return t.stylize(RegExp.prototype.toString.call(n),"regexp");if(A(n))return t.stylize(Date.prototype.toString.call(n),"date");if(I(n))return f(n)}var _="",w=!1,E=["{","}"];if(d(n)&&(w=!0,E=["[","]"]),S(n)){var b=n.name?": "+n.name:"";_=" [Function"+b+"]"}if(m(n)&&(_=" "+RegExp.prototype.toString.call(n)),A(n)&&(_=" "+Date.prototype.toUTCString.call(n)),I(n)&&(_=" "+f(n)),0===s.length&&(!w||0==n.length))return E[0]+_+E[1];if(e<0)return m(n)?t.stylize(RegExp.prototype.toString.call(n),"regexp"):t.stylize("[Object]","special");t.seen.push(n);var B;return B=w?c(t,n,e,g,s):s.map(function(r){return l(t,n,e,g,r,w)}),t.seen.pop(),p(B,_,E)}function h(t,r){if(b(r))return t.stylize("undefined","undefined");if(v(r)){var n="'"+JSON.stringify(r).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return w(r)?t.stylize(""+r,"number"):g(r)?t.stylize(""+r,"boolean"):y(r)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,r,n,e,i){for(var o=[],s=0,u=r.length;s-1&&(u=o?u.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+u.split("\n").map(function(t){return" "+t}).join("\n"))):u=t.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return u;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function p(t,r,n){var e=0,i=t.reduce(function(t,r){return e++,r.indexOf("\n")>=0&&e++,t+r.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===r?"":r+"\n ")+" "+t.join(",\n ")+" "+n[1]:n[0]+r+" "+t.join(", ")+" "+n[1]}function d(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function y(t){return null===t}function _(t){return null==t}function w(t){return"number"==typeof t}function v(t){return"string"==typeof t}function E(t){return"symbol"==typeof t}function b(t){return void 0===t}function m(t){return B(t)&&"[object RegExp]"===U(t)}function B(t){return"object"==typeof t&&null!==t}function A(t){return B(t)&&"[object Date]"===U(t)}function I(t){return B(t)&&("[object Error]"===U(t)||t instanceof Error)}function S(t){return"function"==typeof t}function R(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function U(t){return Object.prototype.toString.call(t)}function P(t){return t<10?"0"+t.toString(10):t.toString(10)}function T(){var t=new Date,r=[P(t.getHours()),P(t.getMinutes()),P(t.getSeconds())].join(":");return[t.getDate(),k[t.getMonth()],r].join(" ")}function x(t,r){return Object.prototype.hasOwnProperty.call(t,r)}var L=/%[sdj%]/g;r.format=function(t){if(!v(t)){for(var r=[],n=0;n=o)return t;switch(t){case"%s":return String(e[n++]);case"%d":return Number(e[n++]);case"%j":try{return JSON.stringify(e[n++])}catch(r){return"[Circular]"}default:return t}}),u=e[n];n1)for(var n=1;n>>r|t<<32-r}function o(t,r){return t>>>r}function s(t,r,n){return t&r^~t&n}function u(t,r,n){return t&r^t&n^r&n}function a(t){return i(t,2)^i(t,13)^i(t,22)}function h(t){return i(t,6)^i(t,11)^i(t,25)}function f(t){return i(t,7)^i(t,18)^o(t,3)}function c(t){return i(t,17)^i(t,19)^o(t,10)}var l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=new Array(64);return e(n,r),n.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._len=this._s=0,this},n.prototype._update=function(t){var r,n,e,i,o,p,d,g,y,_,w=this._w;r=0|this._a,n=0|this._b,e=0|this._c,i=0|this._d,o=0|this._e,p=0|this._f,d=0|this._g,g=0|this._h;for(var v=0;v<64;v++){var E=w[v]=v<16?t.readInt32BE(4*v):c(w[v-2])+w[v-7]+f(w[v-15])+w[v-16];y=g+h(o)+s(o,p,d)+l[v]+E,_=a(r)+u(r,n,e),g=d,d=p,p=o,o=i+y,i=e,e=n,n=r,r=y+_}this._a=r+this._a|0,this._b=n+this._b|0,this._c=e+this._c|0,this._d=i+this._d|0,this._e=o+this._e|0,this._f=p+this._f|0,this._g=d+this._g|0,this._h=g+this._h|0},n.prototype._hash=function(){var r=new t(32);return r.writeInt32BE(this._a,0),r.writeInt32BE(this._b,4),r.writeInt32BE(this._c,8),r.writeInt32BE(this._d,12),r.writeInt32BE(this._e,16),r.writeInt32BE(this._f,20),r.writeInt32BE(this._g,24),r.writeInt32BE(this._h,28),r},n}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){this.init(),this._w=a,r.call(this,128,112)}function i(t,r,n){return t>>>n|r<<32-n}function o(t,r,n){return t&r^~t&n}function s(t,r,n){return t&r^t&n^r&n}var u=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);return e(n,r),n.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._al=-205731576,this._bl=-2067093701,this._cl=-23791573,this._dl=1595750129,this._el=-1377402159,this._fl=725511199,this._gl=-79577749,this._hl=327033209,this._len=this._s=0,this},n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d,g,y,_,w,v,E,b=this._w;r=0|this._a,n=0|this._b,e=0|this._c,a=0|this._d,h=0|this._e,f=0|this._f,c=0|this._g,l=0|this._h,p=0|this._al,d=0|this._bl,g=0|this._cl,y=0|this._dl,_=0|this._el,w=0|this._fl,v=0|this._gl,E=0|this._hl;for(var m=0;m<80;m++){var B,A,I=2*m;if(m<16)B=b[I]=t.readInt32BE(4*I),A=b[I+1]=t.readInt32BE(4*I+4);else{var S=b[I-30],R=b[I-30+1],U=i(S,R,1)^i(S,R,8)^S>>>7,P=i(R,S,1)^i(R,S,8)^i(R,S,7);S=b[I-4],R=b[I-4+1];var T=i(S,R,19)^i(R,S,29)^S>>>6,x=i(R,S,19)^i(S,R,29)^i(R,S,6),L=b[I-14],O=b[I-14+1],D=b[I-32],k=b[I-32+1];A=P+O,B=U+L+(A>>>0

>>0?1:0),A+=x,B=B+T+(A>>>0>>0?1:0),A+=k,B=B+D+(A>>>0>>0?1:0),b[I]=B,b[I+1]=A}var Y=s(r,n,e),C=s(p,d,g),M=i(r,p,28)^i(p,r,2)^i(p,r,7),z=i(p,r,28)^i(r,p,2)^i(r,p,7),j=i(h,_,14)^i(h,_,18)^i(_,h,9),N=i(_,h,14)^i(_,h,18)^i(h,_,9),F=u[I],H=u[I+1],J=o(h,f,c),V=o(_,w,v),q=E+N,G=l+j+(q>>>0>>0?1:0);q+=V,G=G+J+(q>>>0>>0?1:0),q+=H,G=G+F+(q>>>0>>0?1:0),q+=A,G=G+B+(q>>>0>>0?1:0);var Z=z+C,$=M+Y+(Z>>>0>>0?1:0);l=c,E=v,c=f,v=w,f=h,w=_,_=y+q|0,h=a+G+(_>>>0>>0?1:0)|0,a=e,y=g,e=n,g=d,n=r,d=p,p=q+Z|0,r=G+$+(p>>>0>>0?1:0)|0}this._al=this._al+p|0,this._bl=this._bl+d|0,this._cl=this._cl+g|0,this._dl=this._dl+y|0,this._el=this._el+_|0,this._fl=this._fl+w|0,this._gl=this._gl+v|0,this._hl=this._hl+E|0,this._a=this._a+r+(this._al>>>0

>>0?1:0)|0,this._b=this._b+n+(this._bl>>>0>>0?1:0)|0,this._c=this._c+e+(this._cl>>>0>>0?1:0)|0,this._d=this._d+a+(this._dl>>>0>>0?1:0)|0,this._e=this._e+h+(this._el>>>0<_>>>0?1:0)|0,this._f=this._f+f+(this._fl>>>0>>0?1:0)|0,this._g=this._g+c+(this._gl>>>0>>0?1:0)|0,this._h=this._h+l+(this._hl>>>0>>0?1:0)|0},n.prototype._hash=function(){function r(t,r,e){n.writeInt32BE(t,e),n.writeInt32BE(r,e+4)}var n=new t(64);return r(this._a,this._al,0),r(this._b,this._bl,8),r(this._c,this._cl,16),r(this._d,this._dl,24),r(this._e,this._el,32),r(this._f,this._fl,40),r(this._g,this._gl,48),r(this._h,this._hl,56),n},n}},function(t,r,n){function e(t,r){t[r>>5]|=128<>>9<<4)+14]=r;for(var n=1732584193,e=-271733879,i=-1732584194,f=271733878,c=0;c>16)+(r>>16)+(n>>16);return e<<16|65535&n}function f(t,r){return t<>>32-r}var c=n(20);t.exports=function(t){return c.hash(t,e,16)}},function(t,r,n){(function(r){function n(t,n){if(t.length%o!==0){var e=t.length+(o-t.length%o);t=r.concat([t,s],e)}for(var i=[],u=n?t.readInt32BE:t.readInt32LE,a=0;a>>32-r}function a(t){var n=[1732584193,4023233417,2562383102,271733878,3285377520];"string"==typeof t&&(t=new r(t,"utf8"));var e=g(t),i=8*t.length,o=8*t.length;e[i>>>5]|=128<<24-i%32,e[(i+64>>>9<<4)+14]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8);for(var s=0;s>>24)|4278255360&(u<<24|u>>>8)}var a=y(n);return new r(a)}t.exports=a;var h=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],f=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],c=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],l=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],p=[0,1518500249,1859775393,2400959708,2840853838],d=[1352829926,1548603684,1836072691,2053994217,0],g=function(t){for(var r=[],n=0,e=0;n>>5]|=t[n]<<24-e%32;return r},y=function(t){for(var r=[],n=0;n<32*t.length;n+=8)r.push(t[n>>>5]>>>24-n%32&255);return r},_=function(t,r,a){for(var g=0;g<16;g++){var y=a+g,_=r[y];r[y]=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8)}var w,v,E,b,m,B,A,I,S,R;B=w=t[0],A=v=t[1],I=E=t[2],S=b=t[3],R=m=t[4];for(var U,g=0;g<80;g+=1)U=w+r[a+h[g]]|0,U+=g<16?n(v,E,b)+p[0]:g<32?e(v,E,b)+p[1]:g<48?i(v,E,b)+p[2]:g<64?o(v,E,b)+p[3]:s(v,E,b)+p[4],U=0|U,U=u(U,c[g]),U=U+m|0,w=m,m=b,b=u(E,10),E=v,v=U,U=B+r[a+f[g]]|0,U+=g<16?s(A,I,S)+d[0]:g<32?o(A,I,S)+d[1]:g<48?i(A,I,S)+d[2]:g<64?e(A,I,S)+d[3]:n(A,I,S)+d[4],U=0|U,U=u(U,l[g]),U=U+R|0,B=R,R=S,S=u(I,10),I=A,A=U;U=t[1]+E+S|0,t[1]=t[2]+b+R|0,t[2]=t[3]+m+B|0,t[3]=t[4]+w+A|0,t[4]=t[0]+v+I|0,t[0]=U}}).call(r,n(3).Buffer)},function(t,r,n){(function(r){function e(t,n){if(!(this instanceof e))return new e(t,n);this._opad=a,this._alg=t;var s="sha512"===t?128:64;n=this._key=r.isBuffer(n)?n:new r(n),n.length>s?n=i(t).update(n).digest():n.length(Math.pow(2,32)-1)*u))throw new TypeError("keylen exceeds maximum length");d.copy(h,0,0,u);for(var g=1;g", + "description": "lesspass javascript module to generate idempotent passwords", + "main": "src/lesspass.js", "scripts": { "test": "ava --require babel-core/register && xo", - "build": "babel src --out-dir lib", + "build": "rm -rf dist && webpack", "prepublish": "npm test && npm run build" }, "keywords": [ "password", + "crypto", "lesspass" ], "repository": { "type": "git", "url": "git+ssh://git@github.com:lesspass/core.git" }, - "author": { - "name": "Guillaume Vincent", - "email": "guillaume@oslab.fr", - "url": "guillaumevincent.com" - }, "engines": { "node": ">=4.2.6" }, @@ -30,22 +27,18 @@ }, "homepage": "https://github.com/lesspass/core#readme", "devDependencies": { - "ava": "^0.14.0", - "babel-cli": "^6.9.0", - "babel-core": "^6.9.0", + "ava": "^0.15.2", + "babel-core": "^6.10.4", + "babel-loader": "^6.2.4", "babel-preset-es2015": "^6.9.0", - "xo": "^0.15.1" + "webpack": "^1.13.1", + "xo": "^0.16.0" }, "babel": { "presets": [ "es2015" ] }, - "browserify": { - "transform": [ - "babelify" - ] - }, "xo": { "esnext": true, "space": true, diff --git a/readme.md b/readme.md index cc01a89..4b9342a 100644 --- a/readme.md +++ b/readme.md @@ -14,28 +14,63 @@ core library for LessPass password manager in node.js used to generate unique pa ## Usage - import lesspass from 'lesspass'; +### Node - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; - const site = 'lesspass.com'; - const options = { + var lesspass = require('lesspass'); + + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var site = 'lesspass.com'; + var options = { counter: 1, password: { length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] } }; - lesspass.generatePassword(login, masterPassword, site, options).then(password => { - console.log(password) //azYS7,olOL2] + lesspass.generatePassword(login, masterPassword, site, options).then(function (generatedPassword) { + console.log(generatedPassword) //azYS7,olOL2] }); +### Browser + + + + + + + + + + + + ## API ### `generatePassword(login, masterPassword, site, options)` generate unique password based on login, masterPassword, site and options. +return: promise with generatedPassword + + lesspass.generatePassword(login, masterPassword, site, options) + .then(function (generatedPassword) { + + }); ## Tests diff --git a/src/encryption.js b/src/encryption.js deleted file mode 100644 index 5487987..0000000 --- a/src/encryption.js +++ /dev/null @@ -1,58 +0,0 @@ -import crypto from 'crypto'; -import render from './render'; - -module.exports = { - createPassword: _createPassword, - generatePassword: _generatePassword, - encryptLogin: _encryptLogin, - deriveHash: _deriveHash -}; - -function _encryptLogin(login, masterPassword) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword) { - reject('encryptLogin parameter could not be empty'); - } - const iterations = 8192; - const keylen = 32; - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }); -} - -function _deriveHash(hash, site, {password = {length: 12}, counter = 1} = {}) { - const salt = site + counter.toString(); - const derivedHash = crypto.createHmac('sha256', hash).update(salt).digest('hex'); - return derivedHash.substring(0, password.length); -} - -function _createPassword(hash, entry) { - // createPassword is deprecated use generatePassword instead - const options = { - counter: entry.password.counter || 1, - password: entry.password - }; - const site = entry.site; - const derivedHash = _deriveHash(hash, site, options); - const template = render.getTemplate(options.password.settings); - return render.prettyPrint(derivedHash, template); -} - -function _generatePassword(login, masterPassword, site, options) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword || !site) { - reject('generatePassword invalid parameter'); - } - - _encryptLogin(login, masterPassword).then(hash => { - const derivedHash = _deriveHash(hash, site, options); - const template = render.getTemplate(options.password.settings); - resolve(render.prettyPrint(derivedHash, template)); - }); - }); -} diff --git a/src/lesspass.js b/src/lesspass.js index e98b333..8e2fef5 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -1,7 +1,114 @@ -import encryption from './encryption'; +import crypto from 'crypto'; -module.exports = { - generatePassword: encryption.generatePassword, - createPassword: encryption.createPassword, - createMasterPassword: encryption.encryptLogin -}; +(function () { + const lesspass = { + generatePassword: _generatePassword, + _encryptLogin, + _deriveHash, + _prettyPrint, + _getTemplate, + _getCharType, + _getPasswordChar, + _string2charCodes + }; + + if (typeof window === 'undefined') { + if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { + module.exports = lesspass; + } else { + console.error('cannot load properly lesspass'); + } + } else { + window.lesspass = lesspass; + } + + function _generatePassword(login, masterPassword, site, options) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword || !site) { + reject('generatePassword invalid parameter'); + } + + _encryptLogin(login, masterPassword).then(hash => { + const derivedHash = _deriveHash(hash, site, options); + const template = _getTemplate(options.password.settings); + resolve(_prettyPrint(derivedHash, template)); + }); + }); + } + + function _encryptLogin(login, masterPassword) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword) { + reject('encryptLogin parameter could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); + } + + function _deriveHash(hash, site, {password = {length: 12}, counter = 1} = {}) { + const salt = site + counter.toString(); + const derivedHash = crypto.createHmac('sha256', hash).update(salt).digest('hex'); + return derivedHash.substring(0, password.length); + } + + function _getTemplate(passwordTypes = ['strong']) { + const passwordTypesInfo = { + lowercase: {value: 'vc', order: 1}, + uppercase: {value: 'VC', order: 2}, + numbers: {value: 'n', order: 3}, + symbols: {value: 's', order: 4}, + strong: {value: 'Cvcvns', order: 5} + }; + return passwordTypes + .map(passwordType => passwordTypesInfo[passwordType]) + .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) + .map(passwordType => passwordType.value) + .join(''); + } + + function _prettyPrint(hash, template) { + let password = ''; + + _string2charCodes(hash).forEach((charCode, index) => { + const charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; + } + + function _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; + } + + function _getCharType(template, index) { + return template[index % template.length]; + } + + function _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; + } +})(); diff --git a/src/render.js b/src/render.js deleted file mode 100644 index e6de2f9..0000000 --- a/src/render.js +++ /dev/null @@ -1,60 +0,0 @@ -module.exports = { - prettyPrint: _prettyPrint, - getTemplate: _getTemplate, - _getCharType, - _getPasswordChar, - _string2charCodes -}; - -function _getCharType(template, index) { - return template[index % template.length]; -} - -function _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; -} - -function _prettyPrint(hash, template) { - let password = ''; - - _string2charCodes(hash).forEach((charCode, index) => { - const charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; -} - -function _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} - -function _getTemplate(passwordTypes = ['strong']) { - const passwordTypesInfo = { - lowercase: {value: 'vc', order: 1}, - uppercase: {value: 'VC', order: 2}, - numbers: {value: 'n', order: 3}, - symbols: {value: 's', order: 4}, - strong: {value: 'Cvcvns', order: 5} - }; - return passwordTypes - .map(passwordType => passwordTypesInfo[passwordType]) - .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) - .map(passwordType => passwordType.value) - .join(''); -} diff --git a/tests/api.tests.js b/tests/api.tests.js new file mode 100644 index 0000000..c3aff6a --- /dev/null +++ b/tests/api.tests.js @@ -0,0 +1,144 @@ +import test from 'ava'; +import lesspass from '../src/lesspass'; + +test('generate password', t => { + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + return lesspass.generatePassword(login, masterPassword, site, options).then(password => { + t.is(password, 'azYS7,olOL2]'); + }); +}); + +test('generate password2', t => { + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + return lesspass.generatePassword(login, masterPassword, site, options).then(password => { + t.is(password, 'azYS7,olOL2]'); + }); +}); + +test('generate password3', t => { + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const site = 'lesspass.com'; + const options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } + }; + return lesspass.generatePassword(login, masterPassword, site, options).then(password => { + t.is(password, 'azYS7,olOL2]'); + }); +}); + +test('auto generated password', t => { + const promises = []; + const entries = [ + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'azYS7,olOL2]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 14, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'azYS7,olOL2]iz' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase']}}, + generatedPassword: 'azyseqololat' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'AZ3[EQ7@OL2]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['numbers', 'symbols']}}, + generatedPassword: '4?3[7,7@7@2]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['symbols']}}, + generatedPassword: '[?=[&,:@:@[]' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers']}}, + generatedPassword: 'azYS7uwAW8at' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase']}}, + generatedPassword: 'azYSeqOLolAT' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 2, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'obYT2=olOV9=' + }, + { + login: 'lesspass', + masterPassword: 'password', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'erOC1%imIW3,' + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password2', + site: 'lesspass.com', + options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, + generatedPassword: 'uvUM5_ucUP5=' + } + ]; + + for (const entry of entries) { + promises.push(lesspass.generatePassword(entry.login, entry.masterPassword, entry.site, entry.options)); + } + + t.plan(entries.length); + return Promise.all(promises).then(values => { + for (let i = 0; i < values.length; i++) { + t.is(entries[i].generatedPassword, values[i], JSON.stringify(entries[i], null, 2)); + } + }); +}); diff --git a/tests/encryption.tests.js b/tests/encryption.tests.js deleted file mode 100644 index b3c06cf..0000000 --- a/tests/encryption.tests.js +++ /dev/null @@ -1,82 +0,0 @@ -import test from 'ava'; -import {encryptLogin, deriveHash} from '../src/encryption'; - -test('should create encrypted hash with pbkdf2 (8192 iterations and sha 256)', t => { - const login = 'test@lesspass.com'; - const masterPassword = 'password'; - - return encryptLogin(login, masterPassword).then(hash => { - t.is('90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d', hash); - }); -}); - -test('should create encrypted hash with 64 chars length', t => { - const login = 'test@lesspass.com'; - const masterPassword = 'password'; - - return encryptLogin(login, masterPassword).then(hash => { - t.is(64, hash.length); - }); -}); - -test('should reject promise if no parameter', t => { - t.plan(1); - return encryptLogin('', '').catch(() => { - t.pass('promise rejected with empty parameter'); - }); -}); - -test('should derive hash with default length', t => { - const hash = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - t.is(12, deriveHash(hash, site).length); -}); - -test('should derive hash with default options', t => { - const hash = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - const option = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } - }; - t.is( - deriveHash(hash, site), - deriveHash(hash, site, option) - ); -}); - -test('should derive hash with defined length', t => { - const hash = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - const site = 'lesspass.com'; - const option = { - counter: 1, - password: { - length: 10 - } - }; - t.is(10, deriveHash(hash, site, option).length); -}); - -test('should return two different passwords if site different', t => { - const hash = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'google.com'; - const site2 = 'facebook.com'; - t.not( - deriveHash(hash, site), - deriveHash(hash, site2) - ); -}); - -test('should return two different passwords if counter different', t => { - const hash = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option = {counter: 1}; - const option2 = {counter: 2}; - t.not( - deriveHash(hash, site, option), - deriveHash(hash, site, option2) - ); -}); diff --git a/tests/index.html b/tests/index.html new file mode 100644 index 0000000..fe13421 --- /dev/null +++ b/tests/index.html @@ -0,0 +1,24 @@ + + + + + + + + + + \ No newline at end of file diff --git a/tests/legacy.tests.js b/tests/legacy.tests.js deleted file mode 100644 index 542bc0e..0000000 --- a/tests/legacy.tests.js +++ /dev/null @@ -1,50 +0,0 @@ -import test from 'ava'; -import lesspass from '../src/lesspass'; - -test('should create password', t => { - const masterPassword = 'password'; - const entry = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 - } - }; - t.is('iwIQ8[acYT4&oc', lesspass.createPassword(masterPassword, entry)); -}); -test('should create password 2', t => { - const masterPassword = 'password'; - const entry = { - site: 'facebook', - password: { - length: 12, - settings: ['strong'], - counter: 1 - } - }; - t.is('Vexu8[Syce4&', lesspass.createPassword(masterPassword, entry)); -}); -test('should create 2 passwords different if counter different', t => { - const masterPassword = 'password'; - const entry = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 1 - } - }; - const entry2 = { - site: 'facebook', - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'], - counter: 2 - } - }; - t.not( - lesspass.createPassword(masterPassword, entry), - lesspass.createPassword(masterPassword, entry2) - ); -}); diff --git a/tests/lesspass.tests.js b/tests/lesspass.tests.js index c3aff6a..d3f6da1 100644 --- a/tests/lesspass.tests.js +++ b/tests/lesspass.tests.js @@ -1,144 +1,137 @@ import test from 'ava'; import lesspass from '../src/lesspass'; -test('generate password', t => { - const login = 'contact@lesspass.com'; +test('should create encrypted hash with pbkdf2 (8192 iterations and sha 256)', t => { + const login = 'test@lesspass.com'; const masterPassword = 'password'; - const site = 'lesspass.com'; - const options = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } - }; - return lesspass.generatePassword(login, masterPassword, site, options).then(password => { - t.is(password, 'azYS7,olOL2]'); + + return lesspass._encryptLogin(login, masterPassword).then(hash => { + t.is('90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d', hash); }); }); -test('generate password2', t => { - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; +test('should create encrypted hash with 64 chars length', t => { + return lesspass._encryptLogin('♥', '♥ ♥').then(hash => { + t.is(64, hash.length); + }); +}); + +test('should reject promise if no parameter', t => { + t.plan(1); + return lesspass._encryptLogin('', '').catch(() => { + t.pass('promise rejected with empty parameter'); + }); +}); + +test('should derive hash with default length', t => { + const hash = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + t.is(12, lesspass._deriveHash(hash, site).length); +}); + +test('should derive hash with default options', t => { + const hash = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; const site = 'lesspass.com'; - const options = { + const option = { counter: 1, password: { length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] } }; - return lesspass.generatePassword(login, masterPassword, site, options).then(password => { - t.is(password, 'azYS7,olOL2]'); - }); + t.is( + lesspass._deriveHash(hash, site), + lesspass._deriveHash(hash, site, option) + ); }); -test('generate password3', t => { - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; +test('should derive hash with defined length', t => { + const hash = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; const site = 'lesspass.com'; - const options = { + const option = { counter: 1, password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + length: 10 } }; - return lesspass.generatePassword(login, masterPassword, site, options).then(password => { - t.is(password, 'azYS7,olOL2]'); - }); + t.is(10, lesspass._deriveHash(hash, site, option).length); }); -test('auto generated password', t => { - const promises = []; - const entries = [ - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'azYS7,olOL2]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 14, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'azYS7,olOL2]iz' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase']}}, - generatedPassword: 'azyseqololat' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'AZ3[EQ7@OL2]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['numbers', 'symbols']}}, - generatedPassword: '4?3[7,7@7@2]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['symbols']}}, - generatedPassword: '[?=[&,:@:@[]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers']}}, - generatedPassword: 'azYS7uwAW8at' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase']}}, - generatedPassword: 'azYSeqOLolAT' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 2, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'obYT2=olOV9=' - }, - { - login: 'lesspass', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'erOC1%imIW3,' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password2', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'uvUM5_ucUP5=' - } - ]; +test('should return two different passwords if site different', t => { + const hash = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'google.com'; + const site2 = 'facebook.com'; + t.not( + lesspass._deriveHash(hash, site), + lesspass._deriveHash(hash, site2) + ); +}); - for (const entry of entries) { - promises.push(lesspass.generatePassword(entry.login, entry.masterPassword, entry.site, entry.options)); - } +test('should return two different passwords if counter different', t => { + const hash = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option = {counter: 1}; + const option2 = {counter: 2}; + t.not( + lesspass._deriveHash(hash, site, option), + lesspass._deriveHash(hash, site, option2) + ); +}); - t.plan(entries.length); - return Promise.all(promises).then(values => { - for (let i = 0; i < values.length; i++) { - t.is(entries[i].generatedPassword, values[i], JSON.stringify(entries[i], null, 2)); - } - }); +test('should print different password if templates different', t => { + const hash = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; + t.not(lesspass._prettyPrint(hash, 'cv'), lesspass._prettyPrint(hash, 'vc')); +}); + +test('must return a string of the same length as the input', t => { + const hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; + t.is(hash.length, lesspass._prettyPrint(hash, 'cv').length); +}); + +test('should return char inside a string based on modulo of the index', t => { + const template = 'cv'; + t.is('c', lesspass._getCharType(template, 0)); + t.is('v', lesspass._getCharType(template, 1)); + t.is('c', lesspass._getCharType(template, 10)); +}); + +test('should convert a string into an array of char code', t => { + const charCodes = lesspass._string2charCodes('ab40f6ee71'); + t.is(97, charCodes[0]); + t.is(98, charCodes[1]); + t.is(10, charCodes.length); +}); + +test('should get password char based on its type and index', t => { + const typeVowel = 'V'; + t.is('A', lesspass._getPasswordChar(typeVowel, 0)); +}); + +test('should modulo if overflow', t => { + const typeVowel = 'V'; + t.is('E', lesspass._getPasswordChar(typeVowel, 1)); + t.is('E', lesspass._getPasswordChar(typeVowel, 7)); +}); + +test('should get default template', t => { + t.is('Cvcvns', lesspass._getTemplate()); +}); + +test('should get template from password setting', t => { + t.is('vc', lesspass._getTemplate(['lowercase'])); + t.is('VC', lesspass._getTemplate(['uppercase'])); + t.is('n', lesspass._getTemplate(['numbers'])); + t.is('s', lesspass._getTemplate(['symbols'])); +}); + +test('should concatenate template if two password settings', t => { + t.is('vcVC', lesspass._getTemplate(['lowercase', 'uppercase'])); + t.is('vcns', lesspass._getTemplate(['lowercase', 'numbers', 'symbols'])); +}); + +test('should not care about order of password settings', t => { + t.is( + lesspass._getTemplate(['uppercase', 'lowercase']), + lesspass._getTemplate(['lowercase', 'uppercase']) + ); }); diff --git a/tests/render.tests.js b/tests/render.tests.js deleted file mode 100644 index 33fe289..0000000 --- a/tests/render.tests.js +++ /dev/null @@ -1,60 +0,0 @@ -import test from 'ava'; -import render from '../src/render'; - -test('should print different password if templates different', t => { - const hash = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; - t.not(render.prettyPrint(hash, 'cv'), render.prettyPrint(hash, 'vc')); -}); - -test('must return a string of the same length as the input', t => { - const hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; - t.is(hash.length, render.prettyPrint(hash, 'cv').length); -}); - -test('should return char inside a string based on modulo of the index', t => { - const template = 'cv'; - t.is('c', render._getCharType(template, 0)); - t.is('v', render._getCharType(template, 1)); - t.is('c', render._getCharType(template, 10)); -}); - -test('should convert a string into an array of char code', t => { - const charCodes = render._string2charCodes('ab40f6ee71'); - t.is(97, charCodes[0]); - t.is(98, charCodes[1]); - t.is(10, charCodes.length); -}); - -test('should get password char based on its type and index', t => { - const typeVowel = 'V'; - t.is('A', render._getPasswordChar(typeVowel, 0)); -}); - -test('should modulo if overflow', t => { - const typeVowel = 'V'; - t.is('E', render._getPasswordChar(typeVowel, 1)); - t.is('E', render._getPasswordChar(typeVowel, 7)); -}); - -test('should get default template', t => { - t.is('Cvcvns', render.getTemplate()); -}); - -test('should get template from password setting', t => { - t.is('vc', render.getTemplate(['lowercase'])); - t.is('VC', render.getTemplate(['uppercase'])); - t.is('n', render.getTemplate(['numbers'])); - t.is('s', render.getTemplate(['symbols'])); -}); - -test('should concatenate template if two password settings', t => { - t.is('vcVC', render.getTemplate(['lowercase', 'uppercase'])); - t.is('vcns', render.getTemplate(['lowercase', 'numbers', 'symbols'])); -}); - -test('should not care about order of password settings', t => { - t.is( - render.getTemplate(['uppercase', 'lowercase']), - render.getTemplate(['lowercase', 'uppercase']) - ); -}); diff --git a/webpack.config.js b/webpack.config.js new file mode 100644 index 0000000..7376897 --- /dev/null +++ b/webpack.config.js @@ -0,0 +1,28 @@ +const path = require('path'); +const webpack = require('webpack'); + +module.exports = { + entry: [ + './src/lesspass' + ], + output: { + path: __dirname, + filename: 'dist/lesspass.min.js' + }, + module: { + loaders: [ + { + test: /\.js$/, + include: path.join(__dirname, 'src'), + loader: 'babel-loader', + query: { + presets: ['es2015'] + } + } + ] + }, + plugins: [ + new webpack.NoErrorsPlugin(), + new webpack.optimize.UglifyJsPlugin({output: {comments: false}}) + ] +}; From ae7a85b5eab22f7b4ce30233fc2796c10615fa19 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 29 Jun 2016 14:36:20 +0200 Subject: [PATCH 016/124] update documentation --- readme.md | 39 +++++++++++++++++++++++++++++++++++---- tests/karma.conf.js | 20 ++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 tests/karma.conf.js diff --git a/readme.md b/readme.md index 4b9342a..fc16e11 100644 --- a/readme.md +++ b/readme.md @@ -40,7 +40,7 @@ core library for LessPass password manager in node.js used to generate unique pa - + @@ -65,13 +65,44 @@ core library for LessPass password manager in node.js used to generate unique pa generate unique password based on login, masterPassword, site and options. -return: promise with generatedPassword +paramaters : + + * `login`: string + * `masterPassword`: string + * `site`: string + * option: dict with lesspass options + * `counter`: integer (default: 1) + * `password.length`: integer between 6 and 64 (default: 12) + * `password.settings`: array of string in `lowercase`, `uppercase`, `numbers` or `symbols` (default: `['lowercase', 'uppercase', 'numbers', 'symbols']`) + +exemple : + + var options = { + counter: 2, + password: { + length: 14, + settings: ['lowercase', 'uppercase', 'numbers'] + } + }; + + +return: + + * promise with generated password + lesspass.generatePassword(login, masterPassword, site, options) .then(function (generatedPassword) { - + console.log(generatedPassword); + }) + .catch(function (error) { + console.log(error); }); + +see **tests/api.tests.js** for more examples + + ## Tests npm test diff --git a/tests/karma.conf.js b/tests/karma.conf.js new file mode 100644 index 0000000..eb97c35 --- /dev/null +++ b/tests/karma.conf.js @@ -0,0 +1,20 @@ +module.exports = function (config) { + config.set({ + basePath: '..', + frameworks: ['mocha', 'chai'], + files: [ + 'src/**/*.js', + 'test/**/*.js' + ], + exclude: [], + preprocessors: {}, + reporters: ['progress'], + port: 9876, + colors: true, + logLevel: config.LOG_DISABLE, + singleRun: false, + autoWatch: true, + browsers: ['Firefox', 'Chrome'], + concurrency: Infinity + }); +}; From 5ff1f0ef0e5950a5ddb57c7113376f4bef7e8cfc Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 29 Jun 2016 14:45:57 +0200 Subject: [PATCH 017/124] add karma --- package.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index d3539b3..64acddc 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,10 @@ "babel-core": "^6.10.4", "babel-loader": "^6.2.4", "babel-preset-es2015": "^6.9.0", + "karma": "^1.1.0", + "karma-ava": "0.0.1", + "karma-chrome-launcher": "^1.0.1", + "karma-firefox-launcher": "^1.0.0", "webpack": "^1.13.1", "xo": "^0.16.0" }, @@ -54,7 +58,8 @@ }, "ava": { "files": [ - "tests/*.js" + "tests/*.js", + "!tests/karma.conf.js" ], "source": [ "src/*.js" From 649fbe6350681c5a41fedda58e359361045cfc6b Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 30 Jun 2016 09:24:21 +0200 Subject: [PATCH 018/124] improve frontend test --- tests/index.html | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/index.html b/tests/index.html index fe13421..ef2ea22 100644 --- a/tests/index.html +++ b/tests/index.html @@ -17,7 +17,9 @@ } }; lesspass.generatePassword(login, masterPassword, site, options).then(function (generatedPassword) { - console.log(generatedPassword) + if (generatedPassword === 'azYS7,olOL2]') { + document.body.innerHTML = "generatePassword ok"; + } }); From 9ad154fb39b22b08ba139d50f834d9fecdbf20b7 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 1 Jul 2016 17:39:48 +0200 Subject: [PATCH 019/124] 3.0.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 64acddc..9eb549e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.0.1", + "version": "3.0.0", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "src/lesspass.js", From 473e09c10060c2c60b7f776c9e81926b349271a3 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 1 Jul 2016 19:18:55 +0200 Subject: [PATCH 020/124] make encryptLogin function public for the API --- src/lesspass.js | 2 +- tests/lesspass.tests.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lesspass.js b/src/lesspass.js index 8e2fef5..8b8f992 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -3,7 +3,7 @@ import crypto from 'crypto'; (function () { const lesspass = { generatePassword: _generatePassword, - _encryptLogin, + encryptLogin: _encryptLogin, _deriveHash, _prettyPrint, _getTemplate, diff --git a/tests/lesspass.tests.js b/tests/lesspass.tests.js index d3f6da1..d255daf 100644 --- a/tests/lesspass.tests.js +++ b/tests/lesspass.tests.js @@ -5,20 +5,20 @@ test('should create encrypted hash with pbkdf2 (8192 iterations and sha 256)', t const login = 'test@lesspass.com'; const masterPassword = 'password'; - return lesspass._encryptLogin(login, masterPassword).then(hash => { + return lesspass.encryptLogin(login, masterPassword).then(hash => { t.is('90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d', hash); }); }); test('should create encrypted hash with 64 chars length', t => { - return lesspass._encryptLogin('♥', '♥ ♥').then(hash => { + return lesspass.encryptLogin('♥', '♥ ♥').then(hash => { t.is(64, hash.length); }); }); test('should reject promise if no parameter', t => { t.plan(1); - return lesspass._encryptLogin('', '').catch(() => { + return lesspass.encryptLogin('', '').catch(() => { t.pass('promise rejected with empty parameter'); }); }); From be6b82d96c0202d24089018dd8573281b7e74b40 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 1 Jul 2016 19:19:18 +0200 Subject: [PATCH 021/124] 3.1.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9eb549e..7f7dff1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.0.0", + "version": "3.1.0", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "src/lesspass.js", From e7648da36c3a7e65a8310e1287af4192e57e4538 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 1 Jul 2016 19:20:05 +0200 Subject: [PATCH 022/124] build version --- dist/lesspass.min.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js index 46ba963..6c26fce 100644 --- a/dist/lesspass.min.js +++ b/dist/lesspass.min.js @@ -1,2 +1,2 @@ -!function(t){function r(e){if(n[e])return n[e].exports;var i=n[e]={exports:{},id:e,loaded:!1};return t[e].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}var n={};return r.m=t,r.c=n,r.p="",r(0)}([function(t,r,n){t.exports=n(1)},function(t,r,n){"use strict";function e(t){return t&&t.__esModule?t:{"default":t}}var i=n(2),o=e(i);!function(){function r(t,r,o,u){return new Promise(function(a,h){t&&r&&o||h("generatePassword invalid parameter"),n(t,r).then(function(t){var r=e(t,o,u),n=i(u.password.settings);a(s(r,n))})})}function n(t,r){return new Promise(function(n,e){t&&r||e("encryptLogin parameter could not be empty");var i=8192,s=32;o["default"].pbkdf2(r,t,i,s,"sha256",function(t,r){t?e("error in pbkdf2"):n(r.toString("hex"))})})}function e(t,r){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],e=n.password,i=void 0===e?{length:12}:e,s=n.counter,u=void 0===s?1:s,a=r+u.toString(),h=o["default"].createHmac("sha256",t).update(a).digest("hex");return h.substring(0,i.length)}function i(){var t=arguments.length<=0||void 0===arguments[0]?["strong"]:arguments[0],r={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return t.map(function(t){return r[t]}).sort(function(t,r){return t.order>r.order}).map(function(t){return t.value}).join("")}function s(t,r){var n="";return u(t).forEach(function(t,e){var i=a(r,e);n+=h(i,t)}),n}function u(t){for(var r=[],n=0;n1?arguments[1]:"utf8"):a(this,r)):arguments.length>1?new t(r,arguments[1]):new t(r)}function s(r,n){if(r=g(r,n<0?0:0|y(n)),!t.TYPED_ARRAY_SUPPORT)for(var e=0;e>>1;return e&&(r.parent=K),r}function y(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function _(r,n){if(!(this instanceof _))return new _(r,n);var e=new t(r,n);return delete e.parent,e}function w(t,r){"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var e=!1;;)switch(r){case"ascii":case"binary":case"raw":case"raws":return n;case"utf8":case"utf-8":return H(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(t).length;default:if(e)return H(t).length;r=(""+r).toLowerCase(),e=!0}}function v(t,r,n){var e=!1;if(r=0|r,n=void 0===n||n===1/0?this.length:0|n,t||(t="utf8"),r<0&&(r=0),n>this.length&&(n=this.length),n<=r)return"";for(;;)switch(t){case"hex":return x(this,r,n);case"utf8":case"utf-8":return R(this,r,n);case"ascii":return P(this,r,n);case"binary":return T(this,r,n);case"base64":return S(this,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,r,n);default:if(e)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),e=!0}}function E(t,r,n,e){n=Number(n)||0;var i=t.length-n;e?(e=Number(e),e>i&&(e=i)):e=i;var o=r.length;if(o%2!==0)throw new Error("Invalid hex string");e>o/2&&(e=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+u<=n){var a,h,f,c;switch(u){case 1:o<128&&(s=o);break;case 2:a=t[i+1],128===(192&a)&&(c=(31&o)<<6|63&a,c>127&&(s=c));break;case 3:a=t[i+1],h=t[i+2],128===(192&a)&&128===(192&h)&&(c=(15&o)<<12|(63&a)<<6|63&h,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:a=t[i+1],h=t[i+2],f=t[i+3],128===(192&a)&&128===(192&h)&&128===(192&f)&&(c=(15&o)<<18|(63&a)<<12|(63&h)<<6|63&f,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,u=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|1023&s),e.push(s),i+=u}return U(e)}function U(t){var r=t.length;if(r<=Q)return String.fromCharCode.apply(String,t);for(var n="",e=0;ee)&&(n=e);for(var i="",o=r;on)throw new RangeError("Trying to access beyond buffer length")}function D(r,n,e,i,o,s){if(!t.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");if(n>o||nr.length)throw new RangeError("index out of range")}function k(t,r,n,e){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-n,2);i>>8*(e?i:1-i)}function Y(t,r,n,e){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-n,4);i>>8*(e?i:3-i)&255}function C(t,r,n,e,i,o){if(r>i||rt.length)throw new RangeError("index out of range");if(n<0)throw new RangeError("index out of range")}function M(t,r,n,e,i){return i||C(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),$.write(t,r,n,e,23,4),n+4}function z(t,r,n,e,i){return i||C(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),$.write(t,r,n,e,52,8),n+8}function j(t){if(t=N(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function N(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function F(t){return t<16?"0"+t.toString(16):t.toString(16)}function H(t,r){r=r||1/0;for(var n,e=t.length,i=null,o=[],s=0;s55295&&n<57344){if(!i){if(n>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(s+1===e){(r-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(r-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((r-=1)<0)break;o.push(n)}else if(n<2048){if((r-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((r-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function J(t){for(var r=[],n=0;n>8,i=n%256,o.push(i),o.push(e);return o}function q(t){return Z.toByteArray(j(t))}function G(t,r,n,e){for(var i=0;i=r.length||i>=t.length);i++)r[i+n]=t[i];return i}var Z=n(4),$=n(5),X=n(6);r.Buffer=t,r.SlowBuffer=_,r.INSPECT_MAX_BYTES=50,t.poolSize=8192;var K={};t.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:i(),t.TYPED_ARRAY_SUPPORT?(t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array):(t.prototype.length=void 0,t.prototype.parent=void 0),t.isBuffer=function(t){return!(null==t||!t._isBuffer)},t.compare=function(r,n){if(!t.isBuffer(r)||!t.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(r===n)return 0;for(var e=r.length,i=n.length,o=0,s=Math.min(e,i);o0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},t.prototype.compare=function(r){if(!t.isBuffer(r))throw new TypeError("Argument must be a Buffer");return this===r?0:t.compare(this,r)},t.prototype.indexOf=function(r,n){function e(t,r,n){for(var e=-1,i=0;n+i2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n>>=0,0===this.length)return-1;if(n>=this.length)return-1;if(n<0&&(n=Math.max(this.length+n,0)),"string"==typeof r)return 0===r.length?-1:String.prototype.indexOf.call(this,r,n);if(t.isBuffer(r))return e(this,r,n);if("number"==typeof r)return t.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,r,n):e(this,[r],n);throw new TypeError("val must be string, number or Buffer")},t.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},t.prototype.set=function(t,r){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,r)},t.prototype.write=function(t,r,n,e){if(void 0===r)e="utf8",n=this.length,r=0;else if(void 0===n&&"string"==typeof r)e=r,n=this.length,r=0;else if(isFinite(r))r=0|r,isFinite(n)?(n=0|n,void 0===e&&(e="utf8")):(e=n,n=void 0);else{var i=e;e=r,r=0|n,n=i}var o=this.length-r;if((void 0===n||n>o)&&(n=o),t.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("attempt to write outside buffer bounds");e||(e="utf8");for(var s=!1;;)switch(e){case"hex":return E(this,t,r,n);case"utf8":case"utf-8":return b(this,t,r,n);case"ascii":return m(this,t,r,n);case"binary":return B(this,t,r,n);case"base64":return A(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),s=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;t.prototype.slice=function(r,n){var e=this.length;r=~~r,n=void 0===n?e:~~n,r<0?(r+=e,r<0&&(r=0)):r>e&&(r=e),n<0?(n+=e,n<0&&(n=0)):n>e&&(n=e),n0&&(i*=256);)e+=this[t+--r]*i;return e},t.prototype.readUInt8=function(t,r){return r||O(t,1,this.length),this[t]},t.prototype.readUInt16LE=function(t,r){return r||O(t,2,this.length),this[t]|this[t+1]<<8},t.prototype.readUInt16BE=function(t,r){return r||O(t,2,this.length),this[t]<<8|this[t+1]},t.prototype.readUInt32LE=function(t,r){return r||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},t.prototype.readUInt32BE=function(t,r){return r||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},t.prototype.readIntLE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=this[t],i=1,o=0;++o=i&&(e-=Math.pow(2,8*r)),e},t.prototype.readIntBE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=r,i=1,o=this[t+--e];e>0&&(i*=256);)o+=this[t+--e]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*r)),o},t.prototype.readInt8=function(t,r){return r||O(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},t.prototype.readInt16LE=function(t,r){r||O(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(t,r){r||O(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(t,r){return r||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},t.prototype.readInt32BE=function(t,r){return r||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},t.prototype.readFloatLE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!0,23,4)},t.prototype.readFloatBE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!1,23,4)},t.prototype.readDoubleLE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!0,52,8)},t.prototype.readDoubleBE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!1,52,8)},t.prototype.writeUIntLE=function(t,r,n,e){t=+t,r=0|r,n=0|n,e||D(this,t,r,n,Math.pow(2,8*n),0);var i=1,o=0;for(this[r]=255&t;++o=0&&(o*=256);)this[r+i]=t/o&255;return r+n},t.prototype.writeUInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,255,0),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[n]=255&r,n+1},t.prototype.writeUInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeUInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeUInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n+3]=r>>>24,this[n+2]=r>>>16,this[n+1]=r>>>8,this[n]=255&r):Y(this,r,n,!0),n+4},t.prototype.writeUInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeIntLE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=0,s=1,u=t<0?1:0;for(this[r]=255&t;++o>0)-u&255;return r+n},t.prototype.writeIntBE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=n-1,s=1,u=t<0?1:0;for(this[r+o]=255&t;--o>=0&&(s*=256);)this[r+o]=(t/s>>0)-u&255;return r+n},t.prototype.writeInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,127,-128),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[n]=255&r,n+1},t.prototype.writeInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8,this[n+2]=r>>>16,this[n+3]=r>>>24):Y(this,r,n,!0),n+4},t.prototype.writeInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeFloatLE=function(t,r,n){return M(this,t,r,!0,n)},t.prototype.writeFloatBE=function(t,r,n){return M(this,t,r,!1,n)},t.prototype.writeDoubleLE=function(t,r,n){return z(this,t,r,!0,n)},t.prototype.writeDoubleBE=function(t,r,n){return z(this,t,r,!1,n)},t.prototype.copy=function(r,n,e,i){if(e||(e=0),i||0===i||(i=this.length),n>=r.length&&(n=r.length),n||(n=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),r.length-n=0;o--)r[o+n]=this[o+e];else if(s<1e3||!t.TYPED_ARRAY_SUPPORT)for(o=0;o=this.length)throw new RangeError("start out of bounds");if(n<0||n>this.length)throw new RangeError("end out of bounds");var e;if("number"==typeof t)for(e=r;e0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;a="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,h=new o(3*t.length/4-a),s=a>0?t.length-4:t.length;var c=0;for(e=0,i=0;e>16),n((65280&u)>>8),n(255&u);return 2===a?(u=r(t.charAt(e))<<2|r(t.charAt(e+1))>>4,n(255&u)):1===a&&(u=r(t.charAt(e))<<10|r(t.charAt(e+1))<<4|r(t.charAt(e+2))>>2,n(u>>8&255),n(255&u)),h}function i(t){function r(t){return e.charAt(t)}function n(t){return r(t>>18&63)+r(t>>12&63)+r(t>>6&63)+r(63&t)}var i,o,s,u=t.length%3,a="";for(i=0,s=t.length-u;i>2),a+=r(o<<4&63),a+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],a+=r(o>>10),a+=r(o>>4&63),a+=r(o<<2&63),a+="="}return a}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),u="/".charCodeAt(0),a="0".charCodeAt(0),h="a".charCodeAt(0),f="A".charCodeAt(0),c="-".charCodeAt(0),l="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}(r)},function(t,r){r.read=function(t,r,n,e,i){var o,s,u=8*i-e-1,a=(1<>1,f=-7,c=n?i-1:0,l=n?-1:1,p=t[r+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[r+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=e;f>0;s=256*s+t[r+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s+=Math.pow(2,e),o-=h}return(p?-1:1)*s*Math.pow(2,o-e)},r.write=function(t,r,n,e,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=e?0:o-1,d=e?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,s=f):(s=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-s))<1&&(s--,a*=2),r+=s+c>=1?l/a:l*Math.pow(2,1-c),r*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(r*a-1)*Math.pow(2,i),s+=c):(u=r*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[n+p]=255&s,p+=d,s/=256,h-=8);t[n+p-d]|=128*g}},function(t,r){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,r,n){(function(r,e){!function(){var i=("undefined"==typeof window?r:window)||{};_crypto=i.crypto||i.msCrypto||n(8),t.exports=function(t){if(_crypto.getRandomValues){var r=new e(t);return _crypto.getRandomValues(r),r}if(_crypto.randomBytes)return _crypto.randomBytes(t);throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}}()}).call(r,function(){return this}(),n(3).Buffer)},function(t,r){},function(t,r,n){(function(r){function e(t){return function(){var n=[],e={update:function(t,e){return r.isBuffer(t)||(t=new r(t,e)),n.push(t),this},digest:function(e){var i=r.concat(n),o=t(i);return n=null,e?o.toString(e):o}};return e}}var i=n(10),o=e(n(19)),s=e(n(21));t.exports=function(t){return"md5"===t?new o:"rmd160"===t?new s:i(t)}}).call(r,n(3).Buffer)},function(t,r,n){var r=t.exports=function(t){var n=r[t];if(!n)throw new Error(t+" is not supported (we accept pull requests)");return new n},e=n(3).Buffer,i=n(11)(e);r.sha1=n(12)(e,i),r.sha256=n(17)(e,i),r.sha512=n(18)(e,i)},function(t,r){t.exports=function(t){function r(r,n){this._block=new t(r),this._finalSize=n,this._blockSize=r,this._len=0,this._s=0}return r.prototype.init=function(){this._s=0,this._len=0},r.prototype.update=function(r,n){"string"==typeof r&&(n=n||"utf8",r=new t(r,n));for(var e=this._len+=r.length,i=this._s=this._s||0,o=0,s=this._block;i=8*this._finalSize&&(this._update(this._block),this._block.fill(0)),this._block.writeInt32BE(r,this._blockSize-4);var n=this._update(this._block)||this._hash();return t?n.toString(t):n},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},r}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){return d.length?d.pop().init():this instanceof n?(this._w=p,r.call(this,64,56),this._h=null,void this.init()):new n}function i(t,r,n,e){return t<20?r&n|~r&e:t<40?r^n^e:t<60?r&n|r&e|n&e:r^n^e}function o(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function s(t,r){return t+r|0}function u(t,r){return t<>>32-r}var a=0,h=4,f=8,c=12,l=16,p=new("undefined"==typeof Int32Array?Array:Int32Array)(80),d=[];return e(n,r),n.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,r.prototype.init.call(this),this},n.prototype._POOL=d,n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d;r=f=this._a,n=c=this._b,e=l=this._c,a=p=this._d,h=d=this._e;for(var g=this._w,y=0;y<80;y++){var _=g[y]=y<16?t.readInt32BE(4*y):u(g[y-3]^g[y-8]^g[y-14]^g[y-16],1),w=s(s(u(r,5),i(y,n,e,a)),s(s(h,_),o(y)));h=a,a=e,e=u(n,30),n=r,r=w}this._a=s(r,f),this._b=s(n,c),this._c=s(e,l),this._d=s(a,p),this._e=s(h,d)},n.prototype._hash=function(){d.length<100&&d.push(this);var r=new t(20);return r.writeInt32BE(0|this._a,a),r.writeInt32BE(0|this._b,h),r.writeInt32BE(0|this._c,f),r.writeInt32BE(0|this._d,c),r.writeInt32BE(0|this._e,l),r},n}},function(t,r,n){(function(t,e){function i(t,n){var e={seen:[],stylize:s};return arguments.length>=3&&(e.depth=arguments[2]),arguments.length>=4&&(e.colors=arguments[3]),g(n)?e.showHidden=n:n&&r._extend(e,n),b(e.showHidden)&&(e.showHidden=!1),b(e.depth)&&(e.depth=2),b(e.colors)&&(e.colors=!1),b(e.customInspect)&&(e.customInspect=!0),e.colors&&(e.stylize=o),a(e,t,e.depth)}function o(t,r){var n=i.styles[r];return n?"["+i.colors[n][0]+"m"+t+"["+i.colors[n][1]+"m":t}function s(t,r){return t}function u(t){var r={};return t.forEach(function(t,n){r[t]=!0}),r}function a(t,n,e){if(t.customInspect&&n&&S(n.inspect)&&n.inspect!==r.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(e,t);return v(i)||(i=a(t,i,e)),i}var o=h(t,n);if(o)return o;var s=Object.keys(n),g=u(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(n)),I(n)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return f(n);if(0===s.length){if(S(n)){var y=n.name?": "+n.name:"";return t.stylize("[Function"+y+"]","special")}if(m(n))return t.stylize(RegExp.prototype.toString.call(n),"regexp");if(A(n))return t.stylize(Date.prototype.toString.call(n),"date");if(I(n))return f(n)}var _="",w=!1,E=["{","}"];if(d(n)&&(w=!0,E=["[","]"]),S(n)){var b=n.name?": "+n.name:"";_=" [Function"+b+"]"}if(m(n)&&(_=" "+RegExp.prototype.toString.call(n)),A(n)&&(_=" "+Date.prototype.toUTCString.call(n)),I(n)&&(_=" "+f(n)),0===s.length&&(!w||0==n.length))return E[0]+_+E[1];if(e<0)return m(n)?t.stylize(RegExp.prototype.toString.call(n),"regexp"):t.stylize("[Object]","special");t.seen.push(n);var B;return B=w?c(t,n,e,g,s):s.map(function(r){return l(t,n,e,g,r,w)}),t.seen.pop(),p(B,_,E)}function h(t,r){if(b(r))return t.stylize("undefined","undefined");if(v(r)){var n="'"+JSON.stringify(r).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return w(r)?t.stylize(""+r,"number"):g(r)?t.stylize(""+r,"boolean"):y(r)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,r,n,e,i){for(var o=[],s=0,u=r.length;s-1&&(u=o?u.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+u.split("\n").map(function(t){return" "+t}).join("\n"))):u=t.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return u;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function p(t,r,n){var e=0,i=t.reduce(function(t,r){return e++,r.indexOf("\n")>=0&&e++,t+r.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===r?"":r+"\n ")+" "+t.join(",\n ")+" "+n[1]:n[0]+r+" "+t.join(", ")+" "+n[1]}function d(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function y(t){return null===t}function _(t){return null==t}function w(t){return"number"==typeof t}function v(t){return"string"==typeof t}function E(t){return"symbol"==typeof t}function b(t){return void 0===t}function m(t){return B(t)&&"[object RegExp]"===U(t)}function B(t){return"object"==typeof t&&null!==t}function A(t){return B(t)&&"[object Date]"===U(t)}function I(t){return B(t)&&("[object Error]"===U(t)||t instanceof Error)}function S(t){return"function"==typeof t}function R(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function U(t){return Object.prototype.toString.call(t)}function P(t){return t<10?"0"+t.toString(10):t.toString(10)}function T(){var t=new Date,r=[P(t.getHours()),P(t.getMinutes()),P(t.getSeconds())].join(":");return[t.getDate(),k[t.getMonth()],r].join(" ")}function x(t,r){return Object.prototype.hasOwnProperty.call(t,r)}var L=/%[sdj%]/g;r.format=function(t){if(!v(t)){for(var r=[],n=0;n=o)return t;switch(t){case"%s":return String(e[n++]);case"%d":return Number(e[n++]);case"%j":try{return JSON.stringify(e[n++])}catch(r){return"[Circular]"}default:return t}}),u=e[n];nr.order}).map(function(t){return t.value}).join("")}function s(t,r){var n="";return u(t).forEach(function(t,e){var i=a(r,e);n+=h(i,t)}),n}function u(t){for(var r=[],n=0;n1?arguments[1]:"utf8"):a(this,r)):arguments.length>1?new t(r,arguments[1]):new t(r)}function s(r,n){if(r=g(r,n<0?0:0|y(n)),!t.TYPED_ARRAY_SUPPORT)for(var e=0;e>>1;return e&&(r.parent=K),r}function y(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function _(r,n){if(!(this instanceof _))return new _(r,n);var e=new t(r,n);return delete e.parent,e}function w(t,r){"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var e=!1;;)switch(r){case"ascii":case"binary":case"raw":case"raws":return n;case"utf8":case"utf-8":return H(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(t).length;default:if(e)return H(t).length;r=(""+r).toLowerCase(),e=!0}}function v(t,r,n){var e=!1;if(r=0|r,n=void 0===n||n===1/0?this.length:0|n,t||(t="utf8"),r<0&&(r=0),n>this.length&&(n=this.length),n<=r)return"";for(;;)switch(t){case"hex":return x(this,r,n);case"utf8":case"utf-8":return R(this,r,n);case"ascii":return P(this,r,n);case"binary":return T(this,r,n);case"base64":return S(this,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,r,n);default:if(e)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),e=!0}}function E(t,r,n,e){n=Number(n)||0;var i=t.length-n;e?(e=Number(e),e>i&&(e=i)):e=i;var o=r.length;if(o%2!==0)throw new Error("Invalid hex string");e>o/2&&(e=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+u<=n){var a,h,f,c;switch(u){case 1:o<128&&(s=o);break;case 2:a=t[i+1],128===(192&a)&&(c=(31&o)<<6|63&a,c>127&&(s=c));break;case 3:a=t[i+1],h=t[i+2],128===(192&a)&&128===(192&h)&&(c=(15&o)<<12|(63&a)<<6|63&h,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:a=t[i+1],h=t[i+2],f=t[i+3],128===(192&a)&&128===(192&h)&&128===(192&f)&&(c=(15&o)<<18|(63&a)<<12|(63&h)<<6|63&f,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,u=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|1023&s),e.push(s),i+=u}return U(e)}function U(t){var r=t.length;if(r<=Q)return String.fromCharCode.apply(String,t);for(var n="",e=0;ee)&&(n=e);for(var i="",o=r;on)throw new RangeError("Trying to access beyond buffer length")}function D(r,n,e,i,o,s){if(!t.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");if(n>o||nr.length)throw new RangeError("index out of range")}function k(t,r,n,e){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-n,2);i>>8*(e?i:1-i)}function Y(t,r,n,e){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-n,4);i>>8*(e?i:3-i)&255}function C(t,r,n,e,i,o){if(r>i||rt.length)throw new RangeError("index out of range");if(n<0)throw new RangeError("index out of range")}function M(t,r,n,e,i){return i||C(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),$.write(t,r,n,e,23,4),n+4}function z(t,r,n,e,i){return i||C(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),$.write(t,r,n,e,52,8),n+8}function j(t){if(t=N(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function N(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function F(t){return t<16?"0"+t.toString(16):t.toString(16)}function H(t,r){r=r||1/0;for(var n,e=t.length,i=null,o=[],s=0;s55295&&n<57344){if(!i){if(n>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(s+1===e){(r-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(r-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((r-=1)<0)break;o.push(n)}else if(n<2048){if((r-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((r-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function J(t){for(var r=[],n=0;n>8,i=n%256,o.push(i),o.push(e);return o}function q(t){return Z.toByteArray(j(t))}function G(t,r,n,e){for(var i=0;i=r.length||i>=t.length);i++)r[i+n]=t[i];return i}var Z=n(4),$=n(5),X=n(6);r.Buffer=t,r.SlowBuffer=_,r.INSPECT_MAX_BYTES=50,t.poolSize=8192;var K={};t.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:i(),t.TYPED_ARRAY_SUPPORT?(t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array):(t.prototype.length=void 0,t.prototype.parent=void 0),t.isBuffer=function(t){return!(null==t||!t._isBuffer)},t.compare=function(r,n){if(!t.isBuffer(r)||!t.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(r===n)return 0;for(var e=r.length,i=n.length,o=0,s=Math.min(e,i);o0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},t.prototype.compare=function(r){if(!t.isBuffer(r))throw new TypeError("Argument must be a Buffer");return this===r?0:t.compare(this,r)},t.prototype.indexOf=function(r,n){function e(t,r,n){for(var e=-1,i=0;n+i2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n>>=0,0===this.length)return-1;if(n>=this.length)return-1;if(n<0&&(n=Math.max(this.length+n,0)),"string"==typeof r)return 0===r.length?-1:String.prototype.indexOf.call(this,r,n);if(t.isBuffer(r))return e(this,r,n);if("number"==typeof r)return t.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,r,n):e(this,[r],n);throw new TypeError("val must be string, number or Buffer")},t.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},t.prototype.set=function(t,r){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,r)},t.prototype.write=function(t,r,n,e){if(void 0===r)e="utf8",n=this.length,r=0;else if(void 0===n&&"string"==typeof r)e=r,n=this.length,r=0;else if(isFinite(r))r=0|r,isFinite(n)?(n=0|n,void 0===e&&(e="utf8")):(e=n,n=void 0);else{var i=e;e=r,r=0|n,n=i}var o=this.length-r;if((void 0===n||n>o)&&(n=o),t.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("attempt to write outside buffer bounds");e||(e="utf8");for(var s=!1;;)switch(e){case"hex":return E(this,t,r,n);case"utf8":case"utf-8":return b(this,t,r,n);case"ascii":return m(this,t,r,n);case"binary":return B(this,t,r,n);case"base64":return A(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),s=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;t.prototype.slice=function(r,n){var e=this.length;r=~~r,n=void 0===n?e:~~n,r<0?(r+=e,r<0&&(r=0)):r>e&&(r=e),n<0?(n+=e,n<0&&(n=0)):n>e&&(n=e),n0&&(i*=256);)e+=this[t+--r]*i;return e},t.prototype.readUInt8=function(t,r){return r||O(t,1,this.length),this[t]},t.prototype.readUInt16LE=function(t,r){return r||O(t,2,this.length),this[t]|this[t+1]<<8},t.prototype.readUInt16BE=function(t,r){return r||O(t,2,this.length),this[t]<<8|this[t+1]},t.prototype.readUInt32LE=function(t,r){return r||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},t.prototype.readUInt32BE=function(t,r){return r||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},t.prototype.readIntLE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=this[t],i=1,o=0;++o=i&&(e-=Math.pow(2,8*r)),e},t.prototype.readIntBE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=r,i=1,o=this[t+--e];e>0&&(i*=256);)o+=this[t+--e]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*r)),o},t.prototype.readInt8=function(t,r){return r||O(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},t.prototype.readInt16LE=function(t,r){r||O(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(t,r){r||O(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(t,r){return r||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},t.prototype.readInt32BE=function(t,r){return r||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},t.prototype.readFloatLE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!0,23,4)},t.prototype.readFloatBE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!1,23,4)},t.prototype.readDoubleLE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!0,52,8)},t.prototype.readDoubleBE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!1,52,8)},t.prototype.writeUIntLE=function(t,r,n,e){t=+t,r=0|r,n=0|n,e||D(this,t,r,n,Math.pow(2,8*n),0);var i=1,o=0;for(this[r]=255&t;++o=0&&(o*=256);)this[r+i]=t/o&255;return r+n},t.prototype.writeUInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,255,0),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[n]=255&r,n+1},t.prototype.writeUInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeUInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeUInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n+3]=r>>>24,this[n+2]=r>>>16,this[n+1]=r>>>8,this[n]=255&r):Y(this,r,n,!0),n+4},t.prototype.writeUInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeIntLE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=0,s=1,u=t<0?1:0;for(this[r]=255&t;++o>0)-u&255;return r+n},t.prototype.writeIntBE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=n-1,s=1,u=t<0?1:0;for(this[r+o]=255&t;--o>=0&&(s*=256);)this[r+o]=(t/s>>0)-u&255;return r+n},t.prototype.writeInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,127,-128),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[n]=255&r,n+1},t.prototype.writeInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8,this[n+2]=r>>>16,this[n+3]=r>>>24):Y(this,r,n,!0),n+4},t.prototype.writeInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeFloatLE=function(t,r,n){return M(this,t,r,!0,n)},t.prototype.writeFloatBE=function(t,r,n){return M(this,t,r,!1,n)},t.prototype.writeDoubleLE=function(t,r,n){return z(this,t,r,!0,n)},t.prototype.writeDoubleBE=function(t,r,n){return z(this,t,r,!1,n)},t.prototype.copy=function(r,n,e,i){if(e||(e=0),i||0===i||(i=this.length),n>=r.length&&(n=r.length),n||(n=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),r.length-n=0;o--)r[o+n]=this[o+e];else if(s<1e3||!t.TYPED_ARRAY_SUPPORT)for(o=0;o=this.length)throw new RangeError("start out of bounds");if(n<0||n>this.length)throw new RangeError("end out of bounds");var e;if("number"==typeof t)for(e=r;e0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;a="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,h=new o(3*t.length/4-a),s=a>0?t.length-4:t.length;var c=0;for(e=0,i=0;e>16),n((65280&u)>>8),n(255&u);return 2===a?(u=r(t.charAt(e))<<2|r(t.charAt(e+1))>>4,n(255&u)):1===a&&(u=r(t.charAt(e))<<10|r(t.charAt(e+1))<<4|r(t.charAt(e+2))>>2,n(u>>8&255),n(255&u)),h}function i(t){function r(t){return e.charAt(t)}function n(t){return r(t>>18&63)+r(t>>12&63)+r(t>>6&63)+r(63&t)}var i,o,s,u=t.length%3,a="";for(i=0,s=t.length-u;i>2),a+=r(o<<4&63),a+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],a+=r(o>>10),a+=r(o>>4&63),a+=r(o<<2&63),a+="="}return a}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),u="/".charCodeAt(0),a="0".charCodeAt(0),h="a".charCodeAt(0),f="A".charCodeAt(0),c="-".charCodeAt(0),l="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}(r)},function(t,r){r.read=function(t,r,n,e,i){var o,s,u=8*i-e-1,a=(1<>1,f=-7,c=n?i-1:0,l=n?-1:1,p=t[r+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[r+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=e;f>0;s=256*s+t[r+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s+=Math.pow(2,e),o-=h}return(p?-1:1)*s*Math.pow(2,o-e)},r.write=function(t,r,n,e,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=e?0:o-1,d=e?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,s=f):(s=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-s))<1&&(s--,a*=2),r+=s+c>=1?l/a:l*Math.pow(2,1-c),r*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(r*a-1)*Math.pow(2,i),s+=c):(u=r*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[n+p]=255&s,p+=d,s/=256,h-=8);t[n+p-d]|=128*g}},function(t,r){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,r,n){(function(r,e){!function(){var i=("undefined"==typeof window?r:window)||{};_crypto=i.crypto||i.msCrypto||n(8),t.exports=function(t){if(_crypto.getRandomValues){var r=new e(t);return _crypto.getRandomValues(r),r}if(_crypto.randomBytes)return _crypto.randomBytes(t);throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}}()}).call(r,function(){return this}(),n(3).Buffer)},function(t,r){},function(t,r,n){(function(r){function e(t){return function(){var n=[],e={update:function(t,e){return r.isBuffer(t)||(t=new r(t,e)),n.push(t),this},digest:function(e){var i=r.concat(n),o=t(i);return n=null,e?o.toString(e):o}};return e}}var i=n(10),o=e(n(19)),s=e(n(21));t.exports=function(t){return"md5"===t?new o:"rmd160"===t?new s:i(t)}}).call(r,n(3).Buffer)},function(t,r,n){var r=t.exports=function(t){var n=r[t];if(!n)throw new Error(t+" is not supported (we accept pull requests)");return new n},e=n(3).Buffer,i=n(11)(e);r.sha1=n(12)(e,i),r.sha256=n(17)(e,i),r.sha512=n(18)(e,i)},function(t,r){t.exports=function(t){function r(r,n){this._block=new t(r),this._finalSize=n,this._blockSize=r,this._len=0,this._s=0}return r.prototype.init=function(){this._s=0,this._len=0},r.prototype.update=function(r,n){"string"==typeof r&&(n=n||"utf8",r=new t(r,n));for(var e=this._len+=r.length,i=this._s=this._s||0,o=0,s=this._block;i=8*this._finalSize&&(this._update(this._block),this._block.fill(0)),this._block.writeInt32BE(r,this._blockSize-4);var n=this._update(this._block)||this._hash();return t?n.toString(t):n},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},r}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){return d.length?d.pop().init():this instanceof n?(this._w=p,r.call(this,64,56),this._h=null,void this.init()):new n}function i(t,r,n,e){return t<20?r&n|~r&e:t<40?r^n^e:t<60?r&n|r&e|n&e:r^n^e}function o(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function s(t,r){return t+r|0}function u(t,r){return t<>>32-r}var a=0,h=4,f=8,c=12,l=16,p=new("undefined"==typeof Int32Array?Array:Int32Array)(80),d=[];return e(n,r),n.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,r.prototype.init.call(this),this},n.prototype._POOL=d,n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d;r=f=this._a,n=c=this._b,e=l=this._c,a=p=this._d,h=d=this._e;for(var g=this._w,y=0;y<80;y++){var _=g[y]=y<16?t.readInt32BE(4*y):u(g[y-3]^g[y-8]^g[y-14]^g[y-16],1),w=s(s(u(r,5),i(y,n,e,a)),s(s(h,_),o(y)));h=a,a=e,e=u(n,30),n=r,r=w}this._a=s(r,f),this._b=s(n,c),this._c=s(e,l),this._d=s(a,p),this._e=s(h,d)},n.prototype._hash=function(){d.length<100&&d.push(this);var r=new t(20);return r.writeInt32BE(0|this._a,a),r.writeInt32BE(0|this._b,h),r.writeInt32BE(0|this._c,f),r.writeInt32BE(0|this._d,c),r.writeInt32BE(0|this._e,l),r},n}},function(t,r,n){(function(t,e){function i(t,n){var e={seen:[],stylize:s};return arguments.length>=3&&(e.depth=arguments[2]),arguments.length>=4&&(e.colors=arguments[3]),g(n)?e.showHidden=n:n&&r._extend(e,n),b(e.showHidden)&&(e.showHidden=!1),b(e.depth)&&(e.depth=2),b(e.colors)&&(e.colors=!1),b(e.customInspect)&&(e.customInspect=!0),e.colors&&(e.stylize=o),a(e,t,e.depth)}function o(t,r){var n=i.styles[r];return n?"["+i.colors[n][0]+"m"+t+"["+i.colors[n][1]+"m":t}function s(t,r){return t}function u(t){var r={};return t.forEach(function(t,n){r[t]=!0}),r}function a(t,n,e){if(t.customInspect&&n&&S(n.inspect)&&n.inspect!==r.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(e,t);return v(i)||(i=a(t,i,e)),i}var o=h(t,n);if(o)return o;var s=Object.keys(n),g=u(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(n)),I(n)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return f(n);if(0===s.length){if(S(n)){var y=n.name?": "+n.name:"";return t.stylize("[Function"+y+"]","special")}if(m(n))return t.stylize(RegExp.prototype.toString.call(n),"regexp");if(A(n))return t.stylize(Date.prototype.toString.call(n),"date");if(I(n))return f(n)}var _="",w=!1,E=["{","}"];if(d(n)&&(w=!0,E=["[","]"]),S(n)){var b=n.name?": "+n.name:"";_=" [Function"+b+"]"}if(m(n)&&(_=" "+RegExp.prototype.toString.call(n)),A(n)&&(_=" "+Date.prototype.toUTCString.call(n)),I(n)&&(_=" "+f(n)),0===s.length&&(!w||0==n.length))return E[0]+_+E[1];if(e<0)return m(n)?t.stylize(RegExp.prototype.toString.call(n),"regexp"):t.stylize("[Object]","special");t.seen.push(n);var B;return B=w?c(t,n,e,g,s):s.map(function(r){return l(t,n,e,g,r,w)}),t.seen.pop(),p(B,_,E)}function h(t,r){if(b(r))return t.stylize("undefined","undefined");if(v(r)){var n="'"+JSON.stringify(r).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return w(r)?t.stylize(""+r,"number"):g(r)?t.stylize(""+r,"boolean"):y(r)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,r,n,e,i){for(var o=[],s=0,u=r.length;s-1&&(u=o?u.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+u.split("\n").map(function(t){return" "+t}).join("\n"))):u=t.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return u;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function p(t,r,n){var e=0,i=t.reduce(function(t,r){return e++,r.indexOf("\n")>=0&&e++,t+r.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===r?"":r+"\n ")+" "+t.join(",\n ")+" "+n[1]:n[0]+r+" "+t.join(", ")+" "+n[1]}function d(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function y(t){return null===t}function _(t){return null==t}function w(t){return"number"==typeof t}function v(t){return"string"==typeof t}function E(t){return"symbol"==typeof t}function b(t){return void 0===t}function m(t){return B(t)&&"[object RegExp]"===U(t)}function B(t){return"object"==typeof t&&null!==t}function A(t){return B(t)&&"[object Date]"===U(t)}function I(t){return B(t)&&("[object Error]"===U(t)||t instanceof Error)}function S(t){return"function"==typeof t}function R(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function U(t){return Object.prototype.toString.call(t)}function P(t){return t<10?"0"+t.toString(10):t.toString(10)}function T(){var t=new Date,r=[P(t.getHours()),P(t.getMinutes()),P(t.getSeconds())].join(":");return[t.getDate(),k[t.getMonth()],r].join(" ")}function x(t,r){return Object.prototype.hasOwnProperty.call(t,r)}var L=/%[sdj%]/g;r.format=function(t){if(!v(t)){for(var r=[],n=0;n=o)return t;switch(t){case"%s":return String(e[n++]);case"%d":return Number(e[n++]);case"%j":try{return JSON.stringify(e[n++])}catch(r){return"[Circular]"}default:return t}}),u=e[n];n1)for(var n=1;n>>r|t<<32-r}function o(t,r){return t>>>r}function s(t,r,n){return t&r^~t&n}function u(t,r,n){return t&r^t&n^r&n}function a(t){return i(t,2)^i(t,13)^i(t,22)}function h(t){return i(t,6)^i(t,11)^i(t,25)}function f(t){return i(t,7)^i(t,18)^o(t,3)}function c(t){return i(t,17)^i(t,19)^o(t,10)}var l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=new Array(64);return e(n,r),n.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._len=this._s=0,this},n.prototype._update=function(t){var r,n,e,i,o,p,d,g,y,_,w=this._w;r=0|this._a,n=0|this._b,e=0|this._c,i=0|this._d,o=0|this._e,p=0|this._f,d=0|this._g,g=0|this._h;for(var v=0;v<64;v++){var E=w[v]=v<16?t.readInt32BE(4*v):c(w[v-2])+w[v-7]+f(w[v-15])+w[v-16];y=g+h(o)+s(o,p,d)+l[v]+E,_=a(r)+u(r,n,e),g=d,d=p,p=o,o=i+y,i=e,e=n,n=r,r=y+_}this._a=r+this._a|0,this._b=n+this._b|0,this._c=e+this._c|0,this._d=i+this._d|0,this._e=o+this._e|0,this._f=p+this._f|0,this._g=d+this._g|0,this._h=g+this._h|0},n.prototype._hash=function(){var r=new t(32);return r.writeInt32BE(this._a,0),r.writeInt32BE(this._b,4),r.writeInt32BE(this._c,8),r.writeInt32BE(this._d,12),r.writeInt32BE(this._e,16),r.writeInt32BE(this._f,20),r.writeInt32BE(this._g,24),r.writeInt32BE(this._h,28),r},n}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){this.init(),this._w=a,r.call(this,128,112)}function i(t,r,n){return t>>>n|r<<32-n}function o(t,r,n){return t&r^~t&n}function s(t,r,n){return t&r^t&n^r&n}var u=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);return e(n,r),n.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._al=-205731576,this._bl=-2067093701,this._cl=-23791573,this._dl=1595750129,this._el=-1377402159,this._fl=725511199,this._gl=-79577749,this._hl=327033209,this._len=this._s=0,this},n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d,g,y,_,w,v,E,b=this._w;r=0|this._a,n=0|this._b,e=0|this._c,a=0|this._d,h=0|this._e,f=0|this._f,c=0|this._g,l=0|this._h,p=0|this._al,d=0|this._bl,g=0|this._cl,y=0|this._dl,_=0|this._el,w=0|this._fl,v=0|this._gl,E=0|this._hl;for(var m=0;m<80;m++){var B,A,I=2*m;if(m<16)B=b[I]=t.readInt32BE(4*I),A=b[I+1]=t.readInt32BE(4*I+4);else{var S=b[I-30],R=b[I-30+1],U=i(S,R,1)^i(S,R,8)^S>>>7,P=i(R,S,1)^i(R,S,8)^i(R,S,7);S=b[I-4],R=b[I-4+1];var T=i(S,R,19)^i(R,S,29)^S>>>6,x=i(R,S,19)^i(S,R,29)^i(R,S,6),L=b[I-14],O=b[I-14+1],D=b[I-32],k=b[I-32+1];A=P+O,B=U+L+(A>>>0

>>0?1:0),A+=x,B=B+T+(A>>>0>>0?1:0),A+=k,B=B+D+(A>>>0>>0?1:0),b[I]=B,b[I+1]=A}var Y=s(r,n,e),C=s(p,d,g),M=i(r,p,28)^i(p,r,2)^i(p,r,7),z=i(p,r,28)^i(r,p,2)^i(r,p,7),j=i(h,_,14)^i(h,_,18)^i(_,h,9),N=i(_,h,14)^i(_,h,18)^i(h,_,9),F=u[I],H=u[I+1],J=o(h,f,c),V=o(_,w,v),q=E+N,G=l+j+(q>>>0>>0?1:0);q+=V,G=G+J+(q>>>0>>0?1:0),q+=H,G=G+F+(q>>>0>>0?1:0),q+=A,G=G+B+(q>>>0>>0?1:0);var Z=z+C,$=M+Y+(Z>>>0>>0?1:0);l=c,E=v,c=f,v=w,f=h,w=_,_=y+q|0,h=a+G+(_>>>0>>0?1:0)|0,a=e,y=g,e=n,g=d,n=r,d=p,p=q+Z|0,r=G+$+(p>>>0>>0?1:0)|0}this._al=this._al+p|0,this._bl=this._bl+d|0,this._cl=this._cl+g|0,this._dl=this._dl+y|0,this._el=this._el+_|0,this._fl=this._fl+w|0,this._gl=this._gl+v|0,this._hl=this._hl+E|0,this._a=this._a+r+(this._al>>>0

>>0?1:0)|0,this._b=this._b+n+(this._bl>>>0>>0?1:0)|0,this._c=this._c+e+(this._cl>>>0>>0?1:0)|0,this._d=this._d+a+(this._dl>>>0>>0?1:0)|0,this._e=this._e+h+(this._el>>>0<_>>>0?1:0)|0,this._f=this._f+f+(this._fl>>>0>>0?1:0)|0,this._g=this._g+c+(this._gl>>>0>>0?1:0)|0,this._h=this._h+l+(this._hl>>>0>>0?1:0)|0},n.prototype._hash=function(){function r(t,r,e){n.writeInt32BE(t,e),n.writeInt32BE(r,e+4)}var n=new t(64);return r(this._a,this._al,0),r(this._b,this._bl,8),r(this._c,this._cl,16),r(this._d,this._dl,24),r(this._e,this._el,32),r(this._f,this._fl,40),r(this._g,this._gl,48),r(this._h,this._hl,56),n},n}},function(t,r,n){function e(t,r){t[r>>5]|=128<>>9<<4)+14]=r;for(var n=1732584193,e=-271733879,i=-1732584194,f=271733878,c=0;c>16)+(r>>16)+(n>>16);return e<<16|65535&n}function f(t,r){return t<>>32-r}var c=n(20);t.exports=function(t){return c.hash(t,e,16)}},function(t,r,n){(function(r){function n(t,n){if(t.length%o!==0){var e=t.length+(o-t.length%o);t=r.concat([t,s],e)}for(var i=[],u=n?t.readInt32BE:t.readInt32LE,a=0;a>>32-r}function a(t){var n=[1732584193,4023233417,2562383102,271733878,3285377520];"string"==typeof t&&(t=new r(t,"utf8"));var e=g(t),i=8*t.length,o=8*t.length;e[i>>>5]|=128<<24-i%32,e[(i+64>>>9<<4)+14]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8);for(var s=0;s>>24)|4278255360&(u<<24|u>>>8)}var a=y(n);return new r(a)}t.exports=a;var h=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],f=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],c=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],l=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],p=[0,1518500249,1859775393,2400959708,2840853838],d=[1352829926,1548603684,1836072691,2053994217,0],g=function(t){for(var r=[],n=0,e=0;n>>5]|=t[n]<<24-e%32;return r},y=function(t){for(var r=[],n=0;n<32*t.length;n+=8)r.push(t[n>>>5]>>>24-n%32&255);return r},_=function(t,r,a){for(var g=0;g<16;g++){var y=a+g,_=r[y];r[y]=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8)}var w,v,E,b,m,B,A,I,S,R;B=w=t[0],A=v=t[1],I=E=t[2],S=b=t[3],R=m=t[4];for(var U,g=0;g<80;g+=1)U=w+r[a+h[g]]|0,U+=g<16?n(v,E,b)+p[0]:g<32?e(v,E,b)+p[1]:g<48?i(v,E,b)+p[2]:g<64?o(v,E,b)+p[3]:s(v,E,b)+p[4],U=0|U,U=u(U,c[g]),U=U+m|0,w=m,m=b,b=u(E,10),E=v,v=U,U=B+r[a+f[g]]|0,U+=g<16?s(A,I,S)+d[0]:g<32?o(A,I,S)+d[1]:g<48?i(A,I,S)+d[2]:g<64?e(A,I,S)+d[3]:n(A,I,S)+d[4],U=0|U,U=u(U,l[g]),U=U+R|0,B=R,R=S,S=u(I,10),I=A,A=U;U=t[1]+E+S|0,t[1]=t[2]+b+R|0,t[2]=t[3]+m+B|0,t[3]=t[4]+w+A|0,t[4]=t[0]+v+I|0,t[0]=U}}).call(r,n(3).Buffer)},function(t,r,n){(function(r){function e(t,n){if(!(this instanceof e))return new e(t,n);this._opad=a,this._alg=t;var s="sha512"===t?128:64;n=this._key=r.isBuffer(n)?n:new r(n),n.length>s?n=i(t).update(n).digest():n.length(Math.pow(2,32)-1)*u))throw new TypeError("keylen exceeds maximum length");d.copy(h,0,0,u);for(var g=1;g Date: Fri, 1 Jul 2016 19:20:14 +0200 Subject: [PATCH 023/124] 3.1.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 7f7dff1..601c3c0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.1.0", + "version": "3.1.1", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "src/lesspass.js", From 3c9004144e57e2266ffce4ad8b97f562a8dac1b3 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 3 Jul 2016 09:28:11 +0200 Subject: [PATCH 024/124] use browesrify to generate lesspass module for browser --- dist/lesspass.min.js | 5 +- package.json | 12 +++- src/lesspass.js | 183 ++++++++++++++++++++++++--------------------------- webpack.config.js | 28 -------- 4 files changed, 98 insertions(+), 130 deletions(-) delete mode 100644 webpack.config.js diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js index 6c26fce..a8594e0 100644 --- a/dist/lesspass.min.js +++ b/dist/lesspass.min.js @@ -1,2 +1,3 @@ -!function(t){function r(e){if(n[e])return n[e].exports;var i=n[e]={exports:{},id:e,loaded:!1};return t[e].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}var n={};return r.m=t,r.c=n,r.p="",r(0)}([function(t,r,n){t.exports=n(1)},function(t,r,n){"use strict";function e(t){return t&&t.__esModule?t:{"default":t}}var i=n(2),o=e(i);!function(){function r(t,r,o,u){return new Promise(function(a,h){t&&r&&o||h("generatePassword invalid parameter"),n(t,r).then(function(t){var r=e(t,o,u),n=i(u.password.settings);a(s(r,n))})})}function n(t,r){return new Promise(function(n,e){t&&r||e("encryptLogin parameter could not be empty");var i=8192,s=32;o["default"].pbkdf2(r,t,i,s,"sha256",function(t,r){t?e("error in pbkdf2"):n(r.toString("hex"))})})}function e(t,r){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],e=n.password,i=void 0===e?{length:12}:e,s=n.counter,u=void 0===s?1:s,a=r+u.toString(),h=o["default"].createHmac("sha256",t).update(a).digest("hex");return h.substring(0,i.length)}function i(){var t=arguments.length<=0||void 0===arguments[0]?["strong"]:arguments[0],r={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return t.map(function(t){return r[t]}).sort(function(t,r){return t.order>r.order}).map(function(t){return t.value}).join("")}function s(t,r){var n="";return u(t).forEach(function(t,e){var i=a(r,e);n+=h(i,t)}),n}function u(t){for(var r=[],n=0;n1?arguments[1]:"utf8"):a(this,r)):arguments.length>1?new t(r,arguments[1]):new t(r)}function s(r,n){if(r=g(r,n<0?0:0|y(n)),!t.TYPED_ARRAY_SUPPORT)for(var e=0;e>>1;return e&&(r.parent=K),r}function y(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function _(r,n){if(!(this instanceof _))return new _(r,n);var e=new t(r,n);return delete e.parent,e}function w(t,r){"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var e=!1;;)switch(r){case"ascii":case"binary":case"raw":case"raws":return n;case"utf8":case"utf-8":return H(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(t).length;default:if(e)return H(t).length;r=(""+r).toLowerCase(),e=!0}}function v(t,r,n){var e=!1;if(r=0|r,n=void 0===n||n===1/0?this.length:0|n,t||(t="utf8"),r<0&&(r=0),n>this.length&&(n=this.length),n<=r)return"";for(;;)switch(t){case"hex":return x(this,r,n);case"utf8":case"utf-8":return R(this,r,n);case"ascii":return P(this,r,n);case"binary":return T(this,r,n);case"base64":return S(this,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,r,n);default:if(e)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),e=!0}}function E(t,r,n,e){n=Number(n)||0;var i=t.length-n;e?(e=Number(e),e>i&&(e=i)):e=i;var o=r.length;if(o%2!==0)throw new Error("Invalid hex string");e>o/2&&(e=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+u<=n){var a,h,f,c;switch(u){case 1:o<128&&(s=o);break;case 2:a=t[i+1],128===(192&a)&&(c=(31&o)<<6|63&a,c>127&&(s=c));break;case 3:a=t[i+1],h=t[i+2],128===(192&a)&&128===(192&h)&&(c=(15&o)<<12|(63&a)<<6|63&h,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:a=t[i+1],h=t[i+2],f=t[i+3],128===(192&a)&&128===(192&h)&&128===(192&f)&&(c=(15&o)<<18|(63&a)<<12|(63&h)<<6|63&f,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,u=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|1023&s),e.push(s),i+=u}return U(e)}function U(t){var r=t.length;if(r<=Q)return String.fromCharCode.apply(String,t);for(var n="",e=0;ee)&&(n=e);for(var i="",o=r;on)throw new RangeError("Trying to access beyond buffer length")}function D(r,n,e,i,o,s){if(!t.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");if(n>o||nr.length)throw new RangeError("index out of range")}function k(t,r,n,e){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-n,2);i>>8*(e?i:1-i)}function Y(t,r,n,e){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-n,4);i>>8*(e?i:3-i)&255}function C(t,r,n,e,i,o){if(r>i||rt.length)throw new RangeError("index out of range");if(n<0)throw new RangeError("index out of range")}function M(t,r,n,e,i){return i||C(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),$.write(t,r,n,e,23,4),n+4}function z(t,r,n,e,i){return i||C(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),$.write(t,r,n,e,52,8),n+8}function j(t){if(t=N(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function N(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function F(t){return t<16?"0"+t.toString(16):t.toString(16)}function H(t,r){r=r||1/0;for(var n,e=t.length,i=null,o=[],s=0;s55295&&n<57344){if(!i){if(n>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(s+1===e){(r-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(r-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((r-=1)<0)break;o.push(n)}else if(n<2048){if((r-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((r-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function J(t){for(var r=[],n=0;n>8,i=n%256,o.push(i),o.push(e);return o}function q(t){return Z.toByteArray(j(t))}function G(t,r,n,e){for(var i=0;i=r.length||i>=t.length);i++)r[i+n]=t[i];return i}var Z=n(4),$=n(5),X=n(6);r.Buffer=t,r.SlowBuffer=_,r.INSPECT_MAX_BYTES=50,t.poolSize=8192;var K={};t.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:i(),t.TYPED_ARRAY_SUPPORT?(t.prototype.__proto__=Uint8Array.prototype,t.__proto__=Uint8Array):(t.prototype.length=void 0,t.prototype.parent=void 0),t.isBuffer=function(t){return!(null==t||!t._isBuffer)},t.compare=function(r,n){if(!t.isBuffer(r)||!t.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(r===n)return 0;for(var e=r.length,i=n.length,o=0,s=Math.min(e,i);o0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},t.prototype.compare=function(r){if(!t.isBuffer(r))throw new TypeError("Argument must be a Buffer");return this===r?0:t.compare(this,r)},t.prototype.indexOf=function(r,n){function e(t,r,n){for(var e=-1,i=0;n+i2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n>>=0,0===this.length)return-1;if(n>=this.length)return-1;if(n<0&&(n=Math.max(this.length+n,0)),"string"==typeof r)return 0===r.length?-1:String.prototype.indexOf.call(this,r,n);if(t.isBuffer(r))return e(this,r,n);if("number"==typeof r)return t.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,r,n):e(this,[r],n);throw new TypeError("val must be string, number or Buffer")},t.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},t.prototype.set=function(t,r){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,r)},t.prototype.write=function(t,r,n,e){if(void 0===r)e="utf8",n=this.length,r=0;else if(void 0===n&&"string"==typeof r)e=r,n=this.length,r=0;else if(isFinite(r))r=0|r,isFinite(n)?(n=0|n,void 0===e&&(e="utf8")):(e=n,n=void 0);else{var i=e;e=r,r=0|n,n=i}var o=this.length-r;if((void 0===n||n>o)&&(n=o),t.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("attempt to write outside buffer bounds");e||(e="utf8");for(var s=!1;;)switch(e){case"hex":return E(this,t,r,n);case"utf8":case"utf-8":return b(this,t,r,n);case"ascii":return m(this,t,r,n);case"binary":return B(this,t,r,n);case"base64":return A(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),s=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;t.prototype.slice=function(r,n){var e=this.length;r=~~r,n=void 0===n?e:~~n,r<0?(r+=e,r<0&&(r=0)):r>e&&(r=e),n<0?(n+=e,n<0&&(n=0)):n>e&&(n=e),n0&&(i*=256);)e+=this[t+--r]*i;return e},t.prototype.readUInt8=function(t,r){return r||O(t,1,this.length),this[t]},t.prototype.readUInt16LE=function(t,r){return r||O(t,2,this.length),this[t]|this[t+1]<<8},t.prototype.readUInt16BE=function(t,r){return r||O(t,2,this.length),this[t]<<8|this[t+1]},t.prototype.readUInt32LE=function(t,r){return r||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},t.prototype.readUInt32BE=function(t,r){return r||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},t.prototype.readIntLE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=this[t],i=1,o=0;++o=i&&(e-=Math.pow(2,8*r)),e},t.prototype.readIntBE=function(t,r,n){t=0|t,r=0|r,n||O(t,r,this.length);for(var e=r,i=1,o=this[t+--e];e>0&&(i*=256);)o+=this[t+--e]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*r)),o},t.prototype.readInt8=function(t,r){return r||O(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},t.prototype.readInt16LE=function(t,r){r||O(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(t,r){r||O(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(t,r){return r||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},t.prototype.readInt32BE=function(t,r){return r||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},t.prototype.readFloatLE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!0,23,4)},t.prototype.readFloatBE=function(t,r){return r||O(t,4,this.length),$.read(this,t,!1,23,4)},t.prototype.readDoubleLE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!0,52,8)},t.prototype.readDoubleBE=function(t,r){return r||O(t,8,this.length),$.read(this,t,!1,52,8)},t.prototype.writeUIntLE=function(t,r,n,e){t=+t,r=0|r,n=0|n,e||D(this,t,r,n,Math.pow(2,8*n),0);var i=1,o=0;for(this[r]=255&t;++o=0&&(o*=256);)this[r+i]=t/o&255;return r+n},t.prototype.writeUInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,255,0),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[n]=255&r,n+1},t.prototype.writeUInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeUInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,65535,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeUInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n+3]=r>>>24,this[n+2]=r>>>16,this[n+1]=r>>>8,this[n]=255&r):Y(this,r,n,!0),n+4},t.prototype.writeUInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,4294967295,0),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeIntLE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=0,s=1,u=t<0?1:0;for(this[r]=255&t;++o>0)-u&255;return r+n},t.prototype.writeIntBE=function(t,r,n,e){if(t=+t,r=0|r,!e){var i=Math.pow(2,8*n-1);D(this,t,r,n,i-1,-i)}var o=n-1,s=1,u=t<0?1:0;for(this[r+o]=255&t;--o>=0&&(s*=256);)this[r+o]=(t/s>>0)-u&255;return r+n},t.prototype.writeInt8=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,1,127,-128),t.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[n]=255&r,n+1},t.prototype.writeInt16LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8):k(this,r,n,!0),n+2},t.prototype.writeInt16BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,2,32767,-32768),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>8,this[n+1]=255&r):k(this,r,n,!1),n+2},t.prototype.writeInt32LE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),t.TYPED_ARRAY_SUPPORT?(this[n]=255&r,this[n+1]=r>>>8,this[n+2]=r>>>16,this[n+3]=r>>>24):Y(this,r,n,!0),n+4},t.prototype.writeInt32BE=function(r,n,e){return r=+r,n=0|n,e||D(this,r,n,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),t.TYPED_ARRAY_SUPPORT?(this[n]=r>>>24,this[n+1]=r>>>16,this[n+2]=r>>>8,this[n+3]=255&r):Y(this,r,n,!1),n+4},t.prototype.writeFloatLE=function(t,r,n){return M(this,t,r,!0,n)},t.prototype.writeFloatBE=function(t,r,n){return M(this,t,r,!1,n)},t.prototype.writeDoubleLE=function(t,r,n){return z(this,t,r,!0,n)},t.prototype.writeDoubleBE=function(t,r,n){return z(this,t,r,!1,n)},t.prototype.copy=function(r,n,e,i){if(e||(e=0),i||0===i||(i=this.length),n>=r.length&&(n=r.length),n||(n=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),r.length-n=0;o--)r[o+n]=this[o+e];else if(s<1e3||!t.TYPED_ARRAY_SUPPORT)for(o=0;o=this.length)throw new RangeError("start out of bounds");if(n<0||n>this.length)throw new RangeError("end out of bounds");var e;if("number"==typeof t)for(e=r;e0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;a="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,h=new o(3*t.length/4-a),s=a>0?t.length-4:t.length;var c=0;for(e=0,i=0;e>16),n((65280&u)>>8),n(255&u);return 2===a?(u=r(t.charAt(e))<<2|r(t.charAt(e+1))>>4,n(255&u)):1===a&&(u=r(t.charAt(e))<<10|r(t.charAt(e+1))<<4|r(t.charAt(e+2))>>2,n(u>>8&255),n(255&u)),h}function i(t){function r(t){return e.charAt(t)}function n(t){return r(t>>18&63)+r(t>>12&63)+r(t>>6&63)+r(63&t)}var i,o,s,u=t.length%3,a="";for(i=0,s=t.length-u;i>2),a+=r(o<<4&63),a+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],a+=r(o>>10),a+=r(o>>4&63),a+=r(o<<2&63),a+="="}return a}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),u="/".charCodeAt(0),a="0".charCodeAt(0),h="a".charCodeAt(0),f="A".charCodeAt(0),c="-".charCodeAt(0),l="_".charCodeAt(0);t.toByteArray=n,t.fromByteArray=i}(r)},function(t,r){r.read=function(t,r,n,e,i){var o,s,u=8*i-e-1,a=(1<>1,f=-7,c=n?i-1:0,l=n?-1:1,p=t[r+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[r+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=e;f>0;s=256*s+t[r+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s+=Math.pow(2,e),o-=h}return(p?-1:1)*s*Math.pow(2,o-e)},r.write=function(t,r,n,e,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=e?0:o-1,d=e?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,s=f):(s=Math.floor(Math.log(r)/Math.LN2),r*(a=Math.pow(2,-s))<1&&(s--,a*=2),r+=s+c>=1?l/a:l*Math.pow(2,1-c),r*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(r*a-1)*Math.pow(2,i),s+=c):(u=r*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[n+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[n+p]=255&s,p+=d,s/=256,h-=8);t[n+p-d]|=128*g}},function(t,r){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,r,n){(function(r,e){!function(){var i=("undefined"==typeof window?r:window)||{};_crypto=i.crypto||i.msCrypto||n(8),t.exports=function(t){if(_crypto.getRandomValues){var r=new e(t);return _crypto.getRandomValues(r),r}if(_crypto.randomBytes)return _crypto.randomBytes(t);throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}}()}).call(r,function(){return this}(),n(3).Buffer)},function(t,r){},function(t,r,n){(function(r){function e(t){return function(){var n=[],e={update:function(t,e){return r.isBuffer(t)||(t=new r(t,e)),n.push(t),this},digest:function(e){var i=r.concat(n),o=t(i);return n=null,e?o.toString(e):o}};return e}}var i=n(10),o=e(n(19)),s=e(n(21));t.exports=function(t){return"md5"===t?new o:"rmd160"===t?new s:i(t)}}).call(r,n(3).Buffer)},function(t,r,n){var r=t.exports=function(t){var n=r[t];if(!n)throw new Error(t+" is not supported (we accept pull requests)");return new n},e=n(3).Buffer,i=n(11)(e);r.sha1=n(12)(e,i),r.sha256=n(17)(e,i),r.sha512=n(18)(e,i)},function(t,r){t.exports=function(t){function r(r,n){this._block=new t(r),this._finalSize=n,this._blockSize=r,this._len=0,this._s=0}return r.prototype.init=function(){this._s=0,this._len=0},r.prototype.update=function(r,n){"string"==typeof r&&(n=n||"utf8",r=new t(r,n));for(var e=this._len+=r.length,i=this._s=this._s||0,o=0,s=this._block;i=8*this._finalSize&&(this._update(this._block),this._block.fill(0)),this._block.writeInt32BE(r,this._blockSize-4);var n=this._update(this._block)||this._hash();return t?n.toString(t):n},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},r}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){return d.length?d.pop().init():this instanceof n?(this._w=p,r.call(this,64,56),this._h=null,void this.init()):new n}function i(t,r,n,e){return t<20?r&n|~r&e:t<40?r^n^e:t<60?r&n|r&e|n&e:r^n^e}function o(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function s(t,r){return t+r|0}function u(t,r){return t<>>32-r}var a=0,h=4,f=8,c=12,l=16,p=new("undefined"==typeof Int32Array?Array:Int32Array)(80),d=[];return e(n,r),n.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,r.prototype.init.call(this),this},n.prototype._POOL=d,n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d;r=f=this._a,n=c=this._b,e=l=this._c,a=p=this._d,h=d=this._e;for(var g=this._w,y=0;y<80;y++){var _=g[y]=y<16?t.readInt32BE(4*y):u(g[y-3]^g[y-8]^g[y-14]^g[y-16],1),w=s(s(u(r,5),i(y,n,e,a)),s(s(h,_),o(y)));h=a,a=e,e=u(n,30),n=r,r=w}this._a=s(r,f),this._b=s(n,c),this._c=s(e,l),this._d=s(a,p),this._e=s(h,d)},n.prototype._hash=function(){d.length<100&&d.push(this);var r=new t(20);return r.writeInt32BE(0|this._a,a),r.writeInt32BE(0|this._b,h),r.writeInt32BE(0|this._c,f),r.writeInt32BE(0|this._d,c),r.writeInt32BE(0|this._e,l),r},n}},function(t,r,n){(function(t,e){function i(t,n){var e={seen:[],stylize:s};return arguments.length>=3&&(e.depth=arguments[2]),arguments.length>=4&&(e.colors=arguments[3]),g(n)?e.showHidden=n:n&&r._extend(e,n),b(e.showHidden)&&(e.showHidden=!1),b(e.depth)&&(e.depth=2),b(e.colors)&&(e.colors=!1),b(e.customInspect)&&(e.customInspect=!0),e.colors&&(e.stylize=o),a(e,t,e.depth)}function o(t,r){var n=i.styles[r];return n?"["+i.colors[n][0]+"m"+t+"["+i.colors[n][1]+"m":t}function s(t,r){return t}function u(t){var r={};return t.forEach(function(t,n){r[t]=!0}),r}function a(t,n,e){if(t.customInspect&&n&&S(n.inspect)&&n.inspect!==r.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(e,t);return v(i)||(i=a(t,i,e)),i}var o=h(t,n);if(o)return o;var s=Object.keys(n),g=u(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(n)),I(n)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return f(n);if(0===s.length){if(S(n)){var y=n.name?": "+n.name:"";return t.stylize("[Function"+y+"]","special")}if(m(n))return t.stylize(RegExp.prototype.toString.call(n),"regexp");if(A(n))return t.stylize(Date.prototype.toString.call(n),"date");if(I(n))return f(n)}var _="",w=!1,E=["{","}"];if(d(n)&&(w=!0,E=["[","]"]),S(n)){var b=n.name?": "+n.name:"";_=" [Function"+b+"]"}if(m(n)&&(_=" "+RegExp.prototype.toString.call(n)),A(n)&&(_=" "+Date.prototype.toUTCString.call(n)),I(n)&&(_=" "+f(n)),0===s.length&&(!w||0==n.length))return E[0]+_+E[1];if(e<0)return m(n)?t.stylize(RegExp.prototype.toString.call(n),"regexp"):t.stylize("[Object]","special");t.seen.push(n);var B;return B=w?c(t,n,e,g,s):s.map(function(r){return l(t,n,e,g,r,w)}),t.seen.pop(),p(B,_,E)}function h(t,r){if(b(r))return t.stylize("undefined","undefined");if(v(r)){var n="'"+JSON.stringify(r).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return w(r)?t.stylize(""+r,"number"):g(r)?t.stylize(""+r,"boolean"):y(r)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,r,n,e,i){for(var o=[],s=0,u=r.length;s-1&&(u=o?u.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+u.split("\n").map(function(t){return" "+t}).join("\n"))):u=t.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return u;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function p(t,r,n){var e=0,i=t.reduce(function(t,r){return e++,r.indexOf("\n")>=0&&e++,t+r.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===r?"":r+"\n ")+" "+t.join(",\n ")+" "+n[1]:n[0]+r+" "+t.join(", ")+" "+n[1]}function d(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function y(t){return null===t}function _(t){return null==t}function w(t){return"number"==typeof t}function v(t){return"string"==typeof t}function E(t){return"symbol"==typeof t}function b(t){return void 0===t}function m(t){return B(t)&&"[object RegExp]"===U(t)}function B(t){return"object"==typeof t&&null!==t}function A(t){return B(t)&&"[object Date]"===U(t)}function I(t){return B(t)&&("[object Error]"===U(t)||t instanceof Error)}function S(t){return"function"==typeof t}function R(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function U(t){return Object.prototype.toString.call(t)}function P(t){return t<10?"0"+t.toString(10):t.toString(10)}function T(){var t=new Date,r=[P(t.getHours()),P(t.getMinutes()),P(t.getSeconds())].join(":");return[t.getDate(),k[t.getMonth()],r].join(" ")}function x(t,r){return Object.prototype.hasOwnProperty.call(t,r)}var L=/%[sdj%]/g;r.format=function(t){if(!v(t)){for(var r=[],n=0;n=o)return t;switch(t){case"%s":return String(e[n++]);case"%d":return Number(e[n++]);case"%j":try{return JSON.stringify(e[n++])}catch(r){return"[Circular]"}default:return t}}),u=e[n];n1)for(var n=1;n>>r|t<<32-r}function o(t,r){return t>>>r}function s(t,r,n){return t&r^~t&n}function u(t,r,n){return t&r^t&n^r&n}function a(t){return i(t,2)^i(t,13)^i(t,22)}function h(t){return i(t,6)^i(t,11)^i(t,25)}function f(t){return i(t,7)^i(t,18)^o(t,3)}function c(t){return i(t,17)^i(t,19)^o(t,10)}var l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=new Array(64);return e(n,r),n.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._len=this._s=0,this},n.prototype._update=function(t){var r,n,e,i,o,p,d,g,y,_,w=this._w;r=0|this._a,n=0|this._b,e=0|this._c,i=0|this._d,o=0|this._e,p=0|this._f,d=0|this._g,g=0|this._h;for(var v=0;v<64;v++){var E=w[v]=v<16?t.readInt32BE(4*v):c(w[v-2])+w[v-7]+f(w[v-15])+w[v-16];y=g+h(o)+s(o,p,d)+l[v]+E,_=a(r)+u(r,n,e),g=d,d=p,p=o,o=i+y,i=e,e=n,n=r,r=y+_}this._a=r+this._a|0,this._b=n+this._b|0,this._c=e+this._c|0,this._d=i+this._d|0,this._e=o+this._e|0,this._f=p+this._f|0,this._g=d+this._g|0,this._h=g+this._h|0},n.prototype._hash=function(){var r=new t(32);return r.writeInt32BE(this._a,0),r.writeInt32BE(this._b,4),r.writeInt32BE(this._c,8),r.writeInt32BE(this._d,12),r.writeInt32BE(this._e,16),r.writeInt32BE(this._f,20),r.writeInt32BE(this._g,24),r.writeInt32BE(this._h,28),r},n}},function(t,r,n){var e=n(13).inherits;t.exports=function(t,r){function n(){this.init(),this._w=a,r.call(this,128,112)}function i(t,r,n){return t>>>n|r<<32-n}function o(t,r,n){return t&r^~t&n}function s(t,r,n){return t&r^t&n^r&n}var u=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);return e(n,r),n.prototype.init=function(){return this._a=1779033703,this._b=-1150833019,this._c=1013904242,this._d=-1521486534,this._e=1359893119,this._f=-1694144372,this._g=528734635,this._h=1541459225,this._al=-205731576,this._bl=-2067093701,this._cl=-23791573,this._dl=1595750129,this._el=-1377402159,this._fl=725511199,this._gl=-79577749,this._hl=327033209,this._len=this._s=0,this},n.prototype._update=function(t){var r,n,e,a,h,f,c,l,p,d,g,y,_,w,v,E,b=this._w;r=0|this._a,n=0|this._b,e=0|this._c,a=0|this._d,h=0|this._e,f=0|this._f,c=0|this._g,l=0|this._h,p=0|this._al,d=0|this._bl,g=0|this._cl,y=0|this._dl,_=0|this._el,w=0|this._fl,v=0|this._gl,E=0|this._hl;for(var m=0;m<80;m++){var B,A,I=2*m;if(m<16)B=b[I]=t.readInt32BE(4*I),A=b[I+1]=t.readInt32BE(4*I+4);else{var S=b[I-30],R=b[I-30+1],U=i(S,R,1)^i(S,R,8)^S>>>7,P=i(R,S,1)^i(R,S,8)^i(R,S,7);S=b[I-4],R=b[I-4+1];var T=i(S,R,19)^i(R,S,29)^S>>>6,x=i(R,S,19)^i(S,R,29)^i(R,S,6),L=b[I-14],O=b[I-14+1],D=b[I-32],k=b[I-32+1];A=P+O,B=U+L+(A>>>0

>>0?1:0),A+=x,B=B+T+(A>>>0>>0?1:0),A+=k,B=B+D+(A>>>0>>0?1:0),b[I]=B,b[I+1]=A}var Y=s(r,n,e),C=s(p,d,g),M=i(r,p,28)^i(p,r,2)^i(p,r,7),z=i(p,r,28)^i(r,p,2)^i(r,p,7),j=i(h,_,14)^i(h,_,18)^i(_,h,9),N=i(_,h,14)^i(_,h,18)^i(h,_,9),F=u[I],H=u[I+1],J=o(h,f,c),V=o(_,w,v),q=E+N,G=l+j+(q>>>0>>0?1:0);q+=V,G=G+J+(q>>>0>>0?1:0),q+=H,G=G+F+(q>>>0>>0?1:0),q+=A,G=G+B+(q>>>0>>0?1:0);var Z=z+C,$=M+Y+(Z>>>0>>0?1:0);l=c,E=v,c=f,v=w,f=h,w=_,_=y+q|0,h=a+G+(_>>>0>>0?1:0)|0,a=e,y=g,e=n,g=d,n=r,d=p,p=q+Z|0,r=G+$+(p>>>0>>0?1:0)|0}this._al=this._al+p|0,this._bl=this._bl+d|0,this._cl=this._cl+g|0,this._dl=this._dl+y|0,this._el=this._el+_|0,this._fl=this._fl+w|0,this._gl=this._gl+v|0,this._hl=this._hl+E|0,this._a=this._a+r+(this._al>>>0

>>0?1:0)|0,this._b=this._b+n+(this._bl>>>0>>0?1:0)|0,this._c=this._c+e+(this._cl>>>0>>0?1:0)|0,this._d=this._d+a+(this._dl>>>0>>0?1:0)|0,this._e=this._e+h+(this._el>>>0<_>>>0?1:0)|0,this._f=this._f+f+(this._fl>>>0>>0?1:0)|0,this._g=this._g+c+(this._gl>>>0>>0?1:0)|0,this._h=this._h+l+(this._hl>>>0>>0?1:0)|0},n.prototype._hash=function(){function r(t,r,e){n.writeInt32BE(t,e),n.writeInt32BE(r,e+4)}var n=new t(64);return r(this._a,this._al,0),r(this._b,this._bl,8),r(this._c,this._cl,16),r(this._d,this._dl,24),r(this._e,this._el,32),r(this._f,this._fl,40),r(this._g,this._gl,48),r(this._h,this._hl,56),n},n}},function(t,r,n){function e(t,r){t[r>>5]|=128<>>9<<4)+14]=r;for(var n=1732584193,e=-271733879,i=-1732584194,f=271733878,c=0;c>16)+(r>>16)+(n>>16);return e<<16|65535&n}function f(t,r){return t<>>32-r}var c=n(20);t.exports=function(t){return c.hash(t,e,16)}},function(t,r,n){(function(r){function n(t,n){if(t.length%o!==0){var e=t.length+(o-t.length%o);t=r.concat([t,s],e)}for(var i=[],u=n?t.readInt32BE:t.readInt32LE,a=0;a>>32-r}function a(t){var n=[1732584193,4023233417,2562383102,271733878,3285377520];"string"==typeof t&&(t=new r(t,"utf8"));var e=g(t),i=8*t.length,o=8*t.length;e[i>>>5]|=128<<24-i%32,e[(i+64>>>9<<4)+14]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8);for(var s=0;s>>24)|4278255360&(u<<24|u>>>8)}var a=y(n);return new r(a)}t.exports=a;var h=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],f=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],c=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],l=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],p=[0,1518500249,1859775393,2400959708,2840853838],d=[1352829926,1548603684,1836072691,2053994217,0],g=function(t){for(var r=[],n=0,e=0;n>>5]|=t[n]<<24-e%32;return r},y=function(t){for(var r=[],n=0;n<32*t.length;n+=8)r.push(t[n>>>5]>>>24-n%32&255);return r},_=function(t,r,a){for(var g=0;g<16;g++){var y=a+g,_=r[y];r[y]=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8)}var w,v,E,b,m,B,A,I,S,R;B=w=t[0],A=v=t[1],I=E=t[2],S=b=t[3],R=m=t[4];for(var U,g=0;g<80;g+=1)U=w+r[a+h[g]]|0,U+=g<16?n(v,E,b)+p[0]:g<32?e(v,E,b)+p[1]:g<48?i(v,E,b)+p[2]:g<64?o(v,E,b)+p[3]:s(v,E,b)+p[4],U=0|U,U=u(U,c[g]),U=U+m|0,w=m,m=b,b=u(E,10),E=v,v=U,U=B+r[a+f[g]]|0,U+=g<16?s(A,I,S)+d[0]:g<32?o(A,I,S)+d[1]:g<48?i(A,I,S)+d[2]:g<64?e(A,I,S)+d[3]:n(A,I,S)+d[4],U=0|U,U=u(U,l[g]),U=U+R|0,B=R,R=S,S=u(I,10),I=A,A=U;U=t[1]+E+S|0,t[1]=t[2]+b+R|0,t[2]=t[3]+m+B|0,t[3]=t[4]+w+A|0,t[4]=t[0]+v+I|0,t[0]=U}}).call(r,n(3).Buffer)},function(t,r,n){(function(r){function e(t,n){if(!(this instanceof e))return new e(t,n);this._opad=a,this._alg=t;var s="sha512"===t?128:64;n=this._key=r.isBuffer(n)?n:new r(n),n.length>s?n=i(t).update(n).digest():n.length(Math.pow(2,32)-1)*u))throw new TypeError("keylen exceeds maximum length");d.copy(h,0,0,u);for(var g=1;g0){throw new Error("Invalid string. Length must be a multiple of 4")}placeHolders=b64[len-2]==="="?2:b64[len-1]==="="?1:0;arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],3:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(this,val,byteOffset,encoding)}if(typeof val==="number"){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,val,byteOffset)}return arrayIndexOf(this,[val],byteOffset,encoding)}throw new TypeError("val must be string, number or Buffer")};Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"binary":return binaryWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":2,ieee754:11,isarray:13}],4:[function(require,module,exports){(function(Buffer){var createHash=require("sha.js");var md5=toConstructor(require("./md5"));var rmd160=toConstructor(require("ripemd160"));function toConstructor(fn){return function(){var buffers=[];var m={update:function(data,enc){if(!Buffer.isBuffer(data))data=new Buffer(data,enc);buffers.push(data);return this},digest:function(enc){var buf=Buffer.concat(buffers);var r=fn(buf);buffers=null;return enc?r.toString(enc):r}};return m}}module.exports=function(alg){if("md5"===alg)return new md5;if("rmd160"===alg)return new rmd160;return createHash(alg)}}).call(this,require("buffer").Buffer)},{"./md5":8,buffer:3,ripemd160:16,"sha.js":18}],5:[function(require,module,exports){(function(Buffer){var createHash=require("./create-hash");var zeroBuffer=new Buffer(128);zeroBuffer.fill(0);module.exports=Hmac;function Hmac(alg,key){if(!(this instanceof Hmac))return new Hmac(alg,key);this._opad=opad;this._alg=alg;var blocksize=alg==="sha512"?128:64;key=this._key=!Buffer.isBuffer(key)?new Buffer(key):key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.length>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":6}],9:[function(require,module,exports){var pbkdf2Export=require("pbkdf2-compat/pbkdf2");module.exports=function(crypto,exports){exports=exports||{};var exported=pbkdf2Export(crypto);exports.pbkdf2=exported.pbkdf2;exports.pbkdf2Sync=exported.pbkdf2Sync;return exports}},{"pbkdf2-compat/pbkdf2":14}],10:[function(require,module,exports){(function(global,Buffer){(function(){var g=("undefined"===typeof window?global:window)||{};_crypto=g.crypto||g.msCrypto||require("crypto");module.exports=function(size){if(_crypto.getRandomValues){var bytes=new Buffer(size);_crypto.getRandomValues(bytes);return bytes}else if(_crypto.randomBytes){return _crypto.randomBytes(size)}else throw new Error("secure random number generation not supported by this browser\n"+"use chrome, FireFox or Internet Explorer 11")}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{buffer:3,crypto:1}],11:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],12:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],13:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],14:[function(require,module,exports){(function(Buffer){module.exports=function(crypto){function pbkdf2(password,salt,iterations,keylen,digest,callback){if("function"===typeof digest){callback=digest;digest=undefined}if("function"!==typeof callback)throw new Error("No callback provided to pbkdf2");setTimeout(function(){var result;try{result=pbkdf2Sync(password,salt,iterations,keylen,digest)}catch(e){return callback(e)}callback(undefined,result)})}function pbkdf2Sync(password,salt,iterations,keylen,digest){if("number"!==typeof iterations)throw new TypeError("Iterations not a number");if(iterations<0)throw new TypeError("Bad iterations");if("number"!==typeof keylen)throw new TypeError("Key length not a number");if(keylen<0)throw new TypeError("Bad key length");digest=digest||"sha1";if(!Buffer.isBuffer(password))password=new Buffer(password);if(!Buffer.isBuffer(salt))salt=new Buffer(salt);var hLen,l=1,r,T;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=crypto.createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen;if(keylen>(Math.pow(2,32)-1)*hLen)throw new TypeError("keylen exceeds maximum length")}U.copy(T,0,0,hLen);for(var j=1;j1){for(var i=1;i>>5]|=bytes[i]<<24-b%32}return words};var wordsToBytes=function(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes};var processBlock=function(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(var i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t};function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message=="string")message=new Buffer(message,"utf8");var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}}).call(this,require("buffer").Buffer)},{buffer:3}],17:[function(require,module,exports){module.exports=function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.init=function(){this._s=0;this._len=0};Hash.prototype.update=function(data,enc){if("string"===typeof data){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};return Hash}},{}],18:[function(require,module,exports){var exports=module.exports=function(alg){var Alg=exports[alg];if(!Alg)throw new Error(alg+" is not supported (we accept pull requests)");return new Alg};var Buffer=require("buffer").Buffer;var Hash=require("./hash")(Buffer);exports.sha1=require("./sha1")(Buffer,Hash);exports.sha256=require("./sha256")(Buffer,Hash);exports.sha512=require("./sha512")(Buffer,Hash)},{"./hash":17,"./sha1":19,"./sha256":20,"./sha512":21,buffer:3}],19:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var A=0|0;var B=4|0;var C=8|0;var D=12|0;var E=16|0;var W=new(typeof Int32Array==="undefined"?Array:Int32Array)(80);var POOL=[];function Sha1(){if(POOL.length)return POOL.pop().init();if(!(this instanceof Sha1))return new Sha1;this._w=W;Hash.call(this,16*4,14*4);this._h=null;this.init()}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;Hash.prototype.init.call(this);return this};Sha1.prototype._POOL=POOL;Sha1.prototype._update=function(X){var a,b,c,d,e,_a,_b,_c,_d,_e;a=_a=this._a;b=_b=this._b;c=_c=this._c;d=_d=this._d;e=_e=this._e;var w=this._w;for(var j=0;j<80;j++){var W=w[j]=j<16?X.readInt32BE(j*4):rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=add(add(rol(a,5),sha1_ft(j,b,c,d)),add(add(e,W),sha1_kt(j)));e=d;d=c;c=rol(b,30);b=a;a=t}this._a=add(a,_a);this._b=add(b,_b);this._c=add(c,_c);this._d=add(d,_d);this._e=add(e,_e)};Sha1.prototype._hash=function(){if(POOL.length<100)POOL.push(this);var H=new Buffer(20);H.writeInt32BE(this._a|0,A);H.writeInt32BE(this._b|0,B);H.writeInt32BE(this._c|0,C);H.writeInt32BE(this._d|0,D);H.writeInt32BE(this._e|0,E);return H};function sha1_ft(t,b,c,d){if(t<20)return b&c|~b&d;if(t<40)return b^c^d;if(t<60)return b&c|b&d|c&d;return b^c^d}function sha1_kt(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function add(x,y){return x+y|0}function rol(num,cnt){return num<>>32-cnt}return Sha1}},{util:23}],20:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,16*4,14*4)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._len=this._s=0;return this};function S(X,n){return X>>>n|X<<32-n}function R(X,n){return X>>>n}function Ch(x,y,z){return x&y^~x&z}function Maj(x,y,z){return x&y^x&z^y&z}function Sigma0256(x){return S(x,2)^S(x,13)^S(x,22)}function Sigma1256(x){return S(x,6)^S(x,11)^S(x,25)}function Gamma0256(x){return S(x,7)^S(x,18)^R(x,3)}function Gamma1256(x){return S(x,17)^S(x,19)^R(x,10)}Sha256.prototype._update=function(M){var W=this._w;var a,b,c,d,e,f,g,h;var T1,T2;a=this._a|0;b=this._b|0;c=this._c|0;d=this._d|0;e=this._e|0;f=this._f|0;g=this._g|0;h=this._h|0;for(var j=0;j<64;j++){var w=W[j]=j<16?M.readInt32BE(j*4):Gamma1256(W[j-2])+W[j-7]+Gamma0256(W[j-15])+W[j-16];T1=h+Sigma1256(e)+Ch(e,f,g)+K[j]+w;T2=Sigma0256(a)+Maj(a,b,c);h=g;g=f;f=e;e=d+T1;d=c;c=b;b=a;a=T1+T2}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};return Sha256}},{util:23}],21:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._al=4089235720|0;this._bl=2227873595|0;this._cl=4271175723|0;this._dl=1595750129|0;this._el=2917565137|0;this._fl=725511199|0;this._gl=4215389547|0;this._hl=327033209|0;this._len=this._s=0;return this};function S(X,Xl,n){return X>>>n|Xl<<32-n}function Ch(x,y,z){return x&y^~x&z}function Maj(x,y,z){return x&y^x&z^y&z}Sha512.prototype._update=function(M){var W=this._w;var a,b,c,d,e,f,g,h;var al,bl,cl,dl,el,fl,gl,hl;a=this._a|0;b=this._b|0;c=this._c|0;d=this._d|0;e=this._e|0;f=this._f|0;g=this._g|0;h=this._h|0;al=this._al|0;bl=this._bl|0;cl=this._cl|0;dl=this._dl|0;el=this._el|0;fl=this._fl|0;gl=this._gl|0;hl=this._hl|0;for(var i=0;i<80;i++){var j=i*2;var Wi,Wil;if(i<16){Wi=W[j]=M.readInt32BE(j*4);Wil=W[j+1]=M.readInt32BE(j*4+4)}else{var x=W[j-15*2];var xl=W[j-15*2+1];var gamma0=S(x,xl,1)^S(x,xl,8)^x>>>7;var gamma0l=S(xl,x,1)^S(xl,x,8)^S(xl,x,7);x=W[j-2*2];xl=W[j-2*2+1];var gamma1=S(x,xl,19)^S(xl,x,29)^x>>>6;var gamma1l=S(xl,x,19)^S(x,xl,29)^S(xl,x,6);var Wi7=W[j-7*2];var Wi7l=W[j-7*2+1];var Wi16=W[j-16*2];var Wi16l=W[j-16*2+1];Wil=gamma0l+Wi7l;Wi=gamma0+Wi7+(Wil>>>0>>0?1:0);Wil=Wil+gamma1l;Wi=Wi+gamma1+(Wil>>>0>>0?1:0);Wil=Wil+Wi16l;Wi=Wi+Wi16+(Wil>>>0>>0?1:0);W[j]=Wi;W[j+1]=Wil}var maj=Maj(a,b,c);var majl=Maj(al,bl,cl);var sigma0h=S(a,al,28)^S(al,a,2)^S(al,a,7);var sigma0l=S(al,a,28)^S(a,al,2)^S(a,al,7);var sigma1h=S(e,el,14)^S(e,el,18)^S(el,e,9);var sigma1l=S(el,e,14)^S(el,e,18)^S(e,el,9);var Ki=K[j];var Kil=K[j+1];var ch=Ch(e,f,g);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l;var t1=h+sigma1h+(t1l>>>0>>0?1:0);t1l=t1l+chl;t1=t1+ch+(t1l>>>0>>0?1:0);t1l=t1l+Kil;t1=t1+Ki+(t1l>>>0>>0?1:0);t1l=t1l+Wil;t1=t1+Wi+(t1l>>>0>>0?1:0);var t2l=sigma0l+majl;var t2=sigma0h+maj+(t2l>>>0>>0?1:0);h=g;hl=gl;g=f;gl=fl;f=e;fl=el;el=dl+t1l|0;e=d+t1+(el>>>0

>>0?1:0)|0;d=c;dl=cl;c=b;cl=bl;b=a;bl=al;al=t1l+t2l|0;a=t1+t2+(al>>>0>>0?1:0)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._a=this._a+a+(this._al>>>0>>0?1:0)|0;this._b=this._b+b+(this._bl>>>0>>0?1:0)|0;this._c=this._c+c+(this._cl>>>0>>0?1:0)|0;this._d=this._d+d+(this._dl>>>0
>>0?1:0)|0;this._e=this._e+e+(this._el>>>0>>0?1:0)|0;this._f=this._f+f+(this._fl>>>0>>0?1:0)|0;this._g=this._g+g+(this._gl>>>0>>0?1:0)|0;this._h=this._h+h+(this._hl>>>0>>0?1:0)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._a,this._al,0);writeInt64BE(this._b,this._bl,8);writeInt64BE(this._c,this._cl,16);writeInt64BE(this._d,this._dl,24);writeInt64BE(this._e,this._el,32);writeInt64BE(this._f,this._fl,40);writeInt64BE(this._g,this._gl,48);writeInt64BE(this._h,this._hl,56);return H};return Sha512}},{util:23}],22:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],23:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){ +return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":22,_process:15,inherits:12}],24:[function(require,module,exports){"use strict";var _crypto=require("crypto");var _crypto2=_interopRequireDefault(_crypto);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}module.exports={generatePassword:_generatePassword,encryptLogin:_encryptLogin,_deriveHash:_deriveHash,_prettyPrint:_prettyPrint,_getTemplate:_getTemplate,_getCharType:_getCharType,_getPasswordChar:_getPasswordChar,_string2charCodes:_string2charCodes};function _generatePassword(login,masterPassword,site,options){return new Promise(function(resolve,reject){if(!login||!masterPassword||!site){reject("generatePassword invalid parameter")}_encryptLogin(login,masterPassword).then(function(hash){var derivedHash=_deriveHash(hash,site,options);var template=_getTemplate(options.password.settings);resolve(_prettyPrint(derivedHash,template))})})}function _encryptLogin(login,masterPassword){return new Promise(function(resolve,reject){if(!login||!masterPassword){reject("encryptLogin parameter could not be empty")}var iterations=8192;var keylen=32;_crypto2.default.pbkdf2(masterPassword,login,iterations,keylen,"sha256",function(error,key){if(error){reject("error in pbkdf2")}else{resolve(key.toString("hex"))}})})}function _deriveHash(hash,site){var _ref=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];var _ref$password=_ref.password;var password=_ref$password===undefined?{length:12}:_ref$password;var _ref$counter=_ref.counter;var counter=_ref$counter===undefined?1:_ref$counter;var salt=site+counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",hash).update(salt).digest("hex");return derivedHash.substring(0,password.length)}function _getTemplate(){var passwordTypes=arguments.length<=0||arguments[0]===undefined?["strong"]:arguments[0];var passwordTypesInfo={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return passwordTypes.map(function(passwordType){return passwordTypesInfo[passwordType]}).sort(function(passwordType1,passwordType2){return passwordType1.order>passwordType2.order}).map(function(passwordType){return passwordType.value}).join("")}function _prettyPrint(hash,template){var password="";_string2charCodes(hash).forEach(function(charCode,index){var charType=_getCharType(template,index);password+=_getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i dist/lesspass.min.js", "prepublish": "npm test && npm run build" }, "keywords": [ @@ -29,13 +29,14 @@ "devDependencies": { "ava": "^0.15.2", "babel-core": "^6.10.4", - "babel-loader": "^6.2.4", "babel-preset-es2015": "^6.9.0", + "babelify": "^7.3.0", + "browserify": "^13.0.1", "karma": "^1.1.0", "karma-ava": "0.0.1", "karma-chrome-launcher": "^1.0.1", "karma-firefox-launcher": "^1.0.0", - "webpack": "^1.13.1", + "uglify-js": "^2.6.4", "xo": "^0.16.0" }, "babel": { @@ -43,6 +44,11 @@ "es2015" ] }, + "browserify": { + "transform": [ + "babelify" + ] + }, "xo": { "esnext": true, "space": true, diff --git a/src/lesspass.js b/src/lesspass.js index 8b8f992..23aa019 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -1,114 +1,103 @@ import crypto from 'crypto'; -(function () { - const lesspass = { - generatePassword: _generatePassword, - encryptLogin: _encryptLogin, - _deriveHash, - _prettyPrint, - _getTemplate, - _getCharType, - _getPasswordChar, - _string2charCodes - }; +module.exports = { + generatePassword: _generatePassword, + encryptLogin: _encryptLogin, + _deriveHash, + _prettyPrint, + _getTemplate, + _getCharType, + _getPasswordChar, + _string2charCodes +}; - if (typeof window === 'undefined') { - if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { - module.exports = lesspass; - } else { - console.error('cannot load properly lesspass'); +function _generatePassword(login, masterPassword, site, options) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword || !site) { + reject('generatePassword invalid parameter'); } - } else { - window.lesspass = lesspass; - } - function _generatePassword(login, masterPassword, site, options) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword || !site) { - reject('generatePassword invalid parameter'); - } - - _encryptLogin(login, masterPassword).then(hash => { - const derivedHash = _deriveHash(hash, site, options); - const template = _getTemplate(options.password.settings); - resolve(_prettyPrint(derivedHash, template)); - }); + _encryptLogin(login, masterPassword).then(hash => { + const derivedHash = _deriveHash(hash, site, options); + const template = _getTemplate(options.password.settings); + resolve(_prettyPrint(derivedHash, template)); }); - } + }); +} - function _encryptLogin(login, masterPassword) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword) { - reject('encryptLogin parameter could not be empty'); +function _encryptLogin(login, masterPassword) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword) { + reject('encryptLogin parameter could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); } - const iterations = 8192; - const keylen = 32; - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); }); - } + }); +} - function _deriveHash(hash, site, {password = {length: 12}, counter = 1} = {}) { - const salt = site + counter.toString(); - const derivedHash = crypto.createHmac('sha256', hash).update(salt).digest('hex'); - return derivedHash.substring(0, password.length); - } +function _deriveHash(hash, site, {password = {length: 12}, counter = 1} = {}) { + const salt = site + counter.toString(); + const derivedHash = crypto.createHmac('sha256', hash).update(salt).digest('hex'); + return derivedHash.substring(0, password.length); +} - function _getTemplate(passwordTypes = ['strong']) { - const passwordTypesInfo = { - lowercase: {value: 'vc', order: 1}, - uppercase: {value: 'VC', order: 2}, - numbers: {value: 'n', order: 3}, - symbols: {value: 's', order: 4}, - strong: {value: 'Cvcvns', order: 5} - }; - return passwordTypes - .map(passwordType => passwordTypesInfo[passwordType]) - .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) - .map(passwordType => passwordType.value) - .join(''); - } +function _getTemplate(passwordTypes = ['strong']) { + const passwordTypesInfo = { + lowercase: {value: 'vc', order: 1}, + uppercase: {value: 'VC', order: 2}, + numbers: {value: 'n', order: 3}, + symbols: {value: 's', order: 4}, + strong: {value: 'Cvcvns', order: 5} + }; + return passwordTypes + .map(passwordType => passwordTypesInfo[passwordType]) + .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) + .map(passwordType => passwordType.value) + .join(''); +} - function _prettyPrint(hash, template) { - let password = ''; +function _prettyPrint(hash, template) { + let password = ''; - _string2charCodes(hash).forEach((charCode, index) => { - const charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; - } + _string2charCodes(hash).forEach((charCode, index) => { + const charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; +} - function _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; +function _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); } + return charCodes; +} - function _getCharType(template, index) { - return template[index % template.length]; - } +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} - function _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; - } -})(); diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index 7376897..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,28 +0,0 @@ -const path = require('path'); -const webpack = require('webpack'); - -module.exports = { - entry: [ - './src/lesspass' - ], - output: { - path: __dirname, - filename: 'dist/lesspass.min.js' - }, - module: { - loaders: [ - { - test: /\.js$/, - include: path.join(__dirname, 'src'), - loader: 'babel-loader', - query: { - presets: ['es2015'] - } - } - ] - }, - plugins: [ - new webpack.NoErrorsPlugin(), - new webpack.optimize.UglifyJsPlugin({output: {comments: false}}) - ] -}; From 71d6d59e8324a4b456ffad805bfeedf9b9eb985b Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 3 Jul 2016 09:28:31 +0200 Subject: [PATCH 025/124] 3.1.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 39d18f7..ff2195a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.1.1", + "version": "3.1.2", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "src/lesspass.js", From 19fda275172b733086f7585f0860a48375789e32 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 4 Jul 2016 10:00:02 +0200 Subject: [PATCH 026/124] fix node module not babelified --- package.json | 13 +++++++++---- readme.md | 40 +++++++++++++++++++++------------------- tests/node.js | 16 ++++++++++++++++ 3 files changed, 46 insertions(+), 23 deletions(-) create mode 100644 tests/node.js diff --git a/package.json b/package.json index ff2195a..8a31f67 100644 --- a/package.json +++ b/package.json @@ -3,10 +3,12 @@ "version": "3.1.2", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", - "main": "src/lesspass.js", + "main": "lib/lesspass.js", "scripts": { "test": "ava --require babel-core/register && xo", - "build": "rm -rf dist && mkdir dist && browserify -s lesspass ./src/lesspass.js | uglifyjs > dist/lesspass.min.js", + "browserify": "browserify src/lesspass.js --standalone lesspass | uglifyjs > dist/lesspass.min.js", + "babelify": "babel src/lesspass.js -o lib/lesspass.js", + "build": "rm -rf dist lib && mkdir dist lib && npm run browserify && npm run babelify", "prepublish": "npm test && npm run build" }, "keywords": [ @@ -28,6 +30,7 @@ "homepage": "https://github.com/lesspass/core#readme", "devDependencies": { "ava": "^0.15.2", + "babel-cli": "^6.10.1", "babel-core": "^6.10.4", "babel-preset-es2015": "^6.9.0", "babelify": "^7.3.0", @@ -59,13 +62,15 @@ "es6" ], "ignores": [ - "lib/**" + "lib/**", + "tests/node.js" ] }, "ava": { "files": [ "tests/*.js", - "!tests/karma.conf.js" + "!tests/karma.conf.js", + "!tests/node.js" ], "source": [ "src/*.js" diff --git a/readme.md b/readme.md index fc16e11..794cba7 100644 --- a/readme.md +++ b/readme.md @@ -22,16 +22,18 @@ core library for LessPass password manager in node.js used to generate unique pa var masterPassword = 'password'; var site = 'lesspass.com'; var options = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } }; lesspass.generatePassword(login, masterPassword, site, options).then(function (generatedPassword) { - console.log(generatedPassword) //azYS7,olOL2] + console.log(generatedPassword); //azYS7,olOL2] }); + + ### Browser @@ -42,19 +44,19 @@ core library for LessPass password manager in node.js used to generate unique pa diff --git a/tests/node.js b/tests/node.js new file mode 100644 index 0000000..f1bba6e --- /dev/null +++ b/tests/node.js @@ -0,0 +1,16 @@ +var lesspass = require('../lib/lesspass'); + +var login = 'contact@lesspass.com'; +var masterPassword = 'password'; +var site = 'lesspass.com'; +var options = { + counter: 1, + password: { + length: 12, + settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] + } +}; +lesspass.generatePassword(login, masterPassword, site, options).then(function (generatedPassword) { + console.log(generatedPassword); //azYS7,olOL2] +}); + From 8a0fe6e71664807d2fe74c58d2ffc87569a593ae Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 4 Jul 2016 10:00:28 +0200 Subject: [PATCH 027/124] 3.1.3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8a31f67..9db0373 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.1.2", + "version": "3.1.3", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "lib/lesspass.js", From 4c3f49630270d20e0cc7c164de035ecf8c876883 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 4 Jul 2016 21:26:17 +0200 Subject: [PATCH 028/124] add render password method --- src/lesspass.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/lesspass.js b/src/lesspass.js index 23aa019..6ce3240 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -3,6 +3,7 @@ import crypto from 'crypto'; module.exports = { generatePassword: _generatePassword, encryptLogin: _encryptLogin, + renderPassword: _renderPassword, _deriveHash, _prettyPrint, _getTemplate, @@ -18,13 +19,17 @@ function _generatePassword(login, masterPassword, site, options) { } _encryptLogin(login, masterPassword).then(hash => { - const derivedHash = _deriveHash(hash, site, options); - const template = _getTemplate(options.password.settings); - resolve(_prettyPrint(derivedHash, template)); + resolve(_renderPassword(hash, site, options)); }); }); } +function _renderPassword(hash, site, options) { + const derivedHash = _deriveHash(hash, site, options); + const template = _getTemplate(options.password.settings); + return _prettyPrint(derivedHash, template); +} + function _encryptLogin(login, masterPassword) { return new Promise((resolve, reject) => { if (!login || !masterPassword) { From 3595bf9eafbdca4ea2f1ac6d4a7cb3acab495b5e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 4 Jul 2016 21:26:50 +0200 Subject: [PATCH 029/124] 3.2.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9db0373..726cdb1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.1.3", + "version": "3.2.0", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "lib/lesspass.js", From fb20c20d0bf13eb7c4601333c5300a1aa790695e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 4 Jul 2016 21:32:34 +0200 Subject: [PATCH 030/124] update frontend module --- dist/lesspass.min.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js index a8594e0..a484519 100644 --- a/dist/lesspass.min.js +++ b/dist/lesspass.min.js @@ -1,3 +1,3 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.lesspass=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0){throw new Error("Invalid string. Length must be a multiple of 4")}placeHolders=b64[len-2]==="="?2:b64[len-1]==="="?1:0;arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],3:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(this,val,byteOffset,encoding)}if(typeof val==="number"){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,val,byteOffset)}return arrayIndexOf(this,[val],byteOffset,encoding)}throw new TypeError("val must be string, number or Buffer")};Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"binary":return binaryWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":2,ieee754:11,isarray:13}],4:[function(require,module,exports){(function(Buffer){var createHash=require("sha.js");var md5=toConstructor(require("./md5"));var rmd160=toConstructor(require("ripemd160"));function toConstructor(fn){return function(){var buffers=[];var m={update:function(data,enc){if(!Buffer.isBuffer(data))data=new Buffer(data,enc);buffers.push(data);return this},digest:function(enc){var buf=Buffer.concat(buffers);var r=fn(buf);buffers=null;return enc?r.toString(enc):r}};return m}}module.exports=function(alg){if("md5"===alg)return new md5;if("rmd160"===alg)return new rmd160;return createHash(alg)}}).call(this,require("buffer").Buffer)},{"./md5":8,buffer:3,ripemd160:16,"sha.js":18}],5:[function(require,module,exports){(function(Buffer){var createHash=require("./create-hash");var zeroBuffer=new Buffer(128);zeroBuffer.fill(0);module.exports=Hmac;function Hmac(alg,key){if(!(this instanceof Hmac))return new Hmac(alg,key);this._opad=opad;this._alg=alg;var blocksize=alg==="sha512"?128:64;key=this._key=!Buffer.isBuffer(key)?new Buffer(key):key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.length>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":6}],9:[function(require,module,exports){var pbkdf2Export=require("pbkdf2-compat/pbkdf2");module.exports=function(crypto,exports){exports=exports||{};var exported=pbkdf2Export(crypto);exports.pbkdf2=exported.pbkdf2;exports.pbkdf2Sync=exported.pbkdf2Sync;return exports}},{"pbkdf2-compat/pbkdf2":14}],10:[function(require,module,exports){(function(global,Buffer){(function(){var g=("undefined"===typeof window?global:window)||{};_crypto=g.crypto||g.msCrypto||require("crypto");module.exports=function(size){if(_crypto.getRandomValues){var bytes=new Buffer(size);_crypto.getRandomValues(bytes);return bytes}else if(_crypto.randomBytes){return _crypto.randomBytes(size)}else throw new Error("secure random number generation not supported by this browser\n"+"use chrome, FireFox or Internet Explorer 11")}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{buffer:3,crypto:1}],11:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],12:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],13:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],14:[function(require,module,exports){(function(Buffer){module.exports=function(crypto){function pbkdf2(password,salt,iterations,keylen,digest,callback){if("function"===typeof digest){callback=digest;digest=undefined}if("function"!==typeof callback)throw new Error("No callback provided to pbkdf2");setTimeout(function(){var result;try{result=pbkdf2Sync(password,salt,iterations,keylen,digest)}catch(e){return callback(e)}callback(undefined,result)})}function pbkdf2Sync(password,salt,iterations,keylen,digest){if("number"!==typeof iterations)throw new TypeError("Iterations not a number");if(iterations<0)throw new TypeError("Bad iterations");if("number"!==typeof keylen)throw new TypeError("Key length not a number");if(keylen<0)throw new TypeError("Bad key length");digest=digest||"sha1";if(!Buffer.isBuffer(password))password=new Buffer(password);if(!Buffer.isBuffer(salt))salt=new Buffer(salt);var hLen,l=1,r,T;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=crypto.createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen;if(keylen>(Math.pow(2,32)-1)*hLen)throw new TypeError("keylen exceeds maximum length")}U.copy(T,0,0,hLen);for(var j=1;j1){for(var i=1;i>>5]|=bytes[i]<<24-b%32}return words};var wordsToBytes=function(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes};var processBlock=function(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(var i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t};function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message=="string")message=new Buffer(message,"utf8");var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}}).call(this,require("buffer").Buffer)},{buffer:3}],17:[function(require,module,exports){module.exports=function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.init=function(){this._s=0;this._len=0};Hash.prototype.update=function(data,enc){if("string"===typeof data){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};return Hash}},{}],18:[function(require,module,exports){var exports=module.exports=function(alg){var Alg=exports[alg];if(!Alg)throw new Error(alg+" is not supported (we accept pull requests)");return new Alg};var Buffer=require("buffer").Buffer;var Hash=require("./hash")(Buffer);exports.sha1=require("./sha1")(Buffer,Hash);exports.sha256=require("./sha256")(Buffer,Hash);exports.sha512=require("./sha512")(Buffer,Hash)},{"./hash":17,"./sha1":19,"./sha256":20,"./sha512":21,buffer:3}],19:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var A=0|0;var B=4|0;var C=8|0;var D=12|0;var E=16|0;var W=new(typeof Int32Array==="undefined"?Array:Int32Array)(80);var POOL=[];function Sha1(){if(POOL.length)return POOL.pop().init();if(!(this instanceof Sha1))return new Sha1;this._w=W;Hash.call(this,16*4,14*4);this._h=null;this.init()}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;Hash.prototype.init.call(this);return this};Sha1.prototype._POOL=POOL;Sha1.prototype._update=function(X){var a,b,c,d,e,_a,_b,_c,_d,_e;a=_a=this._a;b=_b=this._b;c=_c=this._c;d=_d=this._d;e=_e=this._e;var w=this._w;for(var j=0;j<80;j++){var W=w[j]=j<16?X.readInt32BE(j*4):rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=add(add(rol(a,5),sha1_ft(j,b,c,d)),add(add(e,W),sha1_kt(j)));e=d;d=c;c=rol(b,30);b=a;a=t}this._a=add(a,_a);this._b=add(b,_b);this._c=add(c,_c);this._d=add(d,_d);this._e=add(e,_e)};Sha1.prototype._hash=function(){if(POOL.length<100)POOL.push(this);var H=new Buffer(20);H.writeInt32BE(this._a|0,A);H.writeInt32BE(this._b|0,B);H.writeInt32BE(this._c|0,C);H.writeInt32BE(this._d|0,D);H.writeInt32BE(this._e|0,E);return H};function sha1_ft(t,b,c,d){if(t<20)return b&c|~b&d;if(t<40)return b^c^d;if(t<60)return b&c|b&d|c&d;return b^c^d}function sha1_kt(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function add(x,y){return x+y|0}function rol(num,cnt){return num<>>32-cnt}return Sha1}},{util:23}],20:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,16*4,14*4)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._len=this._s=0;return this};function S(X,n){return X>>>n|X<<32-n}function R(X,n){return X>>>n}function Ch(x,y,z){return x&y^~x&z}function Maj(x,y,z){return x&y^x&z^y&z}function Sigma0256(x){return S(x,2)^S(x,13)^S(x,22)}function Sigma1256(x){return S(x,6)^S(x,11)^S(x,25)}function Gamma0256(x){return S(x,7)^S(x,18)^R(x,3)}function Gamma1256(x){return S(x,17)^S(x,19)^R(x,10)}Sha256.prototype._update=function(M){var W=this._w;var a,b,c,d,e,f,g,h;var T1,T2;a=this._a|0;b=this._b|0;c=this._c|0;d=this._d|0;e=this._e|0;f=this._f|0;g=this._g|0;h=this._h|0;for(var j=0;j<64;j++){var w=W[j]=j<16?M.readInt32BE(j*4):Gamma1256(W[j-2])+W[j-7]+Gamma0256(W[j-15])+W[j-16];T1=h+Sigma1256(e)+Ch(e,f,g)+K[j]+w;T2=Sigma0256(a)+Maj(a,b,c);h=g;g=f;f=e;e=d+T1;d=c;c=b;b=a;a=T1+T2}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};return Sha256}},{util:23}],21:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._al=4089235720|0;this._bl=2227873595|0;this._cl=4271175723|0;this._dl=1595750129|0;this._el=2917565137|0;this._fl=725511199|0;this._gl=4215389547|0;this._hl=327033209|0;this._len=this._s=0;return this};function S(X,Xl,n){return X>>>n|Xl<<32-n}function Ch(x,y,z){return x&y^~x&z}function Maj(x,y,z){return x&y^x&z^y&z}Sha512.prototype._update=function(M){var W=this._w;var a,b,c,d,e,f,g,h;var al,bl,cl,dl,el,fl,gl,hl;a=this._a|0;b=this._b|0;c=this._c|0;d=this._d|0;e=this._e|0;f=this._f|0;g=this._g|0;h=this._h|0;al=this._al|0;bl=this._bl|0;cl=this._cl|0;dl=this._dl|0;el=this._el|0;fl=this._fl|0;gl=this._gl|0;hl=this._hl|0;for(var i=0;i<80;i++){var j=i*2;var Wi,Wil;if(i<16){Wi=W[j]=M.readInt32BE(j*4);Wil=W[j+1]=M.readInt32BE(j*4+4)}else{var x=W[j-15*2];var xl=W[j-15*2+1];var gamma0=S(x,xl,1)^S(x,xl,8)^x>>>7;var gamma0l=S(xl,x,1)^S(xl,x,8)^S(xl,x,7);x=W[j-2*2];xl=W[j-2*2+1];var gamma1=S(x,xl,19)^S(xl,x,29)^x>>>6;var gamma1l=S(xl,x,19)^S(x,xl,29)^S(xl,x,6);var Wi7=W[j-7*2];var Wi7l=W[j-7*2+1];var Wi16=W[j-16*2];var Wi16l=W[j-16*2+1];Wil=gamma0l+Wi7l;Wi=gamma0+Wi7+(Wil>>>0>>0?1:0);Wil=Wil+gamma1l;Wi=Wi+gamma1+(Wil>>>0>>0?1:0);Wil=Wil+Wi16l;Wi=Wi+Wi16+(Wil>>>0>>0?1:0);W[j]=Wi;W[j+1]=Wil}var maj=Maj(a,b,c);var majl=Maj(al,bl,cl);var sigma0h=S(a,al,28)^S(al,a,2)^S(al,a,7);var sigma0l=S(al,a,28)^S(a,al,2)^S(a,al,7);var sigma1h=S(e,el,14)^S(e,el,18)^S(el,e,9);var sigma1l=S(el,e,14)^S(el,e,18)^S(e,el,9);var Ki=K[j];var Kil=K[j+1];var ch=Ch(e,f,g);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l;var t1=h+sigma1h+(t1l>>>0>>0?1:0);t1l=t1l+chl;t1=t1+ch+(t1l>>>0>>0?1:0);t1l=t1l+Kil;t1=t1+Ki+(t1l>>>0>>0?1:0);t1l=t1l+Wil;t1=t1+Wi+(t1l>>>0>>0?1:0);var t2l=sigma0l+majl;var t2=sigma0h+maj+(t2l>>>0>>0?1:0);h=g;hl=gl;g=f;gl=fl;f=e;fl=el;el=dl+t1l|0;e=d+t1+(el>>>0
>>0?1:0)|0;d=c;dl=cl;c=b;cl=bl;b=a;bl=al;al=t1l+t2l|0;a=t1+t2+(al>>>0>>0?1:0)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._a=this._a+a+(this._al>>>0>>0?1:0)|0;this._b=this._b+b+(this._bl>>>0>>0?1:0)|0;this._c=this._c+c+(this._cl>>>0>>0?1:0)|0;this._d=this._d+d+(this._dl>>>0
>>0?1:0)|0;this._e=this._e+e+(this._el>>>0>>0?1:0)|0;this._f=this._f+f+(this._fl>>>0>>0?1:0)|0;this._g=this._g+g+(this._gl>>>0>>0?1:0)|0;this._h=this._h+h+(this._hl>>>0>>0?1:0)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._a,this._al,0);writeInt64BE(this._b,this._bl,8);writeInt64BE(this._c,this._cl,16);writeInt64BE(this._d,this._dl,24);writeInt64BE(this._e,this._el,32);writeInt64BE(this._f,this._fl,40);writeInt64BE(this._g,this._gl,48);writeInt64BE(this._h,this._hl,56);return H};return Sha512}},{util:23}],22:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],23:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){ -return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":22,_process:15,inherits:12}],24:[function(require,module,exports){"use strict";var _crypto=require("crypto");var _crypto2=_interopRequireDefault(_crypto);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}module.exports={generatePassword:_generatePassword,encryptLogin:_encryptLogin,_deriveHash:_deriveHash,_prettyPrint:_prettyPrint,_getTemplate:_getTemplate,_getCharType:_getCharType,_getPasswordChar:_getPasswordChar,_string2charCodes:_string2charCodes};function _generatePassword(login,masterPassword,site,options){return new Promise(function(resolve,reject){if(!login||!masterPassword||!site){reject("generatePassword invalid parameter")}_encryptLogin(login,masterPassword).then(function(hash){var derivedHash=_deriveHash(hash,site,options);var template=_getTemplate(options.password.settings);resolve(_prettyPrint(derivedHash,template))})})}function _encryptLogin(login,masterPassword){return new Promise(function(resolve,reject){if(!login||!masterPassword){reject("encryptLogin parameter could not be empty")}var iterations=8192;var keylen=32;_crypto2.default.pbkdf2(masterPassword,login,iterations,keylen,"sha256",function(error,key){if(error){reject("error in pbkdf2")}else{resolve(key.toString("hex"))}})})}function _deriveHash(hash,site){var _ref=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];var _ref$password=_ref.password;var password=_ref$password===undefined?{length:12}:_ref$password;var _ref$counter=_ref.counter;var counter=_ref$counter===undefined?1:_ref$counter;var salt=site+counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",hash).update(salt).digest("hex");return derivedHash.substring(0,password.length)}function _getTemplate(){var passwordTypes=arguments.length<=0||arguments[0]===undefined?["strong"]:arguments[0];var passwordTypesInfo={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return passwordTypes.map(function(passwordType){return passwordTypesInfo[passwordType]}).sort(function(passwordType1,passwordType2){return passwordType1.order>passwordType2.order}).map(function(passwordType){return passwordType.value}).join("")}function _prettyPrint(hash,template){var password="";_string2charCodes(hash).forEach(function(charCode,index){var charType=_getCharType(template,index);password+=_getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":22,_process:15,inherits:12}],24:[function(require,module,exports){"use strict";var _crypto=require("crypto");var _crypto2=_interopRequireDefault(_crypto);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}module.exports={generatePassword:_generatePassword,encryptLogin:_encryptLogin,renderPassword:_renderPassword,_deriveHash:_deriveHash,_prettyPrint:_prettyPrint,_getTemplate:_getTemplate,_getCharType:_getCharType,_getPasswordChar:_getPasswordChar,_string2charCodes:_string2charCodes};function _generatePassword(login,masterPassword,site,options){return new Promise(function(resolve,reject){if(!login||!masterPassword||!site){reject("generatePassword invalid parameter")}_encryptLogin(login,masterPassword).then(function(hash){resolve(_renderPassword(hash,site,options))})})}function _renderPassword(hash,site,options){var derivedHash=_deriveHash(hash,site,options);var template=_getTemplate(options.password.settings);return _prettyPrint(derivedHash,template)}function _encryptLogin(login,masterPassword){return new Promise(function(resolve,reject){if(!login||!masterPassword){reject("encryptLogin parameter could not be empty")}var iterations=8192;var keylen=32;_crypto2.default.pbkdf2(masterPassword,login,iterations,keylen,"sha256",function(error,key){if(error){reject("error in pbkdf2")}else{resolve(key.toString("hex"))}})})}function _deriveHash(hash,site){var _ref=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];var _ref$password=_ref.password;var password=_ref$password===undefined?{length:12}:_ref$password;var _ref$counter=_ref.counter;var counter=_ref$counter===undefined?1:_ref$counter;var salt=site+counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",hash).update(salt).digest("hex");return derivedHash.substring(0,password.length)}function _getTemplate(){var passwordTypes=arguments.length<=0||arguments[0]===undefined?["strong"]:arguments[0];var passwordTypesInfo={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return passwordTypes.map(function(passwordType){return passwordTypesInfo[passwordType]}).sort(function(passwordType1,passwordType2){return passwordType1.order>passwordType2.order}).map(function(passwordType){return passwordType.value}).join("")}function _prettyPrint(hash,template){var password="";_string2charCodes(hash).forEach(function(charCode,index){var charType=_getCharType(template,index);password+=_getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i Date: Tue, 12 Jul 2016 14:06:49 +0200 Subject: [PATCH 031/124] update documentation --- readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/readme.md b/readme.md index 794cba7..41d3e3f 100644 --- a/readme.md +++ b/readme.md @@ -2,7 +2,9 @@ # LessPass Core -core library for LessPass password manager in node.js used to generate unique password +core library for LessPass password manager in javascript used to generate unique password. + +It works with the browser and NodeJs ## Requirements @@ -88,9 +90,7 @@ exemple : }; -return: - - * promise with generated password +return a promise with generated password : lesspass.generatePassword(login, masterPassword, site, options) @@ -102,7 +102,7 @@ return: }); -see **tests/api.tests.js** for more examples +see [tests/api.tests.js](tests/api.tests.js) for more examples ## Tests From 50500fd531fc0aa6d0ae17476bebe724023438fd Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 30 Sep 2016 17:13:50 +0200 Subject: [PATCH 032/124] migrate to new api --- dist/lesspass.min.js | 16 +++++-- package.json | 19 +------- src/lesspass2.js | 86 +++++++++++++++++++++++++++++++++++++ tests/deriveEncryptedLogin.tests.js | 62 ++++++++++++++++++++++++++ tests/getPasswordTemplate.tests.js | 55 ++++++++++++++++++++++++ tests/karma.conf.js | 20 --------- tests/new.api.tests.js | 28 ++++++++++++ tests/prettyPrint.js | 37 ++++++++++++++++ 8 files changed, 283 insertions(+), 40 deletions(-) create mode 100644 src/lesspass2.js create mode 100644 tests/deriveEncryptedLogin.tests.js create mode 100644 tests/getPasswordTemplate.tests.js delete mode 100644 tests/karma.conf.js create mode 100644 tests/new.api.tests.js create mode 100644 tests/prettyPrint.js diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js index a484519..4a63eda 100644 --- a/dist/lesspass.min.js +++ b/dist/lesspass.min.js @@ -1,3 +1,13 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.lesspass=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0){throw new Error("Invalid string. Length must be a multiple of 4")}placeHolders=b64[len-2]==="="?2:b64[len-1]==="="?1:0;arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],3:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(this,val,byteOffset,encoding)}if(typeof val==="number"){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,val,byteOffset)}return arrayIndexOf(this,[val],byteOffset,encoding)}throw new TypeError("val must be string, number or Buffer")};Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"binary":return binaryWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":2,ieee754:11,isarray:13}],4:[function(require,module,exports){(function(Buffer){var createHash=require("sha.js");var md5=toConstructor(require("./md5"));var rmd160=toConstructor(require("ripemd160"));function toConstructor(fn){return function(){var buffers=[];var m={update:function(data,enc){if(!Buffer.isBuffer(data))data=new Buffer(data,enc);buffers.push(data);return this},digest:function(enc){var buf=Buffer.concat(buffers);var r=fn(buf);buffers=null;return enc?r.toString(enc):r}};return m}}module.exports=function(alg){if("md5"===alg)return new md5;if("rmd160"===alg)return new rmd160;return createHash(alg)}}).call(this,require("buffer").Buffer)},{"./md5":8,buffer:3,ripemd160:16,"sha.js":18}],5:[function(require,module,exports){(function(Buffer){var createHash=require("./create-hash");var zeroBuffer=new Buffer(128);zeroBuffer.fill(0);module.exports=Hmac;function Hmac(alg,key){if(!(this instanceof Hmac))return new Hmac(alg,key);this._opad=opad;this._alg=alg;var blocksize=alg==="sha512"?128:64;key=this._key=!Buffer.isBuffer(key)?new Buffer(key):key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.length>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":6}],9:[function(require,module,exports){var pbkdf2Export=require("pbkdf2-compat/pbkdf2");module.exports=function(crypto,exports){exports=exports||{};var exported=pbkdf2Export(crypto);exports.pbkdf2=exported.pbkdf2;exports.pbkdf2Sync=exported.pbkdf2Sync;return exports}},{"pbkdf2-compat/pbkdf2":14}],10:[function(require,module,exports){(function(global,Buffer){(function(){var g=("undefined"===typeof window?global:window)||{};_crypto=g.crypto||g.msCrypto||require("crypto");module.exports=function(size){if(_crypto.getRandomValues){var bytes=new Buffer(size);_crypto.getRandomValues(bytes);return bytes}else if(_crypto.randomBytes){return _crypto.randomBytes(size)}else throw new Error("secure random number generation not supported by this browser\n"+"use chrome, FireFox or Internet Explorer 11")}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{buffer:3,crypto:1}],11:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],12:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],13:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],14:[function(require,module,exports){(function(Buffer){module.exports=function(crypto){function pbkdf2(password,salt,iterations,keylen,digest,callback){if("function"===typeof digest){callback=digest;digest=undefined}if("function"!==typeof callback)throw new Error("No callback provided to pbkdf2");setTimeout(function(){var result;try{result=pbkdf2Sync(password,salt,iterations,keylen,digest)}catch(e){return callback(e)}callback(undefined,result)})}function pbkdf2Sync(password,salt,iterations,keylen,digest){if("number"!==typeof iterations)throw new TypeError("Iterations not a number");if(iterations<0)throw new TypeError("Bad iterations");if("number"!==typeof keylen)throw new TypeError("Key length not a number");if(keylen<0)throw new TypeError("Bad key length");digest=digest||"sha1";if(!Buffer.isBuffer(password))password=new Buffer(password);if(!Buffer.isBuffer(salt))salt=new Buffer(salt);var hLen,l=1,r,T;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=crypto.createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen;if(keylen>(Math.pow(2,32)-1)*hLen)throw new TypeError("keylen exceeds maximum length")}U.copy(T,0,0,hLen);for(var j=1;j1){for(var i=1;i>>5]|=bytes[i]<<24-b%32}return words};var wordsToBytes=function(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes};var processBlock=function(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(var i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t};function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message=="string")message=new Buffer(message,"utf8");var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}}).call(this,require("buffer").Buffer)},{buffer:3}],17:[function(require,module,exports){module.exports=function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.init=function(){this._s=0;this._len=0};Hash.prototype.update=function(data,enc){if("string"===typeof data){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};return Hash}},{}],18:[function(require,module,exports){var exports=module.exports=function(alg){var Alg=exports[alg];if(!Alg)throw new Error(alg+" is not supported (we accept pull requests)");return new Alg};var Buffer=require("buffer").Buffer;var Hash=require("./hash")(Buffer);exports.sha1=require("./sha1")(Buffer,Hash);exports.sha256=require("./sha256")(Buffer,Hash);exports.sha512=require("./sha512")(Buffer,Hash)},{"./hash":17,"./sha1":19,"./sha256":20,"./sha512":21,buffer:3}],19:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var A=0|0;var B=4|0;var C=8|0;var D=12|0;var E=16|0;var W=new(typeof Int32Array==="undefined"?Array:Int32Array)(80);var POOL=[];function Sha1(){if(POOL.length)return POOL.pop().init();if(!(this instanceof Sha1))return new Sha1;this._w=W;Hash.call(this,16*4,14*4);this._h=null;this.init()}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;Hash.prototype.init.call(this);return this};Sha1.prototype._POOL=POOL;Sha1.prototype._update=function(X){var a,b,c,d,e,_a,_b,_c,_d,_e;a=_a=this._a;b=_b=this._b;c=_c=this._c;d=_d=this._d;e=_e=this._e;var w=this._w;for(var j=0;j<80;j++){var W=w[j]=j<16?X.readInt32BE(j*4):rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=add(add(rol(a,5),sha1_ft(j,b,c,d)),add(add(e,W),sha1_kt(j)));e=d;d=c;c=rol(b,30);b=a;a=t}this._a=add(a,_a);this._b=add(b,_b);this._c=add(c,_c);this._d=add(d,_d);this._e=add(e,_e)};Sha1.prototype._hash=function(){if(POOL.length<100)POOL.push(this);var H=new Buffer(20);H.writeInt32BE(this._a|0,A);H.writeInt32BE(this._b|0,B);H.writeInt32BE(this._c|0,C);H.writeInt32BE(this._d|0,D);H.writeInt32BE(this._e|0,E);return H};function sha1_ft(t,b,c,d){if(t<20)return b&c|~b&d;if(t<40)return b^c^d;if(t<60)return b&c|b&d|c&d;return b^c^d}function sha1_kt(t){return t<20?1518500249:t<40?1859775393:t<60?-1894007588:-899497514}function add(x,y){return x+y|0}function rol(num,cnt){return num<>>32-cnt}return Sha1}},{util:23}],20:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,16*4,14*4)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._len=this._s=0;return this};function S(X,n){return X>>>n|X<<32-n}function R(X,n){return X>>>n}function Ch(x,y,z){return x&y^~x&z}function Maj(x,y,z){return x&y^x&z^y&z}function Sigma0256(x){return S(x,2)^S(x,13)^S(x,22)}function Sigma1256(x){return S(x,6)^S(x,11)^S(x,25)}function Gamma0256(x){return S(x,7)^S(x,18)^R(x,3)}function Gamma1256(x){return S(x,17)^S(x,19)^R(x,10)}Sha256.prototype._update=function(M){var W=this._w;var a,b,c,d,e,f,g,h;var T1,T2;a=this._a|0;b=this._b|0;c=this._c|0;d=this._d|0;e=this._e|0;f=this._f|0;g=this._g|0;h=this._h|0;for(var j=0;j<64;j++){var w=W[j]=j<16?M.readInt32BE(j*4):Gamma1256(W[j-2])+W[j-7]+Gamma0256(W[j-15])+W[j-16];T1=h+Sigma1256(e)+Ch(e,f,g)+K[j]+w;T2=Sigma0256(a)+Maj(a,b,c);h=g;g=f;f=e;e=d+T1;d=c;c=b;b=a;a=T1+T2}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};return Sha256}},{util:23}],21:[function(require,module,exports){var inherits=require("util").inherits;module.exports=function(Buffer,Hash){var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._a=1779033703|0;this._b=3144134277|0;this._c=1013904242|0;this._d=2773480762|0;this._e=1359893119|0;this._f=2600822924|0;this._g=528734635|0;this._h=1541459225|0;this._al=4089235720|0;this._bl=2227873595|0;this._cl=4271175723|0;this._dl=1595750129|0;this._el=2917565137|0;this._fl=725511199|0;this._gl=4215389547|0;this._hl=327033209|0;this._len=this._s=0;return this};function S(X,Xl,n){return X>>>n|Xl<<32-n}function Ch(x,y,z){return x&y^~x&z}function Maj(x,y,z){return x&y^x&z^y&z}Sha512.prototype._update=function(M){var W=this._w;var a,b,c,d,e,f,g,h;var al,bl,cl,dl,el,fl,gl,hl;a=this._a|0;b=this._b|0;c=this._c|0;d=this._d|0;e=this._e|0;f=this._f|0;g=this._g|0;h=this._h|0;al=this._al|0;bl=this._bl|0;cl=this._cl|0;dl=this._dl|0;el=this._el|0;fl=this._fl|0;gl=this._gl|0;hl=this._hl|0;for(var i=0;i<80;i++){var j=i*2;var Wi,Wil;if(i<16){Wi=W[j]=M.readInt32BE(j*4);Wil=W[j+1]=M.readInt32BE(j*4+4)}else{var x=W[j-15*2];var xl=W[j-15*2+1];var gamma0=S(x,xl,1)^S(x,xl,8)^x>>>7;var gamma0l=S(xl,x,1)^S(xl,x,8)^S(xl,x,7);x=W[j-2*2];xl=W[j-2*2+1];var gamma1=S(x,xl,19)^S(xl,x,29)^x>>>6;var gamma1l=S(xl,x,19)^S(x,xl,29)^S(xl,x,6);var Wi7=W[j-7*2];var Wi7l=W[j-7*2+1];var Wi16=W[j-16*2];var Wi16l=W[j-16*2+1];Wil=gamma0l+Wi7l;Wi=gamma0+Wi7+(Wil>>>0>>0?1:0);Wil=Wil+gamma1l;Wi=Wi+gamma1+(Wil>>>0>>0?1:0);Wil=Wil+Wi16l;Wi=Wi+Wi16+(Wil>>>0>>0?1:0);W[j]=Wi;W[j+1]=Wil}var maj=Maj(a,b,c);var majl=Maj(al,bl,cl);var sigma0h=S(a,al,28)^S(al,a,2)^S(al,a,7);var sigma0l=S(al,a,28)^S(a,al,2)^S(a,al,7);var sigma1h=S(e,el,14)^S(e,el,18)^S(el,e,9);var sigma1l=S(el,e,14)^S(el,e,18)^S(e,el,9);var Ki=K[j];var Kil=K[j+1];var ch=Ch(e,f,g);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l;var t1=h+sigma1h+(t1l>>>0>>0?1:0);t1l=t1l+chl;t1=t1+ch+(t1l>>>0>>0?1:0);t1l=t1l+Kil;t1=t1+Ki+(t1l>>>0>>0?1:0);t1l=t1l+Wil;t1=t1+Wi+(t1l>>>0>>0?1:0);var t2l=sigma0l+majl;var t2=sigma0h+maj+(t2l>>>0>>0?1:0);h=g;hl=gl;g=f;gl=fl;f=e;fl=el;el=dl+t1l|0;e=d+t1+(el>>>0
>>0?1:0)|0;d=c;dl=cl;c=b;cl=bl;b=a;bl=al;al=t1l+t2l|0;a=t1+t2+(al>>>0>>0?1:0)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._a=this._a+a+(this._al>>>0>>0?1:0)|0;this._b=this._b+b+(this._bl>>>0>>0?1:0)|0;this._c=this._c+c+(this._cl>>>0>>0?1:0)|0;this._d=this._d+d+(this._dl>>>0
>>0?1:0)|0;this._e=this._e+e+(this._el>>>0>>0?1:0)|0;this._f=this._f+f+(this._fl>>>0>>0?1:0)|0;this._g=this._g+g+(this._gl>>>0>>0?1:0)|0;this._h=this._h+h+(this._hl>>>0>>0?1:0)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._a,this._al,0);writeInt64BE(this._b,this._bl,8);writeInt64BE(this._c,this._cl,16);writeInt64BE(this._d,this._dl,24);writeInt64BE(this._e,this._el,32);writeInt64BE(this._f,this._fl,40);writeInt64BE(this._g,this._gl,48);writeInt64BE(this._h,this._hl,56);return H};return Sha512}},{util:23}],22:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],23:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){ -return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":22,_process:15,inherits:12}],24:[function(require,module,exports){"use strict";var _crypto=require("crypto");var _crypto2=_interopRequireDefault(_crypto);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}module.exports={generatePassword:_generatePassword,encryptLogin:_encryptLogin,renderPassword:_renderPassword,_deriveHash:_deriveHash,_prettyPrint:_prettyPrint,_getTemplate:_getTemplate,_getCharType:_getCharType,_getPasswordChar:_getPasswordChar,_string2charCodes:_string2charCodes};function _generatePassword(login,masterPassword,site,options){return new Promise(function(resolve,reject){if(!login||!masterPassword||!site){reject("generatePassword invalid parameter")}_encryptLogin(login,masterPassword).then(function(hash){resolve(_renderPassword(hash,site,options))})})}function _renderPassword(hash,site,options){var derivedHash=_deriveHash(hash,site,options);var template=_getTemplate(options.password.settings);return _prettyPrint(derivedHash,template)}function _encryptLogin(login,masterPassword){return new Promise(function(resolve,reject){if(!login||!masterPassword){reject("encryptLogin parameter could not be empty")}var iterations=8192;var keylen=32;_crypto2.default.pbkdf2(masterPassword,login,iterations,keylen,"sha256",function(error,key){if(error){reject("error in pbkdf2")}else{resolve(key.toString("hex"))}})})}function _deriveHash(hash,site){var _ref=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];var _ref$password=_ref.password;var password=_ref$password===undefined?{length:12}:_ref$password;var _ref$counter=_ref.counter;var counter=_ref$counter===undefined?1:_ref$counter;var salt=site+counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",hash).update(salt).digest("hex");return derivedHash.substring(0,password.length)}function _getTemplate(){var passwordTypes=arguments.length<=0||arguments[0]===undefined?["strong"]:arguments[0];var passwordTypesInfo={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return passwordTypes.map(function(passwordType){return passwordTypesInfo[passwordType]}).sort(function(passwordType1,passwordType2){return passwordType1.order>passwordType2.order}).map(function(passwordType){return passwordType.value}).join("")}function _prettyPrint(hash,template){var password="";_string2charCodes(hash).forEach(function(charCode,index){var charType=_getCharType(template,index);password+=_getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint); +}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:4,isarray:5}],3:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],4:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],6:[function(require,module,exports){"use strict";exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=require("randombytes");exports.createHash=exports.Hash=require("create-hash");exports.createHmac=exports.Hmac=require("create-hmac");var hashes=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(Object.keys(require("browserify-sign/algos")));exports.getHashes=function(){return hashes};var p=require("pbkdf2");exports.pbkdf2=p.pbkdf2;exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require("browserify-cipher");["Cipher","createCipher","Cipheriv","createCipheriv","Decipher","createDecipher","Decipheriv","createDecipheriv","getCiphers","listCiphers"].forEach(function(key){exports[key]=aes[key]});var dh=require("diffie-hellman");["DiffieHellmanGroup","createDiffieHellmanGroup","getDiffieHellman","createDiffieHellman","DiffieHellman"].forEach(function(key){exports[key]=dh[key]});var sign=require("browserify-sign");["createSign","Sign","createVerify","Verify"].forEach(function(key){exports[key]=sign[key]});exports.createECDH=require("create-ecdh");var publicEncrypt=require("public-encrypt");["publicEncrypt","privateEncrypt","publicDecrypt","privateDecrypt"].forEach(function(key){exports[key]=publicEncrypt[key]});["createCredentials"].forEach(function(name){exports[name]=function(){throw new Error(["sorry, "+name+" is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))}})},{"browserify-cipher":7,"browserify-sign":37,"browserify-sign/algos":36,"create-ecdh":104,"create-hash":130,"create-hmac":143,"diffie-hellman":144,pbkdf2:151,"public-encrypt":153,randombytes:198}],7:[function(require,module,exports){var ebtk=require("evp_bytestokey");var aes=require("browserify-aes/browser");var DES=require("browserify-des");var desModes=require("browserify-des/modes");var aesModes=require("browserify-aes/modes");function createCipher(suite,password){var keyLen,ivLen;suite=suite.toLowerCase();if(aesModes[suite]){keyLen=aesModes[suite].key;ivLen=aesModes[suite].iv}else if(desModes[suite]){keyLen=desModes[suite].key*8;ivLen=desModes[suite].iv}else{throw new TypeError("invalid suite type")}var keys=ebtk(password,false,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){var keyLen,ivLen;suite=suite.toLowerCase();if(aesModes[suite]){keyLen=aesModes[suite].key;ivLen=aesModes[suite].iv}else if(desModes[suite]){keyLen=desModes[suite].key*8;ivLen=desModes[suite].iv}else{throw new TypeError("invalid suite type")}var keys=ebtk(password,false,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){suite=suite.toLowerCase();if(aesModes[suite]){return aes.createCipheriv(suite,key,iv)}else if(desModes[suite]){return new DES({key:key,iv:iv,mode:suite})}else{throw new TypeError("invalid suite type")}}function createDecipheriv(suite,key,iv){suite=suite.toLowerCase();if(aesModes[suite]){return aes.createDecipheriv(suite,key,iv)}else if(desModes[suite]){return new DES({key:key,iv:iv,mode:suite,decrypt:true})}else{throw new TypeError("invalid suite type")}}exports.createCipher=exports.Cipher=createCipher;exports.createCipheriv=exports.Cipheriv=createCipheriv;exports.createDecipher=exports.Decipher=createDecipher;exports.createDecipheriv=exports.Decipheriv=createDecipheriv;function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":10,"browserify-aes/modes":14,"browserify-des":25,"browserify-des/modes":26,evp_bytestokey:35}],8:[function(require,module,exports){(function(Buffer){var uint_max=Math.pow(2,32);function fixup_uint32(x){var ret,x_pos;ret=x>uint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x;return ret}function scrub_vec(v){for(var i=0;i>>8^sx&255^99;this.SBOX[x]=sx;this.INV_SBOX[sx]=x;x2=d[x];x4=d[x2];x8=d[x4];t=d[sx]*257^sx*16843008;this.SUB_MIX[0][x]=t<<24|t>>>8;this.SUB_MIX[1][x]=t<<16|t>>>16;this.SUB_MIX[2][x]=t<<8|t>>>24;this.SUB_MIX[3][x]=t;t=x8*16843009^x4*65537^x2*257^x*16843008;this.INV_SUB_MIX[0][sx]=t<<24|t>>>8;this.INV_SUB_MIX[1][sx]=t<<16|t>>>16;this.INV_SUB_MIX[2][sx]=t<<8|t>>>24;this.INV_SUB_MIX[3][sx]=t;if(x===0){x=xi=1}else{x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]]}}return true};var G=new Global;AES.blockSize=4*4;AES.prototype.blockSize=AES.blockSize;AES.keySize=256/8;AES.prototype.keySize=AES.keySize;function bufferToArray(buf){var len=buf.length/4;var out=new Array(len);var i=-1;while(++i>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255],t^=G.RCON[ksRow/keySize|0]<<24):keySize>6&&ksRow%keySize===4?t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255]:void 0,this._keySchedule[ksRow-keySize]^t)}this._invKeySchedule=[];for(invKsRow=0;invKsRow>>24]]^G.INV_SUB_MIX[1][G.SBOX[t>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[t>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[t&255]]}return true};AES.prototype.encryptBlock=function(M){M=bufferToArray(new Buffer(M));var out=this._doCryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[1],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[3],12);return buf};AES.prototype.decryptBlock=function(M){M=bufferToArray(new Buffer(M));var temp=[M[3],M[1]];M[1]=temp[0];M[3]=temp[1];var out=this._doCryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[3],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[1],12);return buf};AES.prototype.scrub=function(){scrub_vec(this._keySchedule);scrub_vec(this._invKeySchedule);scrub_vec(this._key)};AES.prototype._doCryptBlock=function(M,keySchedule,SUB_MIX,SBOX){var ksRow,s0,s1,s2,s3,t0,t1,t2,t3;s0=M[0]^keySchedule[0];s1=M[1]^keySchedule[1];s2=M[2]^keySchedule[2];s3=M[3]^keySchedule[3];ksRow=4;for(var round=1;round>>24]^SUB_MIX[1][s1>>>16&255]^SUB_MIX[2][s2>>>8&255]^SUB_MIX[3][s3&255]^keySchedule[ksRow++];t1=SUB_MIX[0][s1>>>24]^SUB_MIX[1][s2>>>16&255]^SUB_MIX[2][s3>>>8&255]^SUB_MIX[3][s0&255]^keySchedule[ksRow++];t2=SUB_MIX[0][s2>>>24]^SUB_MIX[1][s3>>>16&255]^SUB_MIX[2][s0>>>8&255]^SUB_MIX[3][s1&255]^keySchedule[ksRow++];t3=SUB_MIX[0][s3>>>24]^SUB_MIX[1][s0>>>16&255]^SUB_MIX[2][s1>>>8&255]^SUB_MIX[3][s2&255]^keySchedule[ksRow++];s0=t0;s1=t1;s2=t2;s3=t3}t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++];t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++];t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++];t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++];return[fixup_uint32(t0),fixup_uint32(t1),fixup_uint32(t2),fixup_uint32(t3)]};exports.AES=AES}).call(this,require("buffer").Buffer)},{buffer:2}],9:[function(require,module,exports){(function(Buffer){var aes=require("./aes");var Transform=require("cipher-base");var inherits=require("inherits");var GHASH=require("./ghash");var xor=require("buffer-xor");inherits(StreamCipher,Transform);module.exports=StreamCipher;function StreamCipher(mode,key,iv,decrypt){if(!(this instanceof StreamCipher)){return new StreamCipher(mode,key,iv)}Transform.call(this);this._finID=Buffer.concat([iv,new Buffer([0,0,0,1])]);iv=Buffer.concat([iv,new Buffer([0,0,0,2])]);this._cipher=new aes.AES(key);this._prev=new Buffer(iv.length);this._cache=new Buffer("");this._secCache=new Buffer("");this._decrypt=decrypt;this._alen=0;this._len=0;iv.copy(this._prev);this._mode=mode;var h=new Buffer(4);h.fill(0);this._ghash=new GHASH(this._cipher.encryptBlock(h));this._authTag=null;this._called=false}StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;if(rump<16){rump=new Buffer(rump);rump.fill(0);this._ghash.update(rump)}}this._called=true;var out=this._mode.encrypt(this,chunk);if(this._decrypt){this._ghash.update(chunk)}else{this._ghash.update(out)}this._len+=chunk.length;return out};StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag){throw new Error("Unsupported state or unable to authenticate data")}var tag=xor(this._ghash.final(this._alen*8,this._len*8),this._cipher.encryptBlock(this._finID));if(this._decrypt){if(xorTest(tag,this._authTag)){throw new Error("Unsupported state or unable to authenticate data")}}else{this._authTag=tag}this._cipher.scrub()};StreamCipher.prototype.getAuthTag=function getAuthTag(){if(!this._decrypt&&Buffer.isBuffer(this._authTag)){return this._authTag}else{throw new Error("Attempting to get auth tag in unsupported state")}};StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(this._decrypt){this._authTag=tag}else{throw new Error("Attempting to set auth tag in unsupported state")}};StreamCipher.prototype.setAAD=function setAAD(buf){if(!this._called){this._ghash.update(buf);this._alen+=buf.length}else{throw new Error("Attempting to set AAD in unsupported state")}};function xorTest(a,b){var out=0;if(a.length!==b.length){out++}var len=Math.min(a.length,b.length);var i=-1;while(++i16){out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}}else{if(this.cache.length>=16){out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}}return null};Splitter.prototype.flush=function(){if(this.cache.length){return this.cache}};function unpad(last){var padded=last[15];var i=-1;while(++i15){var out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}return null};Splitter.prototype.flush=function(){var len=16-this.cache.length;var padBuff=new Buffer(len);var i=-1;while(++i0;j--){Vi[j]=Vi[j]>>>1|(Vi[j-1]&1)<<31}Vi[0]=Vi[0]>>>1;if(lsb_Vi){Vi[0]=Vi[0]^225<<24}}this.state=fromArray(Zi)};GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);var chunk;while(this.cache.length>=16){chunk=this.cache.slice(0,16);this.cache=this.cache.slice(16);this.ghash(chunk)}};GHASH.prototype.final=function(abl,bl){if(this.cache.length){this.ghash(Buffer.concat([this.cache,zeros],16))}this.ghash(fromArray([0,abl,0,bl]));return this.state};function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){out=out.map(fixup_uint32);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[1],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[3],12);return buf}var uint_max=Math.pow(2,32);function fixup_uint32(x){var ret,x_pos;ret=x>uint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x;return ret}function xor(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}}).call(this,require("buffer").Buffer)},{buffer:2}],14:[function(require,module,exports){exports["aes-128-ecb"]={cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"};exports["aes-192-ecb"]={cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"};exports["aes-256-ecb"]={cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"};exports["aes-128-cbc"]={cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"};exports["aes-192-cbc"]={cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"};exports["aes-256-cbc"]={cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"};exports["aes128"]=exports["aes-128-cbc"];exports["aes192"]=exports["aes-192-cbc"];exports["aes256"]=exports["aes-256-cbc"];exports["aes-128-cfb"]={cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"};exports["aes-192-cfb"]={cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"};exports["aes-256-cfb"]={cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"};exports["aes-128-cfb8"]={cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"};exports["aes-192-cfb8"]={cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"};exports["aes-256-cfb8"]={cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"};exports["aes-128-cfb1"]={cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"};exports["aes-192-cfb1"]={cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"};exports["aes-256-cfb1"]={cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"};exports["aes-128-ofb"]={cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"};exports["aes-192-ofb"]={cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"};exports["aes-256-ofb"]={cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"};exports["aes-128-ctr"]={cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"};exports["aes-192-ctr"]={cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"};exports["aes-256-ctr"]={cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"};exports["aes-128-gcm"]={cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"};exports["aes-192-gcm"]={cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"};exports["aes-256-gcm"]={cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}},{}],15:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);self._prev=self._cipher.encryptBlock(data);return self._prev};exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":22}],16:[function(require,module,exports){(function(Buffer){var xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){var out=new Buffer("");var len;while(data.length){if(self._cache.length===0){self._cache=self._cipher.encryptBlock(self._prev);self._prev=new Buffer("")}if(self._cache.length<=data.length){len=self._cache.length;out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]);data=data.slice(len)}else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}}return out};function encryptStart(self,data,decrypt){var len=data.length;var out=xor(data,self._cache);self._cache=self._cache.slice(len);self._prev=Buffer.concat([self._prev,decrypt?data:out]);return out}}).call(this,require("buffer").Buffer)},{buffer:2,"buffer-xor":22}],17:[function(require,module,exports){(function(Buffer){function encryptByte(self,byteParam,decrypt){var pad;var i=-1;var len=8;var out=0;var bit,value;while(++i>i%8;self._prev=shiftIn(self._prev,decrypt?bit:value)}return out}exports.encrypt=function(self,chunk,decrypt){var len=chunk.length;var out=new Buffer(len);var i=-1;while(++i>7}return out}}).call(this,require("buffer").Buffer)},{buffer:2}],18:[function(require,module,exports){(function(Buffer){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev);var out=pad[0]^byteParam;self._prev=Buffer.concat([self._prev.slice(1),new Buffer([decrypt?byteParam:out])]);return out}exports.encrypt=function(self,chunk,decrypt){var len=chunk.length;var out=new Buffer(len);var i=-1;while(++i0;count--){inputOff+=this._buffer(data,inputOff);outputOff+=this._flushBuffer(out,outputOff)}inputOff+=this._buffer(data,inputOff);return out};Cipher.prototype.final=function final(buffer){var first;if(buffer)first=this.update(buffer);var last;if(this.type==="encrypt")last=this._finalEncrypt();else last=this._finalDecrypt();if(first)return first.concat(last);else return last};Cipher.prototype._pad=function _pad(buffer,off){if(off===0)return false;while(off>>1];kL=utils.r28shl(kL,shift);kR=utils.r28shl(kR,shift);utils.pc2(kL,kR,state.keys,i)}};DES.prototype._update=function _update(inp,inOff,out,outOff){var state=this._desState;var l=utils.readUInt32BE(inp,inOff);var r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0);l=state.tmp[0];r=state.tmp[1];if(this.type==="encrypt")this._encrypt(state,l,r,state.tmp,0);else this._decrypt(state,l,r,state.tmp,0);l=state.tmp[0];r=state.tmp[1];utils.writeUInt32BE(out,l,outOff);utils.writeUInt32BE(out,r,outOff+4)};DES.prototype._pad=function _pad(buffer,off){var value=buffer.length-off;for(var i=off;i>>0;l=t}utils.rip(r,l,out,off)};DES.prototype._decrypt=function _decrypt(state,lStart,rStart,out,off){var l=rStart;var r=lStart;for(var i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i];var keyR=state.keys[i+1];utils.expand(l,state.tmp,0);keyL^=state.tmp[0];keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR);var f=utils.permute(s);var t=l;l=(r^f)>>>0;r=t}utils.rip(l,r,out,off)}},{"../des":28,inherits:200,"minimalistic-assert":34}],32:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");var des=require("../des");var Cipher=des.Cipher;var DES=des.DES;function EDEState(type,key){assert.equal(key.length,24,"Invalid key length");var k1=key.slice(0,8);var k2=key.slice(8,16);var k3=key.slice(16,24);if(type==="encrypt"){this.ciphers=[DES.create({type:"encrypt",key:k1}),DES.create({type:"decrypt",key:k2}),DES.create({type:"encrypt",key:k3})]}else{this.ciphers=[DES.create({type:"decrypt",key:k3}),DES.create({type:"encrypt",key:k2}),DES.create({type:"decrypt",key:k1})]}}function EDE(options){Cipher.call(this,options);var state=new EDEState(this.type,this.options.key);this._edeState=state}inherits(EDE,Cipher);module.exports=EDE;EDE.create=function create(options){return new EDE(options)};EDE.prototype._update=function _update(inp,inOff,out,outOff){var state=this._edeState;state.ciphers[0]._update(inp,inOff,out,outOff);state.ciphers[1]._update(out,outOff,out,outOff);state.ciphers[2]._update(out,outOff,out,outOff)};EDE.prototype._pad=DES.prototype._pad;EDE.prototype._unpad=DES.prototype._unpad},{"../des":28,inherits:200,"minimalistic-assert":34}],33:[function(require,module,exports){"use strict";exports.readUInt32BE=function readUInt32BE(bytes,off){var res=bytes[0+off]<<24|bytes[1+off]<<16|bytes[2+off]<<8|bytes[3+off];return res>>>0};exports.writeUInt32BE=function writeUInt32BE(bytes,value,off){bytes[0+off]=value>>>24;bytes[1+off]=value>>>16&255;bytes[2+off]=value>>>8&255;bytes[3+off]=value&255};exports.ip=function ip(inL,inR,out,off){var outL=0;var outR=0;for(var i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>>j+i&1}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inL>>>j+i&1}}for(var i=6;i>=0;i-=2){for(var j=1;j<=25;j+=8){outR<<=1;outR|=inR>>>j+i&1}for(var j=1;j<=25;j+=8){outR<<=1;outR|=inL>>>j+i&1}}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.rip=function rip(inL,inR,out,off){var outL=0;var outR=0;for(var i=0;i<4;i++){for(var j=24;j>=0;j-=8){outL<<=1;outL|=inR>>>j+i&1;outL<<=1;outL|=inL>>>j+i&1}}for(var i=4;i<8;i++){for(var j=24;j>=0;j-=8){outR<<=1;outR|=inR>>>j+i&1;outR<<=1;outR|=inL>>>j+i&1}}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.pc1=function pc1(inL,inR,out,off){var outL=0;var outR=0;for(var i=7;i>=5;i--){for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>j+i&1}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inL>>j+i&1}}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>j+i&1}for(var i=1;i<=3;i++){for(var j=0;j<=24;j+=8){outR<<=1;outR|=inR>>j+i&1}for(var j=0;j<=24;j+=8){outR<<=1;outR|=inL>>j+i&1}}for(var j=0;j<=24;j+=8){outR<<=1;outR|=inL>>j+i&1}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.r28shl=function r28shl(num,shift){return num<>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function pc2(inL,inR,out,off){var outL=0;var outR=0;var len=pc2table.length>>>1;for(var i=0;i>>pc2table[i]&1}for(var i=len;i>>pc2table[i]&1}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.expand=function expand(r,out,off){var outL=0;var outR=0;outL=(r&1)<<5|r>>>27;for(var i=23;i>=15;i-=4){outL<<=6;outL|=r>>>i&63}for(var i=11;i>=3;i-=4){outR|=r>>>i&63;outR<<=6}outR|=(r&31)<<1|r>>>31;out[off+0]=outL>>>0;out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function substitute(inL,inR){var out=0;for(var i=0;i<4;i++){var b=inL>>>18-i*6&63;var sb=sTable[i*64+b];out<<=4;out|=sb}for(var i=0;i<4;i++){var b=inR>>>18-i*6&63;var sb=sTable[4*64+i*64+b];out<<=4;out|=sb}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function permute(num){var out=0;for(var i=0;i>>permuteTable[i]&1}return out>>>0};exports.padSplit=function padSplit(num,size,group){var str=num.toString(2);while(str.length0){bufs.push(md_buf)}bufs.push(password);if(salt){bufs.push(salt)}md_buf=md5(Buffer.concat(bufs));bufs=[];i=0;if(keyLen>0){while(true){if(keyLen===0){break}if(i===md_buf.length){break}key[ki++]=md_buf[i];keyLen--;i++}}if(ivLen>0&&i!==md_buf.length){while(true){if(ivLen===0){break}if(i===md_buf.length){break}iv[ii++]=md_buf[i];ivLen--;i++}}if(keyLen===0&&ivLen===0){break}}for(i=0;i0)return left;return right};BN.min=function min(left,right){if(left.cmp(right)<0)return left;return right};BN.prototype._init=function init(number,base,endian){if(typeof number==="number"){return this._initNumber(number,base,endian)}if(typeof number==="object"){return this._initArray(number,base,endian)}if(base==="hex"){base=16}assert(base===(base|0)&&base>=2&&base<=36);number=number.toString().replace(/\s+/g,"");var start=0;if(number[0]==="-"){start++}if(base===16){this._parseHex(number,start)}else{this._parseBase(number,base,start)}if(number[0]==="-"){this.negative=1}this.strip();if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initNumber=function _initNumber(number,base,endian){if(number<0){this.negative=1;number=-number}if(number<67108864){this.words=[number&67108863];this.length=1}else if(number<4503599627370496){this.words=[number&67108863,number/67108864&67108863];this.length=2}else{assert(number<9007199254740992);this.words=[number&67108863,number/67108864&67108863,1];this.length=3}if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initArray=function _initArray(number,base,endian){assert(typeof number.length==="number");if(number.length<=0){this.words=[0];this.length=1;return this}this.length=Math.ceil(number.length/3);this.words=new Array(this.length);for(var i=0;i=0;i-=3){w=number[i]|number[i-1]<<8|number[i-2]<<16;this.words[j]|=w<>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}else if(endian==="le"){for(i=0,j=0;i>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}return this.strip()};function parseHex(str,start,end){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49&&c<=54){r|=c-49+10}else if(c>=17&&c<=22){r|=c-17+10}else{r|=c&15}}return r}BN.prototype._parseHex=function _parseHex(number,start){this.length=Math.ceil((number.length-start)/6);this.words=new Array(this.length);for(var i=0;i=start;i-=6){w=parseHex(number,i,i+6);this.words[j]|=w<>>26-off&4194303;off+=24;if(off>=26){off-=26;j++}}if(i+6!==start){w=parseHex(number,start,i+6);this.words[j]|=w<>>26-off&4194303}this.strip()};function parseBase(str,start,end,mul){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49){r+=c-49+10}else if(c>=17){r+=c-17+10}else{r+=c}}return r}BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0];this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base){limbLen++}limbLen--;limbPow=limbPow/base|0;var total=number.length-start;var mod=total%limbLen;var end=Math.min(total,total-mod)+start;var word=0;for(var i=start;i1&&this.words[this.length-1]===0){this.length--}return this._normSign()};BN.prototype._normSign=function _normSign(){if(this.length===1&&this.words[0]===0){this.negative=0}return this};BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];var groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];var groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10;padding=padding|0||1;var out;if(base===16||base==="hex"){out="";var off=0;var carry=0;for(var i=0;i>>24-off&16777215;if(carry!==0||i!==this.length-1){out=zeros[6-word.length]+word+out}else{out=word+out}off+=2;if(off>=26){off-=26;i--}}if(carry!==0){out=carry.toString(16)+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base];var groupBase=groupBases[base];out="";var c=this.clone();c.negative=0;while(!c.isZero()){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase);if(!c.isZero()){out=zeros[groupSize-r.length]+r+out}else{out=r+out}}if(this.isZero()){out="0"+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}assert(false,"Base should be between 2 and 36")};BN.prototype.toNumber=function toNumber(){var ret=this.words[0];if(this.length===2){ret+=this.words[1]*67108864}else if(this.length===3&&this.words[2]===1){ret+=4503599627370496+this.words[1]*67108864}else if(this.length>2){assert(false,"Number can only safely store up to 53 bits")}return this.negative!==0?-ret:ret};BN.prototype.toJSON=function toJSON(){return this.toString(16)};BN.prototype.toBuffer=function toBuffer(endian,length){assert(typeof Buffer!=="undefined");return this.toArrayLike(Buffer,endian,length)};BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength();var reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length");assert(reqLength>0,"Requested array length <= 0");this.strip();var littleEndian=endian==="le";var res=new ArrayType(reqLength);var b,i;var q=this.clone();if(!littleEndian){for(i=0;i=4096){r+=13;t>>>=13}if(t>=64){r+=7;t>>>=7}if(t>=8){r+=4;t>>>=4}if(t>=2){r+=2;t>>>=2}return r+t}}BN.prototype._zeroBits=function _zeroBits(w){if(w===0)return 26;var t=w;var r=0;if((t&8191)===0){r+=13;t>>>=13}if((t&127)===0){r+=7;t>>>=7}if((t&15)===0){r+=4;t>>>=4}if((t&3)===0){r+=2;t>>>=2}if((t&1)===0){r++}return r};BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1];var hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){var w=new Array(num.bitLength());for(var bit=0;bit>>wbit}return w}BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;var r=0;for(var i=0;inum.length)return this.clone().ior(num);return num.clone().ior(this)};BN.prototype.uor=function uor(num){if(this.length>num.length)return this.clone().iuor(num);return num.clone().iuor(this)};BN.prototype.iuand=function iuand(num){var b;if(this.length>num.length){b=num}else{b=this}for(var i=0;inum.length)return this.clone().iand(num);return num.clone().iand(this)};BN.prototype.uand=function uand(num){if(this.length>num.length)return this.clone().iuand(num);return num.clone().iuand(this)};BN.prototype.iuxor=function iuxor(num){var a;var b;if(this.length>num.length){a=this;b=num}else{a=num;b=this}for(var i=0;inum.length)return this.clone().ixor(num);return num.clone().ixor(this)};BN.prototype.uxor=function uxor(num){if(this.length>num.length)return this.clone().iuxor(num);return num.clone().iuxor(this)};BN.prototype.inotn=function inotn(width){assert(typeof width==="number"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0;var bitsLeft=width%26;this._expand(bytesNeeded);if(bitsLeft>0){bytesNeeded--}for(var i=0;i0){this.words[i]=~this.words[i]&67108863>>26-bitsLeft}return this.strip()};BN.prototype.notn=function notn(width){return this.clone().inotn(width)};BN.prototype.setn=function setn(bit,val){assert(typeof bit==="number"&&bit>=0);var off=bit/26|0;var wbit=bit%26;this._expand(off+1);if(val){this.words[off]=this.words[off]|1<num.length){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>>26}for(;carry!==0&&i>>26}this.length=a.length;if(carry!==0){this.words[this.length]=carry;this.length++; +}else if(a!==this){for(;inum.length)return this.clone().iadd(num);return num.clone().iadd(this)};BN.prototype.isub=function isub(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);num.negative=1;return r._normSign()}else if(this.negative!==0){this.negative=0;this.iadd(num);this.negative=1;return this._normSign()}var cmp=this.cmp(num);if(cmp===0){this.negative=0;this.length=1;this.words[0]=0;return this}var a,b;if(cmp>0){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>26;this.words[i]=r&67108863}for(;carry!==0&&i>26;this.words[i]=r&67108863}if(carry===0&&i>>26;var rword=carry&67108863;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=self.words[i]|0;b=num.words[j]|0;r=a*b+rword;ncarry+=r/67108864|0;rword=r&67108863}out.words[k]=rword|0;carry=ncarry|0}if(carry!==0){out.words[k]=carry|0}else{out.length--}return out.strip()}var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words;var b=num.words;var o=out.words;var c=0;var lo;var mid;var hi;var a0=a[0]|0;var al0=a0&8191;var ah0=a0>>>13;var a1=a[1]|0;var al1=a1&8191;var ah1=a1>>>13;var a2=a[2]|0;var al2=a2&8191;var ah2=a2>>>13;var a3=a[3]|0;var al3=a3&8191;var ah3=a3>>>13;var a4=a[4]|0;var al4=a4&8191;var ah4=a4>>>13;var a5=a[5]|0;var al5=a5&8191;var ah5=a5>>>13;var a6=a[6]|0;var al6=a6&8191;var ah6=a6>>>13;var a7=a[7]|0;var al7=a7&8191;var ah7=a7>>>13;var a8=a[8]|0;var al8=a8&8191;var ah8=a8>>>13;var a9=a[9]|0;var al9=a9&8191;var ah9=a9>>>13;var b0=b[0]|0;var bl0=b0&8191;var bh0=b0>>>13;var b1=b[1]|0;var bl1=b1&8191;var bh1=b1>>>13;var b2=b[2]|0;var bl2=b2&8191;var bh2=b2>>>13;var b3=b[3]|0;var bl3=b3&8191;var bh3=b3>>>13;var b4=b[4]|0;var bl4=b4&8191;var bh4=b4>>>13;var b5=b[5]|0;var bl5=b5&8191;var bh5=b5>>>13;var b6=b[6]|0;var bl6=b6&8191;var bh6=b6>>>13;var b7=b[7]|0;var bl7=b7&8191;var bh7=b7>>>13;var b8=b[8]|0;var bl8=b8&8191;var bh8=b8>>>13;var b9=b[9]|0;var bl9=b9&8191;var bh9=b9>>>13;out.negative=self.negative^num.negative;out.length=19;lo=Math.imul(al0,bl0);mid=Math.imul(al0,bh0);mid=mid+Math.imul(ah0,bl0)|0;hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0;w0&=67108863;lo=Math.imul(al1,bl0);mid=Math.imul(al1,bh0);mid=mid+Math.imul(ah1,bl0)|0;hi=Math.imul(ah1,bh0);lo=lo+Math.imul(al0,bl1)|0;mid=mid+Math.imul(al0,bh1)|0;mid=mid+Math.imul(ah0,bl1)|0;hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0;w1&=67108863;lo=Math.imul(al2,bl0);mid=Math.imul(al2,bh0);mid=mid+Math.imul(ah2,bl0)|0;hi=Math.imul(ah2,bh0);lo=lo+Math.imul(al1,bl1)|0;mid=mid+Math.imul(al1,bh1)|0;mid=mid+Math.imul(ah1,bl1)|0;hi=hi+Math.imul(ah1,bh1)|0;lo=lo+Math.imul(al0,bl2)|0;mid=mid+Math.imul(al0,bh2)|0;mid=mid+Math.imul(ah0,bl2)|0;hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0;w2&=67108863;lo=Math.imul(al3,bl0);mid=Math.imul(al3,bh0);mid=mid+Math.imul(ah3,bl0)|0;hi=Math.imul(ah3,bh0);lo=lo+Math.imul(al2,bl1)|0;mid=mid+Math.imul(al2,bh1)|0;mid=mid+Math.imul(ah2,bl1)|0;hi=hi+Math.imul(ah2,bh1)|0;lo=lo+Math.imul(al1,bl2)|0;mid=mid+Math.imul(al1,bh2)|0;mid=mid+Math.imul(ah1,bl2)|0;hi=hi+Math.imul(ah1,bh2)|0;lo=lo+Math.imul(al0,bl3)|0;mid=mid+Math.imul(al0,bh3)|0;mid=mid+Math.imul(ah0,bl3)|0;hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0;w3&=67108863;lo=Math.imul(al4,bl0);mid=Math.imul(al4,bh0);mid=mid+Math.imul(ah4,bl0)|0;hi=Math.imul(ah4,bh0);lo=lo+Math.imul(al3,bl1)|0;mid=mid+Math.imul(al3,bh1)|0;mid=mid+Math.imul(ah3,bl1)|0;hi=hi+Math.imul(ah3,bh1)|0;lo=lo+Math.imul(al2,bl2)|0;mid=mid+Math.imul(al2,bh2)|0;mid=mid+Math.imul(ah2,bl2)|0;hi=hi+Math.imul(ah2,bh2)|0;lo=lo+Math.imul(al1,bl3)|0;mid=mid+Math.imul(al1,bh3)|0;mid=mid+Math.imul(ah1,bl3)|0;hi=hi+Math.imul(ah1,bh3)|0;lo=lo+Math.imul(al0,bl4)|0;mid=mid+Math.imul(al0,bh4)|0;mid=mid+Math.imul(ah0,bl4)|0;hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0;w4&=67108863;lo=Math.imul(al5,bl0);mid=Math.imul(al5,bh0);mid=mid+Math.imul(ah5,bl0)|0;hi=Math.imul(ah5,bh0);lo=lo+Math.imul(al4,bl1)|0;mid=mid+Math.imul(al4,bh1)|0;mid=mid+Math.imul(ah4,bl1)|0;hi=hi+Math.imul(ah4,bh1)|0;lo=lo+Math.imul(al3,bl2)|0;mid=mid+Math.imul(al3,bh2)|0;mid=mid+Math.imul(ah3,bl2)|0;hi=hi+Math.imul(ah3,bh2)|0;lo=lo+Math.imul(al2,bl3)|0;mid=mid+Math.imul(al2,bh3)|0;mid=mid+Math.imul(ah2,bl3)|0;hi=hi+Math.imul(ah2,bh3)|0;lo=lo+Math.imul(al1,bl4)|0;mid=mid+Math.imul(al1,bh4)|0;mid=mid+Math.imul(ah1,bl4)|0;hi=hi+Math.imul(ah1,bh4)|0;lo=lo+Math.imul(al0,bl5)|0;mid=mid+Math.imul(al0,bh5)|0;mid=mid+Math.imul(ah0,bl5)|0;hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0;w5&=67108863;lo=Math.imul(al6,bl0);mid=Math.imul(al6,bh0);mid=mid+Math.imul(ah6,bl0)|0;hi=Math.imul(ah6,bh0);lo=lo+Math.imul(al5,bl1)|0;mid=mid+Math.imul(al5,bh1)|0;mid=mid+Math.imul(ah5,bl1)|0;hi=hi+Math.imul(ah5,bh1)|0;lo=lo+Math.imul(al4,bl2)|0;mid=mid+Math.imul(al4,bh2)|0;mid=mid+Math.imul(ah4,bl2)|0;hi=hi+Math.imul(ah4,bh2)|0;lo=lo+Math.imul(al3,bl3)|0;mid=mid+Math.imul(al3,bh3)|0;mid=mid+Math.imul(ah3,bl3)|0;hi=hi+Math.imul(ah3,bh3)|0;lo=lo+Math.imul(al2,bl4)|0;mid=mid+Math.imul(al2,bh4)|0;mid=mid+Math.imul(ah2,bl4)|0;hi=hi+Math.imul(ah2,bh4)|0;lo=lo+Math.imul(al1,bl5)|0;mid=mid+Math.imul(al1,bh5)|0;mid=mid+Math.imul(ah1,bl5)|0;hi=hi+Math.imul(ah1,bh5)|0;lo=lo+Math.imul(al0,bl6)|0;mid=mid+Math.imul(al0,bh6)|0;mid=mid+Math.imul(ah0,bl6)|0;hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0;w6&=67108863;lo=Math.imul(al7,bl0);mid=Math.imul(al7,bh0);mid=mid+Math.imul(ah7,bl0)|0;hi=Math.imul(ah7,bh0);lo=lo+Math.imul(al6,bl1)|0;mid=mid+Math.imul(al6,bh1)|0;mid=mid+Math.imul(ah6,bl1)|0;hi=hi+Math.imul(ah6,bh1)|0;lo=lo+Math.imul(al5,bl2)|0;mid=mid+Math.imul(al5,bh2)|0;mid=mid+Math.imul(ah5,bl2)|0;hi=hi+Math.imul(ah5,bh2)|0;lo=lo+Math.imul(al4,bl3)|0;mid=mid+Math.imul(al4,bh3)|0;mid=mid+Math.imul(ah4,bl3)|0;hi=hi+Math.imul(ah4,bh3)|0;lo=lo+Math.imul(al3,bl4)|0;mid=mid+Math.imul(al3,bh4)|0;mid=mid+Math.imul(ah3,bl4)|0;hi=hi+Math.imul(ah3,bh4)|0;lo=lo+Math.imul(al2,bl5)|0;mid=mid+Math.imul(al2,bh5)|0;mid=mid+Math.imul(ah2,bl5)|0;hi=hi+Math.imul(ah2,bh5)|0;lo=lo+Math.imul(al1,bl6)|0;mid=mid+Math.imul(al1,bh6)|0;mid=mid+Math.imul(ah1,bl6)|0;hi=hi+Math.imul(ah1,bh6)|0;lo=lo+Math.imul(al0,bl7)|0;mid=mid+Math.imul(al0,bh7)|0;mid=mid+Math.imul(ah0,bl7)|0;hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0;w7&=67108863;lo=Math.imul(al8,bl0);mid=Math.imul(al8,bh0);mid=mid+Math.imul(ah8,bl0)|0;hi=Math.imul(ah8,bh0);lo=lo+Math.imul(al7,bl1)|0;mid=mid+Math.imul(al7,bh1)|0;mid=mid+Math.imul(ah7,bl1)|0;hi=hi+Math.imul(ah7,bh1)|0;lo=lo+Math.imul(al6,bl2)|0;mid=mid+Math.imul(al6,bh2)|0;mid=mid+Math.imul(ah6,bl2)|0;hi=hi+Math.imul(ah6,bh2)|0;lo=lo+Math.imul(al5,bl3)|0;mid=mid+Math.imul(al5,bh3)|0;mid=mid+Math.imul(ah5,bl3)|0;hi=hi+Math.imul(ah5,bh3)|0;lo=lo+Math.imul(al4,bl4)|0;mid=mid+Math.imul(al4,bh4)|0;mid=mid+Math.imul(ah4,bl4)|0;hi=hi+Math.imul(ah4,bh4)|0;lo=lo+Math.imul(al3,bl5)|0;mid=mid+Math.imul(al3,bh5)|0;mid=mid+Math.imul(ah3,bl5)|0;hi=hi+Math.imul(ah3,bh5)|0;lo=lo+Math.imul(al2,bl6)|0;mid=mid+Math.imul(al2,bh6)|0;mid=mid+Math.imul(ah2,bl6)|0;hi=hi+Math.imul(ah2,bh6)|0;lo=lo+Math.imul(al1,bl7)|0;mid=mid+Math.imul(al1,bh7)|0;mid=mid+Math.imul(ah1,bl7)|0;hi=hi+Math.imul(ah1,bh7)|0;lo=lo+Math.imul(al0,bl8)|0;mid=mid+Math.imul(al0,bh8)|0;mid=mid+Math.imul(ah0,bl8)|0;hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0;w8&=67108863;lo=Math.imul(al9,bl0);mid=Math.imul(al9,bh0);mid=mid+Math.imul(ah9,bl0)|0;hi=Math.imul(ah9,bh0);lo=lo+Math.imul(al8,bl1)|0;mid=mid+Math.imul(al8,bh1)|0;mid=mid+Math.imul(ah8,bl1)|0;hi=hi+Math.imul(ah8,bh1)|0;lo=lo+Math.imul(al7,bl2)|0;mid=mid+Math.imul(al7,bh2)|0;mid=mid+Math.imul(ah7,bl2)|0;hi=hi+Math.imul(ah7,bh2)|0;lo=lo+Math.imul(al6,bl3)|0;mid=mid+Math.imul(al6,bh3)|0;mid=mid+Math.imul(ah6,bl3)|0;hi=hi+Math.imul(ah6,bh3)|0;lo=lo+Math.imul(al5,bl4)|0;mid=mid+Math.imul(al5,bh4)|0;mid=mid+Math.imul(ah5,bl4)|0;hi=hi+Math.imul(ah5,bh4)|0;lo=lo+Math.imul(al4,bl5)|0;mid=mid+Math.imul(al4,bh5)|0;mid=mid+Math.imul(ah4,bl5)|0;hi=hi+Math.imul(ah4,bh5)|0;lo=lo+Math.imul(al3,bl6)|0;mid=mid+Math.imul(al3,bh6)|0;mid=mid+Math.imul(ah3,bl6)|0;hi=hi+Math.imul(ah3,bh6)|0;lo=lo+Math.imul(al2,bl7)|0;mid=mid+Math.imul(al2,bh7)|0;mid=mid+Math.imul(ah2,bl7)|0;hi=hi+Math.imul(ah2,bh7)|0;lo=lo+Math.imul(al1,bl8)|0;mid=mid+Math.imul(al1,bh8)|0;mid=mid+Math.imul(ah1,bl8)|0;hi=hi+Math.imul(ah1,bh8)|0;lo=lo+Math.imul(al0,bl9)|0;mid=mid+Math.imul(al0,bh9)|0;mid=mid+Math.imul(ah0,bl9)|0;hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0;w9&=67108863;lo=Math.imul(al9,bl1);mid=Math.imul(al9,bh1);mid=mid+Math.imul(ah9,bl1)|0;hi=Math.imul(ah9,bh1);lo=lo+Math.imul(al8,bl2)|0;mid=mid+Math.imul(al8,bh2)|0;mid=mid+Math.imul(ah8,bl2)|0;hi=hi+Math.imul(ah8,bh2)|0;lo=lo+Math.imul(al7,bl3)|0;mid=mid+Math.imul(al7,bh3)|0;mid=mid+Math.imul(ah7,bl3)|0;hi=hi+Math.imul(ah7,bh3)|0;lo=lo+Math.imul(al6,bl4)|0;mid=mid+Math.imul(al6,bh4)|0;mid=mid+Math.imul(ah6,bl4)|0;hi=hi+Math.imul(ah6,bh4)|0;lo=lo+Math.imul(al5,bl5)|0;mid=mid+Math.imul(al5,bh5)|0;mid=mid+Math.imul(ah5,bl5)|0;hi=hi+Math.imul(ah5,bh5)|0;lo=lo+Math.imul(al4,bl6)|0;mid=mid+Math.imul(al4,bh6)|0;mid=mid+Math.imul(ah4,bl6)|0;hi=hi+Math.imul(ah4,bh6)|0;lo=lo+Math.imul(al3,bl7)|0;mid=mid+Math.imul(al3,bh7)|0;mid=mid+Math.imul(ah3,bl7)|0;hi=hi+Math.imul(ah3,bh7)|0;lo=lo+Math.imul(al2,bl8)|0;mid=mid+Math.imul(al2,bh8)|0;mid=mid+Math.imul(ah2,bl8)|0;hi=hi+Math.imul(ah2,bh8)|0;lo=lo+Math.imul(al1,bl9)|0;mid=mid+Math.imul(al1,bh9)|0;mid=mid+Math.imul(ah1,bl9)|0;hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0;w10&=67108863;lo=Math.imul(al9,bl2);mid=Math.imul(al9,bh2);mid=mid+Math.imul(ah9,bl2)|0;hi=Math.imul(ah9,bh2);lo=lo+Math.imul(al8,bl3)|0;mid=mid+Math.imul(al8,bh3)|0;mid=mid+Math.imul(ah8,bl3)|0;hi=hi+Math.imul(ah8,bh3)|0;lo=lo+Math.imul(al7,bl4)|0;mid=mid+Math.imul(al7,bh4)|0;mid=mid+Math.imul(ah7,bl4)|0;hi=hi+Math.imul(ah7,bh4)|0;lo=lo+Math.imul(al6,bl5)|0;mid=mid+Math.imul(al6,bh5)|0;mid=mid+Math.imul(ah6,bl5)|0;hi=hi+Math.imul(ah6,bh5)|0;lo=lo+Math.imul(al5,bl6)|0;mid=mid+Math.imul(al5,bh6)|0;mid=mid+Math.imul(ah5,bl6)|0;hi=hi+Math.imul(ah5,bh6)|0;lo=lo+Math.imul(al4,bl7)|0;mid=mid+Math.imul(al4,bh7)|0;mid=mid+Math.imul(ah4,bl7)|0;hi=hi+Math.imul(ah4,bh7)|0;lo=lo+Math.imul(al3,bl8)|0;mid=mid+Math.imul(al3,bh8)|0;mid=mid+Math.imul(ah3,bl8)|0;hi=hi+Math.imul(ah3,bh8)|0;lo=lo+Math.imul(al2,bl9)|0;mid=mid+Math.imul(al2,bh9)|0;mid=mid+Math.imul(ah2,bl9)|0;hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0;w11&=67108863;lo=Math.imul(al9,bl3);mid=Math.imul(al9,bh3);mid=mid+Math.imul(ah9,bl3)|0;hi=Math.imul(ah9,bh3);lo=lo+Math.imul(al8,bl4)|0;mid=mid+Math.imul(al8,bh4)|0;mid=mid+Math.imul(ah8,bl4)|0;hi=hi+Math.imul(ah8,bh4)|0;lo=lo+Math.imul(al7,bl5)|0;mid=mid+Math.imul(al7,bh5)|0;mid=mid+Math.imul(ah7,bl5)|0;hi=hi+Math.imul(ah7,bh5)|0;lo=lo+Math.imul(al6,bl6)|0;mid=mid+Math.imul(al6,bh6)|0;mid=mid+Math.imul(ah6,bl6)|0;hi=hi+Math.imul(ah6,bh6)|0;lo=lo+Math.imul(al5,bl7)|0;mid=mid+Math.imul(al5,bh7)|0;mid=mid+Math.imul(ah5,bl7)|0;hi=hi+Math.imul(ah5,bh7)|0;lo=lo+Math.imul(al4,bl8)|0;mid=mid+Math.imul(al4,bh8)|0;mid=mid+Math.imul(ah4,bl8)|0;hi=hi+Math.imul(ah4,bh8)|0;lo=lo+Math.imul(al3,bl9)|0;mid=mid+Math.imul(al3,bh9)|0;mid=mid+Math.imul(ah3,bl9)|0;hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0;w12&=67108863;lo=Math.imul(al9,bl4);mid=Math.imul(al9,bh4);mid=mid+Math.imul(ah9,bl4)|0;hi=Math.imul(ah9,bh4);lo=lo+Math.imul(al8,bl5)|0;mid=mid+Math.imul(al8,bh5)|0;mid=mid+Math.imul(ah8,bl5)|0;hi=hi+Math.imul(ah8,bh5)|0;lo=lo+Math.imul(al7,bl6)|0;mid=mid+Math.imul(al7,bh6)|0;mid=mid+Math.imul(ah7,bl6)|0;hi=hi+Math.imul(ah7,bh6)|0;lo=lo+Math.imul(al6,bl7)|0;mid=mid+Math.imul(al6,bh7)|0;mid=mid+Math.imul(ah6,bl7)|0;hi=hi+Math.imul(ah6,bh7)|0;lo=lo+Math.imul(al5,bl8)|0;mid=mid+Math.imul(al5,bh8)|0;mid=mid+Math.imul(ah5,bl8)|0;hi=hi+Math.imul(ah5,bh8)|0;lo=lo+Math.imul(al4,bl9)|0;mid=mid+Math.imul(al4,bh9)|0;mid=mid+Math.imul(ah4,bl9)|0;hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0;w13&=67108863;lo=Math.imul(al9,bl5);mid=Math.imul(al9,bh5);mid=mid+Math.imul(ah9,bl5)|0;hi=Math.imul(ah9,bh5);lo=lo+Math.imul(al8,bl6)|0;mid=mid+Math.imul(al8,bh6)|0;mid=mid+Math.imul(ah8,bl6)|0;hi=hi+Math.imul(ah8,bh6)|0;lo=lo+Math.imul(al7,bl7)|0;mid=mid+Math.imul(al7,bh7)|0;mid=mid+Math.imul(ah7,bl7)|0;hi=hi+Math.imul(ah7,bh7)|0;lo=lo+Math.imul(al6,bl8)|0;mid=mid+Math.imul(al6,bh8)|0;mid=mid+Math.imul(ah6,bl8)|0;hi=hi+Math.imul(ah6,bh8)|0;lo=lo+Math.imul(al5,bl9)|0;mid=mid+Math.imul(al5,bh9)|0;mid=mid+Math.imul(ah5,bl9)|0;hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0;w14&=67108863;lo=Math.imul(al9,bl6);mid=Math.imul(al9,bh6);mid=mid+Math.imul(ah9,bl6)|0;hi=Math.imul(ah9,bh6);lo=lo+Math.imul(al8,bl7)|0;mid=mid+Math.imul(al8,bh7)|0;mid=mid+Math.imul(ah8,bl7)|0;hi=hi+Math.imul(ah8,bh7)|0;lo=lo+Math.imul(al7,bl8)|0;mid=mid+Math.imul(al7,bh8)|0;mid=mid+Math.imul(ah7,bl8)|0;hi=hi+Math.imul(ah7,bh8)|0;lo=lo+Math.imul(al6,bl9)|0;mid=mid+Math.imul(al6,bh9)|0;mid=mid+Math.imul(ah6,bl9)|0;hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0;w15&=67108863;lo=Math.imul(al9,bl7);mid=Math.imul(al9,bh7);mid=mid+Math.imul(ah9,bl7)|0;hi=Math.imul(ah9,bh7);lo=lo+Math.imul(al8,bl8)|0;mid=mid+Math.imul(al8,bh8)|0;mid=mid+Math.imul(ah8,bl8)|0;hi=hi+Math.imul(ah8,bh8)|0;lo=lo+Math.imul(al7,bl9)|0;mid=mid+Math.imul(al7,bh9)|0;mid=mid+Math.imul(ah7,bl9)|0;hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0;w16&=67108863;lo=Math.imul(al9,bl8);mid=Math.imul(al9,bh8);mid=mid+Math.imul(ah9,bl8)|0;hi=Math.imul(ah9,bh8);lo=lo+Math.imul(al8,bl9)|0;mid=mid+Math.imul(al8,bh9)|0;mid=mid+Math.imul(ah8,bl9)|0;hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0;w17&=67108863;lo=Math.imul(al9,bl9);mid=Math.imul(al9,bh9);mid=mid+Math.imul(ah9,bl9)|0;hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w18>>>26)|0;w18&=67108863;o[0]=w0;o[1]=w1;o[2]=w2;o[3]=w3;o[4]=w4;o[5]=w5;o[6]=w6;o[7]=w7;o[8]=w8;o[9]=w9;o[10]=w10;o[11]=w11;o[12]=w12;o[13]=w13;o[14]=w14;o[15]=w15;o[16]=w16;o[17]=w17;o[18]=w18;if(c!==0){o[19]=c;out.length++}return out};if(!Math.imul){comb10MulTo=smallMulTo}function bigMulTo(self,num,out){out.negative=num.negative^self.negative;out.length=self.length+num.length;var carry=0;var hncarry=0;for(var k=0;k>>26)|0;hncarry+=ncarry>>>26;ncarry&=67108863}out.words[k]=rword;carry=ncarry;ncarry=hncarry}if(carry!==0){out.words[k]=carry}else{out.length--}return out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}BN.prototype.mulTo=function mulTo(num,out){var res;var len=this.length+num.length;if(this.length===10&&num.length===10){res=comb10MulTo(this,num,out)}else if(len<63){res=smallMulTo(this,num,out)}else if(len<1024){res=bigMulTo(this,num,out)}else{res=jumboMulTo(this,num,out)}return res};function FFTM(x,y){this.x=x;this.y=y}FFTM.prototype.makeRBT=function makeRBT(N){var t=new Array(N);var l=BN.prototype._countBits(N)-1;for(var i=0;i>=1}return rb};FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1){i++}return 1<>>13;rws[2*i+1]=carry&8191;carry=carry>>>13}for(i=2*len;i>=26;carry+=w/67108864|0;carry+=lo>>>26;this.words[i]=lo&67108863}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.muln=function muln(num){return this.clone().imuln(num)};BN.prototype.sqr=function sqr(){return this.mul(this)};BN.prototype.isqr=function isqr(){return this.imul(this.clone())};BN.prototype.pow=function pow(num){var w=toBitArray(num);if(w.length===0)return new BN(1);var res=this;for(var i=0;i=0);var r=bits%26;var s=(bits-r)/26;var carryMask=67108863>>>26-r<<26-r;var i;if(r!==0){var carry=0;for(i=0;i>>26-r}if(carry){this.words[i]=carry;this.length++}}if(s!==0){for(i=this.length-1;i>=0;i--){this.words[i+s]=this.words[i]}for(i=0;i=0);var h;if(hint){h=(hint-hint%26)/26}else{h=0}var r=bits%26;var s=Math.min((bits-r)/26,this.length);var mask=67108863^67108863>>>r<s){this.length-=s;for(i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r;carry=word&mask}if(maskedWords&&carry!==0){maskedWords.words[maskedWords.length++]=carry}if(this.length===0){this.words[0]=0;this.length=1}return this.strip()};BN.prototype.ishrn=function ishrn(bits,hint,extended){assert(this.negative===0);return this.iushrn(bits,hint,extended)};BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)};BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)};BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)};BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)};BN.prototype.testn=function testn(bit){assert(typeof bit==="number"&&bit>=0);var r=bit%26;var s=(bit-r)/26;var q=1<=0);var r=bits%26;var s=(bits-r)/26;assert(this.negative===0,"imaskn works only with positive numbers");if(this.length<=s){return this}if(r!==0){s++}this.length=Math.min(s,this.length);if(r!==0){var mask=67108863^67108863>>>r<=67108864;i++){this.words[i]-=67108864;if(i===this.length-1){this.words[i+1]=1}else{this.words[i+1]++}}this.length=Math.max(this.length,i+1);return this};BN.prototype.isubn=function isubn(num){assert(typeof num==="number");assert(num<67108864);if(num<0)return this.iaddn(-num);if(this.negative!==0){this.negative=0;this.iaddn(num);this.negative=1;return this}this.words[0]-=num;if(this.length===1&&this.words[0]<0){this.words[0]=-this.words[0];this.negative=1}else{for(var i=0;i>26)-(right/67108864|0);this.words[i+shift]=w&67108863}for(;i>26;this.words[i+shift]=w&67108863}if(carry===0)return this.strip();assert(carry===-1);carry=0;for(i=0;i>26;this.words[i]=w&67108863}this.negative=1;return this.strip()};BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length;var a=this.clone();var b=num;var bhi=b.words[b.length-1]|0;var bhiBits=this._countBits(bhi);shift=26-bhiBits;if(shift!==0){b=b.ushln(shift);a.iushln(shift);bhi=b.words[b.length-1]|0}var m=a.length-b.length;var q;if(mode!=="mod"){q=new BN(null);q.length=m+1;q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);qj=Math.min(qj/bhi|0,67108863);a._ishlnsubmul(b,qj,j);while(a.negative!==0){qj--;a.negative=0;a._ishlnsubmul(b,1,j);if(!a.isZero()){a.negative^=1}}if(q){q.words[j]=qj}}if(q){q.strip()}a.strip();if(mode!=="div"&&shift!==0){a.iushrn(shift)}return{div:q||null,mod:a}};BN.prototype.divmod=function divmod(num,mode,positive){assert(!num.isZero());if(this.isZero()){return{div:new BN(0),mod:new BN(0)}}var div,mod,res;if(this.negative!==0&&num.negative===0){res=this.neg().divmod(num,mode);if(mode!=="mod"){div=res.div.neg()}if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.iadd(num)}}return{div:div,mod:mod}}if(this.negative===0&&num.negative!==0){res=this.divmod(num.neg(),mode);if(mode!=="mod"){div=res.div.neg()}return{div:div,mod:res.mod}}if((this.negative&num.negative)!==0){res=this.neg().divmod(num.neg(),mode);if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.isub(num)}}return{div:res.div,mod:mod}}if(num.length>this.length||this.cmp(num)<0){return{div:new BN(0),mod:this}}if(num.length===1){if(mode==="div"){return{div:this.divn(num.words[0]),mod:null}}if(mode==="mod"){return{div:null,mod:new BN(this.modn(num.words[0]))}}return{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}}return this._wordDiv(num,mode)};BN.prototype.div=function div(num){return this.divmod(num,"div",false).div};BN.prototype.mod=function mod(num){return this.divmod(num,"mod",false).mod};BN.prototype.umod=function umod(num){return this.divmod(num,"mod",true).mod};BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0?dm.mod.isub(num):dm.mod;var half=num.ushrn(1);var r2=num.andln(1);var cmp=mod.cmp(half);if(cmp<0||r2===1&&cmp===0)return dm.div;return dm.div.negative!==0?dm.div.isubn(1):dm.div.iaddn(1)};BN.prototype.modn=function modn(num){assert(num<=67108863);var p=(1<<26)%num;var acc=0;for(var i=this.length-1;i>=0;i--){acc=(p*acc+(this.words[i]|0))%num}return acc};BN.prototype.idivn=function idivn(num){assert(num<=67108863);var carry=0;for(var i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0;carry=w%num}return this.strip()};BN.prototype.divn=function divn(num){return this.clone().idivn(num)};BN.prototype.egcd=function egcd(p){assert(p.negative===0);assert(!p.isZero());var x=this;var y=p.clone();if(x.negative!==0){x=x.umod(p)}else{x=x.clone()}var A=new BN(1);var B=new BN(0);var C=new BN(0);var D=new BN(1);var g=0;while(x.isEven()&&y.isEven()){x.iushrn(1);y.iushrn(1);++g}var yp=y.clone();var xp=x.clone();while(!x.isZero()){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){x.iushrn(i);while(i-- >0){if(A.isOdd()||B.isOdd()){A.iadd(yp);B.isub(xp)}A.iushrn(1);B.iushrn(1)}}for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){y.iushrn(j);while(j-- >0){if(C.isOdd()||D.isOdd()){C.iadd(yp);D.isub(xp)}C.iushrn(1);D.iushrn(1)}}if(x.cmp(y)>=0){x.isub(y);A.isub(C);B.isub(D)}else{y.isub(x);C.isub(A);D.isub(B)}}return{a:C,b:D,gcd:y.iushln(g)}};BN.prototype._invmp=function _invmp(p){assert(p.negative===0);assert(!p.isZero());var a=this;var b=p.clone();if(a.negative!==0){a=a.umod(p)}else{a=a.clone()}var x1=new BN(1);var x2=new BN(0);var delta=b.clone();while(a.cmpn(1)>0&&b.cmpn(1)>0){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){a.iushrn(i);while(i-- >0){if(x1.isOdd()){x1.iadd(delta)}x1.iushrn(1)}}for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){b.iushrn(j);while(j-- >0){if(x2.isOdd()){x2.iadd(delta)}x2.iushrn(1)}}if(a.cmp(b)>=0){a.isub(b);x1.isub(x2)}else{b.isub(a);x2.isub(x1)}}var res;if(a.cmpn(1)===0){res=x1}else{res=x2}if(res.cmpn(0)<0){res.iadd(p)}return res};BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone();var b=num.clone();a.negative=0;b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++){a.iushrn(1);b.iushrn(1)}do{while(a.isEven()){a.iushrn(1)}while(b.isEven()){b.iushrn(1)}var r=a.cmp(b);if(r<0){var t=a;a=b;b=t}else if(r===0||b.cmpn(1)===0){break}a.isub(b)}while(true);return b.iushln(shift)};BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)};BN.prototype.isEven=function isEven(){return(this.words[0]&1)===0};BN.prototype.isOdd=function isOdd(){return(this.words[0]&1)===1};BN.prototype.andln=function andln(num){return this.words[0]&num};BN.prototype.bincn=function bincn(bit){assert(typeof bit==="number");var r=bit%26;var s=(bit-r)/26;var q=1<>>26;w&=67108863;this.words[i]=w}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.isZero=function isZero(){return this.length===1&&this.words[0]===0};BN.prototype.cmpn=function cmpn(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1){res=1}else{if(negative){num=-num}assert(num<=67108863,"Number is too big");var w=this.words[0]|0;res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0;var b=num.words[i]|0;if(a===b)continue;if(ab){res=1}break}return res};BN.prototype.gtn=function gtn(num){return this.cmpn(num)===1};BN.prototype.gt=function gt(num){return this.cmp(num)===1};BN.prototype.gten=function gten(num){return this.cmpn(num)>=0};BN.prototype.gte=function gte(num){return this.cmp(num)>=0};BN.prototype.ltn=function ltn(num){return this.cmpn(num)===-1};BN.prototype.lt=function lt(num){return this.cmp(num)===-1};BN.prototype.lten=function lten(num){return this.cmpn(num)<=0};BN.prototype.lte=function lte(num){return this.cmp(num)<=0};BN.prototype.eqn=function eqn(num){return this.cmpn(num)===0};BN.prototype.eq=function eq(num){return this.cmp(num)===0};BN.red=function red(num){return new Red(num)};BN.prototype.toRed=function toRed(ctx){assert(!this.red,"Already a number in reduction context");assert(this.negative===0,"red works only with positives");return ctx.convertTo(this)._forceRed(ctx)};BN.prototype.fromRed=function fromRed(){assert(this.red,"fromRed works only with numbers in reduction context");return this.red.convertFrom(this)};BN.prototype._forceRed=function _forceRed(ctx){ +this.red=ctx;return this};BN.prototype.forceRed=function forceRed(ctx){assert(!this.red,"Already a number in reduction context");return this._forceRed(ctx)};BN.prototype.redAdd=function redAdd(num){assert(this.red,"redAdd works only with red numbers");return this.red.add(this,num)};BN.prototype.redIAdd=function redIAdd(num){assert(this.red,"redIAdd works only with red numbers");return this.red.iadd(this,num)};BN.prototype.redSub=function redSub(num){assert(this.red,"redSub works only with red numbers");return this.red.sub(this,num)};BN.prototype.redISub=function redISub(num){assert(this.red,"redISub works only with red numbers");return this.red.isub(this,num)};BN.prototype.redShl=function redShl(num){assert(this.red,"redShl works only with red numbers");return this.red.shl(this,num)};BN.prototype.redMul=function redMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.mul(this,num)};BN.prototype.redIMul=function redIMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.imul(this,num)};BN.prototype.redSqr=function redSqr(){assert(this.red,"redSqr works only with red numbers");this.red._verify1(this);return this.red.sqr(this)};BN.prototype.redISqr=function redISqr(){assert(this.red,"redISqr works only with red numbers");this.red._verify1(this);return this.red.isqr(this)};BN.prototype.redSqrt=function redSqrt(){assert(this.red,"redSqrt works only with red numbers");this.red._verify1(this);return this.red.sqrt(this)};BN.prototype.redInvm=function redInvm(){assert(this.red,"redInvm works only with red numbers");this.red._verify1(this);return this.red.invm(this)};BN.prototype.redNeg=function redNeg(){assert(this.red,"redNeg works only with red numbers");this.red._verify1(this);return this.red.neg(this)};BN.prototype.redPow=function redPow(num){assert(this.red&&!num.red,"redPow(normalNum)");this.red._verify1(this);return this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name;this.p=new BN(p,16);this.n=this.p.bitLength();this.k=new BN(1).iushln(this.n).isub(this.p);this.tmp=this._tmp()}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);tmp.words=new Array(Math.ceil(this.n/13));return tmp};MPrime.prototype.ireduce=function ireduce(num){var r=num;var rlen;do{this.split(r,this.tmp);r=this.imulK(r);r=r.iadd(this.tmp);rlen=r.bitLength()}while(rlen>this.n);var cmp=rlen0){r.isub(this.p)}else{r.strip()}return r};MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)};MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)};function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}inherits(K256,MPrime);K256.prototype.split=function split(input,output){var mask=4194303;var outLen=Math.min(input.length,9);for(var i=0;i>>22;prev=next}prev>>>=22;input.words[i-10]=prev;if(prev===0&&input.length>10){input.length-=10}else{input.length-=9}};K256.prototype.imulK=function imulK(num){num.words[num.length]=0;num.words[num.length+1]=0;num.length+=2;var lo=0;for(var i=0;i>>=26;num.words[i]=lo;carry=hi}if(carry!==0){num.words[num.length++]=carry}return num};BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if(name==="k256"){prime=new K256}else if(name==="p224"){prime=new P224}else if(name==="p192"){prime=new P192}else if(name==="p25519"){prime=new P25519}else{throw new Error("Unknown prime "+name)}primes[name]=prime;return prime};function Red(m){if(typeof m==="string"){var prime=BN._prime(m);this.m=prime.p;this.prime=prime}else{assert(m.gtn(1),"modulus must be greater than 1");this.m=m;this.prime=null}}Red.prototype._verify1=function _verify1(a){assert(a.negative===0,"red works only with positives");assert(a.red,"red works only with red numbers")};Red.prototype._verify2=function _verify2(a,b){assert((a.negative|b.negative)===0,"red works only with positives");assert(a.red&&a.red===b.red,"red works only with red numbers")};Red.prototype.imod=function imod(a){if(this.prime)return this.prime.ireduce(a)._forceRed(this);return a.umod(this.m)._forceRed(this)};Red.prototype.neg=function neg(a){if(a.isZero()){return a.clone()}return this.m.sub(a)._forceRed(this)};Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res._forceRed(this)};Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res};Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res._forceRed(this)};Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res};Red.prototype.shl=function shl(a,num){this._verify1(a);return this.imod(a.ushln(num))};Red.prototype.imul=function imul(a,b){this._verify2(a,b);return this.imod(a.imul(b))};Red.prototype.mul=function mul(a,b){this._verify2(a,b);return this.imod(a.mul(b))};Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())};Red.prototype.sqr=function sqr(a){return this.mul(a,a)};Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);assert(mod3%2===1);if(mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}var q=this.m.subn(1);var s=0;while(!q.isZero()&&q.andln(1)===0){s++;q.iushrn(1)}assert(!q.isZero());var one=new BN(1).toRed(this);var nOne=one.redNeg();var lpow=this.m.subn(1).iushrn(1);var z=this.m.bitLength();z=new BN(2*z*z).toRed(this);while(this.pow(z,lpow).cmp(nOne)!==0){z.redIAdd(nOne)}var c=this.pow(z,q);var r=this.pow(a,q.addn(1).iushrn(1));var t=this.pow(a,q);var m=s;while(t.cmp(one)!==0){var tmp=t;for(var i=0;tmp.cmp(one)!==0;i++){tmp=tmp.redSqr()}assert(i=0;i--){var word=num.words[i];for(var j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]){res=this.sqr(res)}if(bit===0&¤t===0){currentLen=0;continue}current<<=1;current|=bit;currentLen++;if(currentLen!==windowSize&&(i!==0||j!==0))continue;res=this.mul(res,wnd[current]);currentLen=0;current=0}start=26}return res};Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r};Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();res.red=null;return res};BN.mont=function mont(num){return new Mont(num)};function Mont(m){Red.call(this,m);this.shift=this.m.bitLength();if(this.shift%26!==0){this.shift+=26-this.shift%26}this.r=new BN(1).iushln(this.shift);this.r2=this.imod(this.r.sqr());this.rinv=this.r._invmp(this.m);this.minv=this.rinv.mul(this.r).isubn(1).div(this.m);this.minv=this.minv.umod(this.r);this.minv=this.r.sub(this.minv)}inherits(Mont,Red);Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))};Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));r.red=null;return r};Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero()){a.words[0]=0;a.length=1;return a}var t=a.imul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module==="undefined"||module,this)},{}],40:[function(require,module,exports){(function(Buffer){var bn=require("bn.js");var randomBytes=require("randombytes");module.exports=crt;function blind(priv){var r=getr(priv);var blinder=r.toRed(bn.mont(priv.modulus)).redPow(new bn(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function crt(msg,priv){var blinds=blind(priv);var len=priv.modulus.byteLength();var mod=bn.mont(priv.modulus);var blinded=new bn(msg).mul(blinds.blinder).umod(priv.modulus);var c1=blinded.toRed(bn.mont(priv.prime1));var c2=blinded.toRed(bn.mont(priv.prime2));var qinv=priv.coefficient;var p=priv.prime1;var q=priv.prime2;var m1=c1.redPow(priv.exponent1);var m2=c2.redPow(priv.exponent2);m1=m1.fromRed();m2=m2.fromRed();var h=m1.isub(m2).imul(qinv).umod(p);h.imul(q);m2.iadd(h);return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false,len))}crt.getr=getr;function getr(priv){var len=priv.modulus.byteLength();var r=new bn(randomBytes(len));while(r.cmp(priv.modulus)>=0||!r.umod(priv.prime1)||!r.umod(priv.prime2)){r=new bn(randomBytes(len))}return r}}).call(this,require("buffer").Buffer)},{"bn.js":39,buffer:2,randombytes:198}],41:[function(require,module,exports){"use strict";var elliptic=exports;elliptic.version=require("../package.json").version;elliptic.utils=require("./elliptic/utils");elliptic.rand=require("brorand");elliptic.hmacDRBG=require("./elliptic/hmac-drbg");elliptic.curve=require("./elliptic/curve");elliptic.curves=require("./elliptic/curves");elliptic.ec=require("./elliptic/ec");elliptic.eddsa=require("./elliptic/eddsa")},{"../package.json":64,"./elliptic/curve":44,"./elliptic/curves":47,"./elliptic/ec":48,"./elliptic/eddsa":51,"./elliptic/hmac-drbg":54,"./elliptic/utils":56,brorand:57}],42:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var getNAF=utils.getNAF;var getJSF=utils.getJSF;var assert=utils.assert;function BaseCurve(type,conf){this.type=type;this.p=new BN(conf.p,16);this.red=conf.prime?BN.red(conf.prime):BN.mont(this.p);this.zero=new BN(0).toRed(this.red);this.one=new BN(1).toRed(this.red);this.two=new BN(2).toRed(this.red);this.n=conf.n&&new BN(conf.n,16);this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed);this._wnafT1=new Array(4);this._wnafT2=new Array(4);this._wnafT3=new Array(4);this._wnafT4=new Array(4);var adjustCount=this.n&&this.p.div(this.n);if(!adjustCount||adjustCount.cmpn(100)>0){this.redN=null}else{this._maxwellTrick=true;this.redN=this.n.toRed(this.red)}}module.exports=BaseCurve;BaseCurve.prototype.point=function point(){throw new Error("Not implemented")};BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")};BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert(p.precomputed);var doubles=p._getDoubles();var naf=getNAF(k,1);var I=(1<=j;k--)nafW=(nafW<<1)+naf[k];repr.push(nafW)}var a=this.jpoint(null,null,null);var b=this.jpoint(null,null,null);for(var i=I;i>0;i--){for(var j=0;j=0;i--){for(var k=0;i>=0&&naf[i]===0;i--)k++;if(i>=0)k++;acc=acc.dblp(k);if(i<0)break;var z=naf[i];assert(z!==0);if(p.type==="affine"){if(z>0)acc=acc.mixedAdd(wnd[z-1>>1]);else acc=acc.mixedAdd(wnd[-z-1>>1].neg())}else{if(z>0)acc=acc.add(wnd[z-1>>1]);else acc=acc.add(wnd[-z-1>>1].neg())}}return p.type==="affine"?acc.toP():acc};BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1;var wnd=this._wnafT2;var naf=this._wnafT3;var max=0;for(var i=0;i=1;i-=2){var a=i-1;var b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a]);naf[b]=getNAF(coeffs[b],wndWidth[b]);max=Math.max(naf[a].length,max);max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];if(points[a].y.cmp(points[b].y)===0){comb[1]=points[a].add(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}else if(points[a].y.cmp(points[b].y.redNeg())===0){comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].add(points[b].neg())}else{comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}var index=[-3,-1,-5,-7,0,7,5,1,3];var jsf=getJSF(coeffs[a],coeffs[b]);max=Math.max(jsf[0].length,max);naf[a]=new Array(max);naf[b]=new Array(max);for(var j=0;j=0;i--){var k=0;while(i>=0){var zero=true;for(var j=0;j=0)k++;acc=acc.dblp(k);if(i<0)break;for(var j=0;j0)p=wnd[j][z-1>>1];else if(z<0)p=wnd[j][-z-1>>1].neg();if(p.type==="affine")acc=acc.mixedAdd(p);else acc=acc.add(p)}}for(var i=0;i=Math.ceil((k.bitLength()+1)/doubles.step)};BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;var doubles=[this];var acc=this;for(var i=0;i";return""};Point.prototype.isInfinity=function isInfinity(){return this.x.cmpn(0)===0&&this.y.cmp(this.z)===0};Point.prototype._extDbl=function _extDbl(){var a=this.x.redSqr();var b=this.y.redSqr();var c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a);var e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);var g=d.redAdd(b);var f=g.redSub(c);var h=d.redSub(b);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projDbl=function _projDbl(){var b=this.x.redAdd(this.y).redSqr();var c=this.x.redSqr();var d=this.y.redSqr();var nx;var ny;var nz;if(this.curve.twisted){var e=this.curve._mulA(c);var f=e.redAdd(d);if(this.zOne){nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));ny=f.redMul(e.redSub(d));nz=f.redSqr().redSub(f).redSub(f)}else{var h=this.z.redSqr();var j=f.redSub(h).redISub(h);nx=b.redSub(c).redISub(d).redMul(j);ny=f.redMul(e.redSub(d));nz=f.redMul(j)}}else{var e=c.redAdd(d);var h=this.curve._mulC(this.c.redMul(this.z)).redSqr();var j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j);ny=this.curve._mulC(e).redMul(c.redISub(d));nz=e.redMul(j)}return this.curve.point(nx,ny,nz)};Point.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.extended)return this._extDbl();else return this._projDbl()};Point.prototype._extAdd=function _extAdd(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x));var b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));var c=this.t.redMul(this.curve.dd).redMul(p.t);var d=this.z.redMul(p.z.redAdd(p.z));var e=b.redSub(a);var f=d.redSub(c);var g=d.redAdd(c);var h=b.redAdd(a);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projAdd=function _projAdd(p){var a=this.z.redMul(p.z);var b=a.redSqr();var c=this.x.redMul(p.x);var d=this.y.redMul(p.y);var e=this.curve.d.redMul(c).redMul(d);var f=b.redSub(e);var g=b.redAdd(e);var tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);var nx=a.redMul(f).redMul(tmp);var ny;var nz;if(this.curve.twisted){ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));nz=f.redMul(g)}else{ny=a.redMul(g).redMul(d.redSub(c));nz=this.curve._mulC(f).redMul(g)}return this.curve.point(nx,ny,nz)};Point.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;if(this.curve.extended)return this._extAdd(p);else return this._projAdd(p)};Point.prototype.mul=function mul(k){if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,false)};Point.prototype.jmulAdd=function jmulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,true)};Point.prototype.normalize=function normalize(){if(this.zOne)return this;var zi=this.z.redInvm();this.x=this.x.redMul(zi);this.y=this.y.redMul(zi);if(this.t)this.t=this.t.redMul(zi);this.z=this.curve.one;this.zOne=true;return this};Point.prototype.neg=function neg(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};Point.prototype.getY=function getY(){this.normalize();return this.y.fromRed()};Point.prototype.eq=function eq(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0};Point.prototype.eqXToP=function eqXToP(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(this.z);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}return false};Point.prototype.toP=Point.prototype.normalize;Point.prototype.mixedAdd=Point.prototype.add},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:200}],44:[function(require,module,exports){"use strict";var curve=exports;curve.base=require("./base");curve.short=require("./short");curve.mont=require("./mont");curve.edwards=require("./edwards")},{"./base":42,"./edwards":43,"./mont":45,"./short":46}],45:[function(require,module,exports){"use strict";var curve=require("../curve");var BN=require("bn.js");var inherits=require("inherits");var Base=curve.base;var elliptic=require("../../elliptic");var utils=elliptic.utils;function MontCurve(conf){Base.call(this,"mont",conf);this.a=new BN(conf.a,16).toRed(this.red);this.b=new BN(conf.b,16).toRed(this.red);this.i4=new BN(4).toRed(this.red).redInvm();this.two=new BN(2).toRed(this.red);this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits(MontCurve,Base);module.exports=MontCurve;MontCurve.prototype.validate=function validate(point){var x=point.normalize().x;var x2=x.redSqr();var rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);var y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point(curve,x,z){Base.BasePoint.call(this,curve,"projective");if(x===null&&z===null){this.x=this.curve.one;this.z=this.curve.zero}else{this.x=new BN(x,16);this.z=new BN(z,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red)}}inherits(Point,Base.BasePoint);MontCurve.prototype.decodePoint=function decodePoint(bytes,enc){return this.point(utils.toArray(bytes,enc),1)};MontCurve.prototype.point=function point(x,z){return new Point(this,x,z)};MontCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)};Point.prototype.precompute=function precompute(){};Point.prototype._encode=function _encode(){return this.getX().toArray("be",this.curve.p.byteLength())};Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"";return""};Point.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};Point.prototype.dbl=function dbl(){var a=this.x.redAdd(this.z);var aa=a.redSqr();var b=this.x.redSub(this.z);var bb=b.redSqr();var c=aa.redSub(bb);var nx=aa.redMul(bb);var nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)};Point.prototype.add=function add(){throw new Error("Not supported on Montgomery curve")};Point.prototype.diffAdd=function diffAdd(p,diff){var a=this.x.redAdd(this.z);var b=this.x.redSub(this.z);var c=p.x.redAdd(p.z);var d=p.x.redSub(p.z);var da=d.redMul(a);var cb=c.redMul(b);var nx=diff.z.redMul(da.redAdd(cb).redSqr());var nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)};Point.prototype.mul=function mul(k){var t=k.clone();var a=this;var b=this.curve.point(null,null);var c=this;for(var bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--){if(bits[i]===0){a=a.diffAdd(b,c);b=b.dbl()}else{b=a.diffAdd(b,c);a=a.dbl()}}return b};Point.prototype.mulAdd=function mulAdd(){throw new Error("Not supported on Montgomery curve")};Point.prototype.jumlAdd=function jumlAdd(){throw new Error("Not supported on Montgomery curve")};Point.prototype.eq=function eq(other){return this.getX().cmp(other.getX())===0};Point.prototype.normalize=function normalize(){this.x=this.x.redMul(this.z.redInvm());this.z=this.curve.one;return this};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()}},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:200}],46:[function(require,module,exports){"use strict";var curve=require("../curve");var elliptic=require("../../elliptic");var BN=require("bn.js");var inherits=require("inherits");var Base=curve.base;var assert=elliptic.utils.assert;function ShortCurve(conf){Base.call(this,"short",conf);this.a=new BN(conf.a,16).toRed(this.red);this.b=new BN(conf.b,16).toRed(this.red);this.tinv=this.two.redInvm();this.zeroA=this.a.fromRed().cmpn(0)===0;this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0;this.endo=this._getEndomorphism(conf);this._endoWnafT1=new Array(4);this._endoWnafT2=new Array(4)}inherits(ShortCurve,Base);module.exports=ShortCurve;ShortCurve.prototype._getEndomorphism=function _getEndomorphism(conf){if(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)return;var beta;var lambda;if(conf.beta){beta=new BN(conf.beta,16).toRed(this.red)}else{var betas=this._getEndoRoots(this.p);beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1];beta=beta.toRed(this.red)}if(conf.lambda){lambda=new BN(conf.lambda,16)}else{var lambdas=this._getEndoRoots(this.n);if(this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))===0){lambda=lambdas[0]}else{lambda=lambdas[1];assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))===0)}}var basis;if(conf.basis){basis=conf.basis.map(function(vec){return{a:new BN(vec.a,16),b:new BN(vec.b,16)}})}else{basis=this._getEndoBasis(lambda)}return{beta:beta,lambda:lambda,basis:basis}};ShortCurve.prototype._getEndoRoots=function _getEndoRoots(num){var red=num===this.p?this.red:BN.mont(num);var tinv=new BN(2).toRed(red).redInvm();var ntinv=tinv.redNeg();var s=new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);var l1=ntinv.redAdd(s).fromRed();var l2=ntinv.redSub(s).fromRed();return[l1,l2]};ShortCurve.prototype._getEndoBasis=function _getEndoBasis(lambda){var aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2));var u=lambda;var v=this.n.clone();var x1=new BN(1);var y1=new BN(0);var x2=new BN(0);var y2=new BN(1);var a0;var b0;var a1;var b1;var a2;var b2;var prevR;var i=0;var r;var x;while(u.cmpn(0)!==0){var q=v.div(u);r=v.sub(q.mul(u));x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0){a0=prevR.neg();b0=x1;a1=r.neg();b1=x}else if(a1&&++i===2){break}prevR=r;v=u;u=r;x2=x1;x1=x;y2=y1;y1=y}a2=r.neg();b2=x;var len1=a1.sqr().add(b1.sqr());var len2=a2.sqr().add(b2.sqr());if(len2.cmp(len1)>=0){a2=a0;b2=b0}if(a1.negative){a1=a1.neg();b1=b1.neg()}if(a2.negative){a2=a2.neg();b2=b2.neg()}return[{a:a1,b:b1},{a:a2,b:b2}]};ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis;var v1=basis[0];var v2=basis[1];var c1=v2.b.mul(k).divRound(this.n);var c2=v1.b.neg().mul(k).divRound(this.n);var p1=c1.mul(v1.a);var p2=c2.mul(v2.a);var q1=c1.mul(v1.b);var q2=c2.mul(v2.b);var k1=k.sub(p1).sub(p2);var k2=q1.add(q2).neg();return{k1:k1,k2:k2}};ShortCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN(x,16);if(!x.red)x=x.toRed(this.red);var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};ShortCurve.prototype.validate=function validate(point){if(point.inf)return true;var x=point.x;var y=point.y;var ax=this.a.redMul(x);var rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0};ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){ +var npoints=this._endoWnafT1;var ncoeffs=this._endoWnafT2;for(var i=0;i";return""};Point.prototype.isInfinity=function isInfinity(){return this.inf};Point.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);if(c.cmpn(0)!==0)c=c.redMul(this.x.redSub(p.x).redInvm());var nx=c.redSqr().redISub(this.x).redISub(p.x);var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a;var x2=this.x.redSqr();var dyinv=ys1.redInvm();var c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);var nx=c.redSqr().redISub(this.x.redAdd(this.x));var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point.prototype.getX=function getX(){return this.x.fromRed()};Point.prototype.getY=function getY(){return this.y.fromRed()};Point.prototype.mul=function mul(k){k=new BN(k,16);if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else if(this.curve.endo)return this.curve._endoWnafMulAdd([this],[k]);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs);else return this.curve._wnafMulAdd(1,points,coeffs,2)};Point.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs,true);else return this.curve._wnafMulAdd(1,points,coeffs,2,true)};Point.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)};Point.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed;var negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res};Point.prototype.toJ=function toJ(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,"jacobian");if(x===null&&y===null&&z===null){this.x=this.curve.one;this.y=this.curve.one;this.z=new BN(0)}else{this.x=new BN(x,16);this.y=new BN(y,16);this.z=new BN(z,16)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);this.zOne=this.z===this.curve.one}inherits(JPoint,Base.BasePoint);ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)};JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm();var zinv2=zinv.redSqr();var ax=this.x.redMul(zinv2);var ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)};JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr();var z2=this.z.redSqr();var u1=this.x.redMul(pz2);var u2=p.x.redMul(z2);var s1=this.y.redMul(pz2.redMul(p.z));var s2=p.y.redMul(z2.redMul(this.z));var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr();var u1=this.x;var u2=p.x.redMul(z2);var s1=this.y;var s2=p.y.redMul(z2).redMul(this.z);var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.dblp=function dblp(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();if(this.curve.zeroA||this.curve.threeA){var r=this;for(var i=0;i=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}return false};JPoint.prototype.inspect=function inspect(){if(this.isInfinity())return"";return""};JPoint.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0}},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:200}],47:[function(require,module,exports){"use strict";var curves=exports;var hash=require("hash.js");var elliptic=require("../elliptic");var assert=elliptic.utils.assert;function PresetCurve(options){if(options.type==="short")this.curve=new elliptic.curve.short(options);else if(options.type==="edwards")this.curve=new elliptic.curve.edwards(options);else this.curve=new elliptic.curve.mont(options);this.g=this.curve.g;this.n=this.curve.n;this.hash=options.hash;assert(this.g.validate(),"Invalid curve");assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}curves.PresetCurve=PresetCurve;function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:true,enumerable:true,get:function(){var curve=new PresetCurve(options);Object.defineProperty(curves,name,{configurable:true,enumerable:true,value:curve});return curve}})}defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:false,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]});defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:false,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]});defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:false,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]});defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f "+"5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 "+"f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:false,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 "+"5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 "+"0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]});defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b "+"99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd "+"3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 "+"f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:false,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 "+"053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 "+"a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 "+"579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 "+"3fad0761 353c7086 a272c240 88be9476 9fd16650"]});defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"0",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["9"]});defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=require("./precomputed/secp256k1")}catch(e){pre=undefined}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:false,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})},{"../elliptic":41,"./precomputed/secp256k1":55,"hash.js":58}],48:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var assert=utils.assert;var KeyPair=require("./key");var Signature=require("./signature");function EC(options){if(!(this instanceof EC))return new EC(options);if(typeof options==="string"){assert(elliptic.curves.hasOwnProperty(options),"Unknown curve "+options);options=elliptic.curves[options]}if(options instanceof elliptic.curves.PresetCurve)options={curve:options};this.curve=options.curve.curve;this.n=this.curve.n;this.nh=this.n.ushrn(1);this.g=this.curve.g;this.g=options.curve.g;this.g.precompute(options.curve.n.bitLength()+1);this.hash=options.hash||options.curve.hash}module.exports=EC;EC.prototype.keyPair=function keyPair(options){return new KeyPair(this,options)};EC.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return KeyPair.fromPrivate(this,priv,enc)};EC.prototype.keyFromPublic=function keyFromPublic(pub,enc){return KeyPair.fromPublic(this,pub,enc)};EC.prototype.genKeyPair=function genKeyPair(options){if(!options)options={};var drbg=new elliptic.hmacDRBG({hash:this.hash,pers:options.pers,entropy:options.entropy||elliptic.rand(this.hash.hmacStrength),nonce:this.n.toArray()});var bytes=this.n.byteLength();var ns2=this.n.sub(new BN(2));do{var priv=new BN(drbg.generate(bytes));if(priv.cmp(ns2)>0)continue;priv.iaddn(1);return this.keyFromPrivate(priv)}while(true)};EC.prototype._truncateToN=function truncateToN(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();if(delta>0)msg=msg.ushrn(delta);if(!truncOnly&&msg.cmp(this.n)>=0)return msg.sub(this.n);else return msg};EC.prototype.sign=function sign(msg,key,enc,options){if(typeof enc==="object"){options=enc;enc=null}if(!options)options={};key=this.keyFromPrivate(key,enc);msg=this._truncateToN(new BN(msg,16));var bytes=this.n.byteLength();var bkey=key.getPrivate().toArray("be",bytes);var nonce=msg.toArray("be",bytes);var drbg=new elliptic.hmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc});var ns1=this.n.sub(new BN(1));for(var iter=0;true;iter++){var k=options.k?options.k(iter):new BN(drbg.generate(this.n.byteLength()));k=this._truncateToN(k,true);if(k.cmpn(1)<=0||k.cmp(ns1)>=0)continue;var kp=this.g.mul(k);if(kp.isInfinity())continue;var kpX=kp.getX();var r=kpX.umod(this.n);if(r.cmpn(0)===0)continue;var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));s=s.umod(this.n);if(s.cmpn(0)===0)continue;var recoveryParam=(kp.getY().isOdd()?1:0)|(kpX.cmp(r)!==0?2:0);if(options.canonical&&s.cmp(this.nh)>0){s=this.n.sub(s);recoveryParam^=1}return new Signature({r:r,s:s,recoveryParam:recoveryParam})}};EC.prototype.verify=function verify(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16));key=this.keyFromPublic(key,enc);signature=new Signature(signature,"hex");var r=signature.r;var s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return false;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return false;var sinv=s.invm(this.n);var u1=sinv.mul(msg).umod(this.n);var u2=sinv.mul(r).umod(this.n);if(!this.curve._maxwellTrick){var p=this.g.mulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.getX().umod(this.n).cmp(r)===0}var p=this.g.jmulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.eqXToP(r)};EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,"The recovery param is more than two bits");signature=new Signature(signature,enc);var n=this.n;var e=new BN(msg);var r=signature.r;var s=signature.s;var isYOdd=j&1;var isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");if(isSecondKey)r=this.curve.pointFromX(r.add(this.curve.n),isYOdd);else r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n);var s1=n.sub(e).mul(rInv).umod(n);var s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)};EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){signature=new Signature(signature,enc);if(signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")}},{"../../elliptic":41,"./key":49,"./signature":50,"bn.js":39}],49:[function(require,module,exports){"use strict";var BN=require("bn.js");function KeyPair(ec,options){this.ec=ec;this.priv=null;this.pub=null;if(options.priv)this._importPrivate(options.priv,options.privEnc);if(options.pub)this._importPublic(options.pub,options.pubEnc)}module.exports=KeyPair;KeyPair.fromPublic=function fromPublic(ec,pub,enc){if(pub instanceof KeyPair)return pub;return new KeyPair(ec,{pub:pub,pubEnc:enc})};KeyPair.fromPrivate=function fromPrivate(ec,priv,enc){if(priv instanceof KeyPair)return priv;return new KeyPair(ec,{priv:priv,privEnc:enc})};KeyPair.prototype.validate=function validate(){var pub=this.getPublic();if(pub.isInfinity())return{result:false,reason:"Invalid public key"};if(!pub.validate())return{result:false,reason:"Public key is not a point"};if(!pub.mul(this.ec.curve.n).isInfinity())return{result:false,reason:"Public key * N != O"};return{result:true,reason:null}};KeyPair.prototype.getPublic=function getPublic(compact,enc){if(typeof compact==="string"){enc=compact;compact=null}if(!this.pub)this.pub=this.ec.g.mul(this.priv);if(!enc)return this.pub;return this.pub.encode(enc,compact)};KeyPair.prototype.getPrivate=function getPrivate(enc){if(enc==="hex")return this.priv.toString(16,2);else return this.priv};KeyPair.prototype._importPrivate=function _importPrivate(key,enc){this.priv=new BN(key,enc||16);this.priv=this.priv.umod(this.ec.curve.n)};KeyPair.prototype._importPublic=function _importPublic(key,enc){if(key.x||key.y){this.pub=this.ec.curve.point(key.x,key.y);return}this.pub=this.ec.curve.decodePoint(key,enc)};KeyPair.prototype.derive=function derive(pub){return pub.mul(this.priv).getX()};KeyPair.prototype.sign=function sign(msg,enc,options){return this.ec.sign(msg,this,enc,options)};KeyPair.prototype.verify=function verify(msg,signature){return this.ec.verify(msg,signature,this)};KeyPair.prototype.inspect=function inspect(){return""}},{"bn.js":39}],50:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;if(this._importDER(options,enc))return;assert(options.r&&options.s,"Signature without r or s");this.r=new BN(options.r,16);this.s=new BN(options.s,16);if(options.recoveryParam===undefined)this.recoveryParam=null;else this.recoveryParam=options.recoveryParam}module.exports=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128)){return initial}var octetLen=initial&15;var val=0;for(var i=0,off=p.place;i>>3);arr.push(octets|128);while(--octets){arr.push(len>>>(octets<<3)&255)}arr.push(len)}Signature.prototype.toDER=function toDER(enc){var r=this.r.toArray();var s=this.s.toArray();if(r[0]&128)r=[0].concat(r);if(s[0]&128)s=[0].concat(s);r=rmPadding(r);s=rmPadding(s);while(!s[0]&&!(s[1]&128)){s=s.slice(1)}var arr=[2];constructLength(arr,r.length);arr=arr.concat(r);arr.push(2);constructLength(arr,s.length);var backHalf=arr.concat(s);var res=[48];constructLength(res,backHalf.length);res=res.concat(backHalf);return utils.encode(res,enc)}},{"../../elliptic":41,"bn.js":39}],51:[function(require,module,exports){"use strict";var hash=require("hash.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var assert=utils.assert;var parseBytes=utils.parseBytes;var KeyPair=require("./key");var Signature=require("./signature");function EDDSA(curve){assert(curve==="ed25519","only tested with ed25519 so far");if(!(this instanceof EDDSA))return new EDDSA(curve);var curve=elliptic.curves[curve].curve;this.curve=curve;this.g=curve.g;this.g.precompute(curve.n.bitLength()+1);this.pointClass=curve.point().constructor;this.encodingLength=Math.ceil(curve.n.bitLength()/8);this.hash=hash.sha512}module.exports=EDDSA;EDDSA.prototype.sign=function sign(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret);var r=this.hashInt(key.messagePrefix(),message);var R=this.g.mul(r);var Rencoded=this.encodePoint(R);var s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv());var S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})};EDDSA.prototype.verify=function verify(message,sig,pub){message=parseBytes(message);sig=this.makeSignature(sig);var key=this.keyFromPublic(pub);var h=this.hashInt(sig.Rencoded(),key.pubBytes(),message);var SG=this.g.mul(sig.S());var RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)};EDDSA.prototype.hashInt=function hashInt(){var hash=this.hash();for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._init(entropy,nonce,pers)}module.exports=HmacDRBG;HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8);this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._update(entropy.concat(add||[]));this.reseed=1};HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this.reseed>this.reseedInterval)throw new Error("Reseed is required");if(typeof enc!=="string"){addEnc=add;add=enc;enc=null}if(add){add=utils.toArray(add,addEnc);this._update(add)}var temp=[];while(temp.length>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}else if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i=0){var z;if(k.isOdd()){var mod=k.andln(ws-1);if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf.push(z);var shift=k.cmpn(0)!==0&&k.andln(ws-1)===0?w+1:1;for(var i=1;i0||k2.cmpn(-d2)>0){var m14=k1.andln(3)+d1&3;var m24=k2.andln(3)+d2&3;if(m14===3)m14=-1;if(m24===3)m24=-1;var u1;if((m14&1)===0){u1=0}else{var m8=k1.andln(7)+d1&7;if((m8===3||m8===5)&&m24===2)u1=-m14;else u1=m14}jsf[0].push(u1);var u2;if((m24&1)===0){u2=0}else{var m8=k2.andln(7)+d2&7;if((m8===3||m8===5)&&m14===2)u2=-m24;else u2=m24}jsf[1].push(u2);if(2*d1===u1+1)d1=1-d1;if(2*d2===u2+1)d2=1-d2;k1.iushrn(1);k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return this[key]!==undefined?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==="string"?utils.toArray(bytes,"hex"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,"hex","le")}utils.intFromLE=intFromLE},{"bn.js":39}],57:[function(require,module,exports){var r;module.exports=function rand(len){if(!r)r=new Rand(null);return r.generate(len)};function Rand(rand){this.rand=rand}module.exports.Rand=Rand;Rand.prototype.generate=function generate(len){return this._rand(len)};if(typeof window==="object"){if(window.crypto&&window.crypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);window.crypto.getRandomValues(arr);return arr}}else if(window.msCrypto&&window.msCrypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);window.msCrypto.getRandomValues(arr);return arr}}else{Rand.prototype._rand=function(){throw new Error("Not implemented yet")}}}else{try{var crypto=require("crypto"); +Rand.prototype._rand=function _rand(n){return crypto.randomBytes(n)}}catch(e){Rand.prototype._rand=function _rand(n){var res=new Uint8Array(n);for(var i=0;i=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length);if(this.pending.length===0)this.pending=null;msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255;res[i++]=len>>>16&255;res[i++]=len>>>8&255;res[i++]=len&255}else{res[i++]=len&255;res[i++]=len>>>8&255;res[i++]=len>>>16&255;res[i++]=len>>>24&255;res[i++]=0;res[i++]=0;res[i++]=0;res[i++]=0;for(var t=8;tthis.blockSize)key=(new this.Hash).update(key).digest();assert(key.length<=this.blockSize);for(var i=key.length;i>>3}function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}function ft_1(s,x,y,z){if(s===0)return ch32(x,y,z);if(s===1||s===3)return p32(x,y,z);if(s===2)return maj32(x,y,z)}function ch64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^~xh&zh;if(r<0)r+=4294967296;return r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;if(r<0)r+=4294967296;return r}function maj64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^xh&zh^yh&zh;if(r<0)r+=4294967296;return r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;if(r<0)r+=4294967296;return r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28);var c1_hi=rotr64_hi(xl,xh,2);var c2_hi=rotr64_hi(xl,xh,7);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28);var c1_lo=rotr64_lo(xl,xh,2);var c2_lo=rotr64_lo(xl,xh,7);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14);var c1_hi=rotr64_hi(xh,xl,18);var c2_hi=rotr64_hi(xl,xh,9);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14);var c1_lo=rotr64_lo(xh,xl,18);var c2_lo=rotr64_lo(xl,xh,9);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1);var c1_hi=rotr64_hi(xh,xl,8);var c2_hi=shr64_hi(xh,xl,7);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1);var c1_lo=rotr64_lo(xh,xl,8);var c2_lo=shr64_lo(xh,xl,7);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19);var c1_hi=rotr64_hi(xl,xh,29);var c2_hi=shr64_hi(xh,xl,6);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19);var c1_lo=rotr64_lo(xl,xh,29);var c2_lo=shr64_lo(xh,xl,6);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}},{"../hash":58}],63:[function(require,module,exports){var utils=exports;var inherits=require("inherits");function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==="string"){if(!enc){for(var i=0;i>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}else if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}utils.htonl=htonl;function toHex32(msg,endian){var res="";for(var i=0;i>>0}return res}utils.join32=join32;function split32(msg,endian){var res=new Array(msg.length*4);for(var i=0,k=0;i>>24;res[k+1]=m>>>16&255;res[k+2]=m>>>8&255;res[k+3]=m&255}else{res[k+3]=m>>>24;res[k+2]=m>>>16&255;res[k+1]=m>>>8&255;res[k]=m&255}}return res}utils.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}utils.rotr32=rotr32;function rotl32(w,b){return w<>>32-b}utils.rotl32=rotl32;function sum32(a,b){return a+b>>>0}utils.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}utils.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}utils.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}utils.sum32_5=sum32_5;function assert(cond,msg){if(!cond)throw new Error(msg||"Assertion failed")}utils.assert=assert;utils.inherits=inherits;function sum64(buf,pos,ah,al){var bh=buf[pos];var bl=buf[pos+1];var lo=al+bl>>>0;var hi=(lo>>0;buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0;var hi=(lo>>0}exports.sum64_hi=sum64_hi;function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}exports.sum64_lo=sum64_lo;function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0;var lo=al;lo=lo+bl>>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>0}exports.sum64_4_hi=sum64_4_hi;function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}exports.sum64_4_lo=sum64_4_lo;function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0;var lo=al;lo=lo+bl>>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>0}exports.sum64_5_hi=sum64_5_hi;function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}exports.sum64_5_lo=sum64_5_lo;function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}exports.rotr64_hi=rotr64_hi;function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.rotr64_lo=rotr64_lo;function shr64_hi(ah,al,num){return ah>>>num}exports.shr64_hi=shr64_hi;function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.shr64_lo=shr64_lo},{inherits:200}],64:[function(require,module,exports){module.exports={name:"elliptic",version:"6.3.2",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},keywords:["EC","Elliptic","curve","Cryptography"],author:{name:"Fedor Indutny",email:"fedor@indutny.com"},license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0",inherits:"^2.0.1"},gitHead:"cbace4683a4a548dc0306ef36756151a20299cd5",_id:"elliptic@6.3.2",_shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",_from:"elliptic@>=6.0.0 <7.0.0",_npmVersion:"3.10.3",_nodeVersion:"6.3.0",_npmUser:{name:"indutny",email:"fedor@indutny.com"},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},maintainers:[{name:"indutny",email:"fedor@indutny.com"}],_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},directories:{},_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz",readme:"ERROR: No README data found!"}},{}],65:[function(require,module,exports){module.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],66:[function(require,module,exports){var asn1=require("asn1.js");var RSAPrivateKey=asn1.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});exports.RSAPrivateKey=RSAPrivateKey;var RSAPublicKey=asn1.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});exports.RSAPublicKey=RSAPublicKey;var PublicKey=asn1.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPublicKey").bitstr())});exports.PublicKey=PublicKey;var AlgorithmIdentifier=asn1.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())});var PrivateKeyInfo=asn1.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPrivateKey").octstr())});exports.PrivateKey=PrivateKeyInfo;var EncryptedPrivateKeyInfo=asn1.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});exports.EncryptedPrivateKey=EncryptedPrivateKeyInfo;var DSAPrivateKey=asn1.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});exports.DSAPrivateKey=DSAPrivateKey;exports.DSAparam=asn1.define("DSAparam",function(){this.int()});var ECPrivateKey=asn1.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(ECParameters),this.key("publicKey").optional().explicit(1).bitstr())});exports.ECPrivateKey=ECPrivateKey;var ECParameters=asn1.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});exports.signature=asn1.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"asn1.js":69}],67:[function(require,module,exports){(function(Buffer){var findProc=/Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\r?\n\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n/m;var startRegex=/^-----BEGIN (.*) KEY-----\r?\n/m;var fullRegex=/^-----BEGIN (.*) KEY-----\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n-----END \1 KEY-----$/m;var evp=require("evp_bytestokey");var ciphers=require("browserify-aes");module.exports=function(okey,password){var key=okey.toString();var match=key.match(findProc);var decrypted;if(!match){var match2=key.match(fullRegex);decrypted=new Buffer(match2[2].replace(/\r?\n/g,""),"base64")}else{var suite="aes"+match[1];var iv=new Buffer(match[2],"hex");var cipherText=new Buffer(match[3].replace(/\r?\n/g,""),"base64");var cipherKey=evp(password,iv.slice(0,8),parseInt(match[1],10)).key;var out=[];var cipher=ciphers.createDecipheriv(suite,cipherKey,iv);out.push(cipher.update(cipherText));out.push(cipher.final());decrypted=Buffer.concat(out)}var tag=key.match(startRegex)[1]+" KEY";return{tag:tag,data:decrypted}}}).call(this,require("buffer").Buffer)},{"browserify-aes":86,buffer:2,evp_bytestokey:101}],68:[function(require,module,exports){(function(Buffer){var asn1=require("./asn1");var aesid=require("./aesid.json");var fixProc=require("./fixProc");var ciphers=require("browserify-aes");var compat=require("pbkdf2");module.exports=parseKeys;function parseKeys(buffer){var password;if(typeof buffer==="object"&&!Buffer.isBuffer(buffer)){password=buffer.passphrase;buffer=buffer.key}if(typeof buffer==="string"){buffer=new Buffer(buffer)}var stripped=fixProc(buffer,password);var type=stripped.tag;var data=stripped.data;var subtype,ndata;switch(type){case"PUBLIC KEY":ndata=asn1.PublicKey.decode(data,"der");subtype=ndata.algorithm.algorithm.join(".");switch(subtype){case"1.2.840.113549.1.1.1":return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":ndata.subjectPrivateKey=ndata.subjectPublicKey;return{type:"ec",data:ndata};case"1.2.840.10040.4.1":ndata.algorithm.params.pub_key=asn1.DSAparam.decode(ndata.subjectPublicKey.data,"der");return{type:"dsa",data:ndata.algorithm.params};default:throw new Error("unknown key id "+subtype)}throw new Error("unknown key type "+type);case"ENCRYPTED PRIVATE KEY":data=asn1.EncryptedPrivateKey.decode(data,"der");data=decrypt(data,password);case"PRIVATE KEY":ndata=asn1.PrivateKey.decode(data,"der");subtype=ndata.algorithm.algorithm.join(".");switch(subtype){case"1.2.840.113549.1.1.1":return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:ndata.algorithm.curve,privateKey:asn1.ECPrivateKey.decode(ndata.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":ndata.algorithm.params.priv_key=asn1.DSAparam.decode(ndata.subjectPrivateKey,"der");return{type:"dsa",params:ndata.algorithm.params};default:throw new Error("unknown key id "+subtype)}throw new Error("unknown key type "+type);case"RSA PUBLIC KEY":return asn1.RSAPublicKey.decode(data,"der");case"RSA PRIVATE KEY":return asn1.RSAPrivateKey.decode(data,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:asn1.DSAPrivateKey.decode(data,"der")};case"EC PRIVATE KEY":data=asn1.ECPrivateKey.decode(data,"der");return{curve:data.parameters.value,privateKey:data.privateKey};default:throw new Error("unknown key type "+type)}}parseKeys.signature=asn1.signature;function decrypt(data,password){var salt=data.algorithm.decrypt.kde.kdeparams.salt;var iters=parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(),10);var algo=aesid[data.algorithm.decrypt.cipher.algo.join(".")];var iv=data.algorithm.decrypt.cipher.iv;var cipherText=data.subjectPrivateKey;var keylen=parseInt(algo.split("-")[1],10)/8;var key=compat.pbkdf2Sync(password,salt,iters,keylen);var cipher=ciphers.createDecipheriv(algo,key,iv);var out=[];out.push(cipher.update(cipherText));out.push(cipher.final());return Buffer.concat(out)}}).call(this,require("buffer").Buffer)},{"./aesid.json":65,"./asn1":66,"./fixProc":67,"browserify-aes":86,buffer:2,pbkdf2:151}],69:[function(require,module,exports){var asn1=exports;asn1.bignum=require("bn.js");asn1.define=require("./asn1/api").define;asn1.base=require("./asn1/base");asn1.constants=require("./asn1/constants");asn1.decoders=require("./asn1/decoders");asn1.encoders=require("./asn1/encoders")},{"./asn1/api":70,"./asn1/base":72,"./asn1/constants":76,"./asn1/decoders":78,"./asn1/encoders":81,"bn.js":39}],70:[function(require,module,exports){var asn1=require("../asn1");var inherits=require("inherits");var api=exports;api.define=function define(name,body){return new Entity(name,body)};function Entity(name,body){this.name=name;this.body=body;this.decoders={};this.encoders={}}Entity.prototype._createNamed=function createNamed(base){var named;try{named=require("vm").runInThisContext("(function "+this.name+"(entity) {\n"+" this._initNamed(entity);\n"+"})")}catch(e){named=function(entity){this._initNamed(entity)}}inherits(named,base);named.prototype._initNamed=function initnamed(entity){base.call(this,entity)};return new named(this)};Entity.prototype._getDecoder=function _getDecoder(enc){enc=enc||"der";if(!this.decoders.hasOwnProperty(enc))this.decoders[enc]=this._createNamed(asn1.decoders[enc]);return this.decoders[enc]};Entity.prototype.decode=function decode(data,enc,options){return this._getDecoder(enc).decode(data,options)};Entity.prototype._getEncoder=function _getEncoder(enc){enc=enc||"der";if(!this.encoders.hasOwnProperty(enc))this.encoders[enc]=this._createNamed(asn1.encoders[enc]);return this.encoders[enc]};Entity.prototype.encode=function encode(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},{"../asn1":69,inherits:200,vm:221}],71:[function(require,module,exports){var inherits=require("inherits");var Reporter=require("../base").Reporter;var Buffer=require("buffer").Buffer;function DecoderBuffer(base,options){Reporter.call(this,options);if(!Buffer.isBuffer(base)){this.error("Input not Buffer");return}this.base=base;this.offset=0;this.length=base.length} +inherits(DecoderBuffer,Reporter);exports.DecoderBuffer=DecoderBuffer;DecoderBuffer.prototype.save=function save(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}};DecoderBuffer.prototype.restore=function restore(save){var res=new DecoderBuffer(this.base);res.offset=save.offset;res.length=this.offset;this.offset=save.offset;Reporter.prototype.restore.call(this,save.reporter);return res};DecoderBuffer.prototype.isEmpty=function isEmpty(){return this.offset===this.length};DecoderBuffer.prototype.readUInt8=function readUInt8(fail){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,true);else return this.error(fail||"DecoderBuffer overrun")};DecoderBuffer.prototype.skip=function skip(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");var res=new DecoderBuffer(this.base);res._reporterState=this._reporterState;res.offset=this.offset;res.length=this.offset+bytes;this.offset+=bytes;return res};DecoderBuffer.prototype.raw=function raw(save){return this.base.slice(save?save.offset:this.offset,this.length)};function EncoderBuffer(value,reporter){if(Array.isArray(value)){this.length=0;this.value=value.map(function(item){if(!(item instanceof EncoderBuffer))item=new EncoderBuffer(item,reporter);this.length+=item.length;return item},this)}else if(typeof value==="number"){if(!(0<=value&&value<=255))return reporter.error("non-byte EncoderBuffer value");this.value=value;this.length=1}else if(typeof value==="string"){this.value=value;this.length=Buffer.byteLength(value)}else if(Buffer.isBuffer(value)){this.value=value;this.length=value.length}else{return reporter.error("Unsupported type: "+typeof value)}}exports.EncoderBuffer=EncoderBuffer;EncoderBuffer.prototype.join=function join(out,offset){if(!out)out=new Buffer(this.length);if(!offset)offset=0;if(this.length===0)return out;if(Array.isArray(this.value)){this.value.forEach(function(item){item.join(out,offset);offset+=item.length})}else{if(typeof this.value==="number")out[offset]=this.value;else if(typeof this.value==="string")out.write(this.value,offset);else if(Buffer.isBuffer(this.value))this.value.copy(out,offset);offset+=this.length}return out}},{"../base":72,buffer:2,inherits:200}],72:[function(require,module,exports){var base=exports;base.Reporter=require("./reporter").Reporter;base.DecoderBuffer=require("./buffer").DecoderBuffer;base.EncoderBuffer=require("./buffer").EncoderBuffer;base.Node=require("./node")},{"./buffer":71,"./node":73,"./reporter":74}],73:[function(require,module,exports){var Reporter=require("../base").Reporter;var EncoderBuffer=require("../base").EncoderBuffer;var DecoderBuffer=require("../base").DecoderBuffer;var assert=require("minimalistic-assert");var tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"];var methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags);var overrided=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function Node(enc,parent){var state={};this._baseState=state;state.enc=enc;state.parent=parent||null;state.children=null;state.tag=null;state.args=null;state.reverseArgs=null;state.choice=null;state.optional=false;state.any=false;state.obj=false;state.use=null;state.useDecoder=null;state.key=null;state["default"]=null;state.explicit=null;state.implicit=null;state.contains=null;if(!state.parent){state.children=[];this._wrap()}}module.exports=Node;var stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function clone(){var state=this._baseState;var cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});var res=new this.constructor(cstate.parent);res._baseState=cstate;return res};Node.prototype._wrap=function wrap(){var state=this._baseState;methods.forEach(function(method){this[method]=function _wrappedMethod(){var clone=new this.constructor(this);state.children.push(clone);return clone[method].apply(clone,arguments)}},this)};Node.prototype._init=function init(body){var state=this._baseState;assert(state.parent===null);body.call(this);state.children=state.children.filter(function(child){return child._baseState.parent===this},this);assert.equal(state.children.length,1,"Root node can have only one child")};Node.prototype._useArgs=function useArgs(args){var state=this._baseState;var children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this);if(children.length!==0){assert(state.children===null);state.children=children;children.forEach(function(child){child._baseState.parent=this},this)}if(args.length!==0){assert(state.args===null);state.args=args;state.reverseArgs=args.map(function(arg){if(typeof arg!=="object"||arg.constructor!==Object)return arg;var res={};Object.keys(arg).forEach(function(key){if(key==(key|0))key|=0;var value=arg[key];res[value]=key});return res})}};overrided.forEach(function(method){Node.prototype[method]=function _overrided(){var state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}});tags.forEach(function(tag){Node.prototype[tag]=function _tagMethod(){var state=this._baseState;var args=Array.prototype.slice.call(arguments);assert(state.tag===null);state.tag=tag;this._useArgs(args);return this}});Node.prototype.use=function use(item){var state=this._baseState;assert(state.use===null);state.use=item;return this};Node.prototype.optional=function optional(){var state=this._baseState;state.optional=true;return this};Node.prototype.def=function def(val){var state=this._baseState;assert(state["default"]===null);state["default"]=val;state.optional=true;return this};Node.prototype.explicit=function explicit(num){var state=this._baseState;assert(state.explicit===null&&state.implicit===null);state.explicit=num;return this};Node.prototype.implicit=function implicit(num){var state=this._baseState;assert(state.explicit===null&&state.implicit===null);state.implicit=num;return this};Node.prototype.obj=function obj(){var state=this._baseState;var args=Array.prototype.slice.call(arguments);state.obj=true;if(args.length!==0)this._useArgs(args);return this};Node.prototype.key=function key(newKey){var state=this._baseState;assert(state.key===null);state.key=newKey;return this};Node.prototype.any=function any(){var state=this._baseState;state.any=true;return this};Node.prototype.choice=function choice(obj){var state=this._baseState;assert(state.choice===null);state.choice=obj;this._useArgs(Object.keys(obj).map(function(key){return obj[key]}));return this};Node.prototype.contains=function contains(item){var state=this._baseState;assert(state.use===null);state.contains=item;return this};Node.prototype._decode=function decode(input,options){var state=this._baseState;if(state.parent===null)return input.wrapResult(state.children[0]._decode(input,options));var result=state["default"];var present=true;var prevKey=null;if(state.key!==null)prevKey=input.enterKey(state.key);if(state.optional){var tag=null;if(state.explicit!==null)tag=state.explicit;else if(state.implicit!==null)tag=state.implicit;else if(state.tag!==null)tag=state.tag;if(tag===null&&!state.any){var save=input.save();try{if(state.choice===null)this._decodeGeneric(state.tag,input,options);else this._decodeChoice(input,options);present=true}catch(e){present=false}input.restore(save)}else{present=this._peekTag(input,tag,state.any);if(input.isError(present))return present}}var prevObj;if(state.obj&&present)prevObj=input.enterObject();if(present){if(state.explicit!==null){var explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}var start=input.offset;if(state.use===null&&state.choice===null){if(state.any)var save=input.save();var body=this._decodeTag(input,state.implicit!==null?state.implicit:state.tag,state.any);if(input.isError(body))return body;if(state.any)result=input.raw(save);else input=body}if(options&&options.track&&state.tag!==null)options.track(input.path(),start,input.length,"tagged");if(options&&options.track&&state.tag!==null)options.track(input.path(),input.offset,input.length,"content");if(state.any)result=result;else if(state.choice===null)result=this._decodeGeneric(state.tag,input,options);else result=this._decodeChoice(input,options);if(input.isError(result))return result;if(!state.any&&state.choice===null&&state.children!==null){state.children.forEach(function decodeChildren(child){child._decode(input,options)})}if(state.contains&&(state.tag==="octstr"||state.tag==="bitstr")){var data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}if(state.obj&&present)result=input.leaveObject(prevObj);if(state.key!==null&&(result!==null||present===true))input.leaveKey(prevKey,state.key,result);else if(prevKey!==null)input.exitKey(prevKey);return result};Node.prototype._decodeGeneric=function decodeGeneric(tag,input,options){var state=this._baseState;if(tag==="seq"||tag==="set")return null;if(tag==="seqof"||tag==="setof")return this._decodeList(input,tag,state.args[0],options);else if(/str$/.test(tag))return this._decodeStr(input,tag,options);else if(tag==="objid"&&state.args)return this._decodeObjid(input,state.args[0],state.args[1],options);else if(tag==="objid")return this._decodeObjid(input,null,null,options);else if(tag==="gentime"||tag==="utctime")return this._decodeTime(input,tag,options);else if(tag==="null_")return this._decodeNull(input,options);else if(tag==="bool")return this._decodeBool(input,options);else if(tag==="int"||tag==="enum")return this._decodeInt(input,state.args&&state.args[0],options);if(state.use!==null){return this._getUse(state.use,input._reporterState.obj)._decode(input,options)}else{return input.error("unknown tag: "+tag)}};Node.prototype._getUse=function _getUse(entity,obj){var state=this._baseState;state.useDecoder=this._use(entity,obj);assert(state.useDecoder._baseState.parent===null);state.useDecoder=state.useDecoder._baseState.children[0];if(state.implicit!==state.useDecoder._baseState.implicit){state.useDecoder=state.useDecoder.clone();state.useDecoder._baseState.implicit=state.implicit}return state.useDecoder};Node.prototype._decodeChoice=function decodeChoice(input,options){var state=this._baseState;var result=null;var match=false;Object.keys(state.choice).some(function(key){var save=input.save();var node=state.choice[key];try{var value=node._decode(input,options);if(input.isError(value))return false;result={type:key,value:value};match=true}catch(e){input.restore(save);return false}return true},this);if(!match)return input.error("Choice not matched");return result};Node.prototype._createEncoderBuffer=function createEncoderBuffer(data){return new EncoderBuffer(data,this.reporter)};Node.prototype._encode=function encode(data,reporter,parent){var state=this._baseState;if(state["default"]!==null&&state["default"]===data)return;var result=this._encodeValue(data,reporter,parent);if(result===undefined)return;if(this._skipDefault(result,reporter,parent))return;return result};Node.prototype._encodeValue=function encode(data,reporter,parent){var state=this._baseState;if(state.parent===null)return state.children[0]._encode(data,reporter||new Reporter);var result=null;this.reporter=reporter;if(state.optional&&data===undefined){if(state["default"]!==null)data=state["default"];else return}var content=null;var primitive=false;if(state.any){result=this._createEncoderBuffer(data)}else if(state.choice){result=this._encodeChoice(data,reporter)}else if(state.contains){content=this._getUse(state.contains,parent)._encode(data,reporter);primitive=true}else if(state.children){content=state.children.map(function(child){if(child._baseState.tag==="null_")return child._encode(null,reporter,data);if(child._baseState.key===null)return reporter.error("Child should have a key");var prevKey=reporter.enterKey(child._baseState.key);if(typeof data!=="object")return reporter.error("Child expected, but input is not object");var res=child._encode(data[child._baseState.key],reporter,data);reporter.leaveKey(prevKey);return res},this).filter(function(child){return child});content=this._createEncoderBuffer(content)}else{if(state.tag==="seqof"||state.tag==="setof"){if(!(state.args&&state.args.length===1))return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");var child=this.clone();child._baseState.implicit=null;content=this._createEncoderBuffer(data.map(function(item){var state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else if(state.use!==null){result=this._getUse(state.use,parent)._encode(data,reporter)}else{content=this._encodePrimitive(state.tag,data);primitive=true}}var result;if(!state.any&&state.choice===null){var tag=state.implicit!==null?state.implicit:state.tag;var cls=state.implicit===null?"universal":"context";if(tag===null){if(state.use===null)reporter.error("Tag could be ommited only for .use()")}else{if(state.use===null)result=this._encodeComposite(tag,primitive,cls,content)}}if(state.explicit!==null)result=this._encodeComposite(state.explicit,false,"context",result);return result};Node.prototype._encodeChoice=function encodeChoice(data,reporter){var state=this._baseState;var node=state.choice[data.type];if(!node){assert(false,data.type+" not found in "+JSON.stringify(Object.keys(state.choice)))}return node._encode(data.value,reporter)};Node.prototype._encodePrimitive=function encodePrimitive(tag,data){var state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);else if(tag==="objid"&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);else if(tag==="objid")return this._encodeObjid(data,null,null);else if(tag==="gentime"||tag==="utctime")return this._encodeTime(data,tag);else if(tag==="null_")return this._encodeNull();else if(tag==="int"||tag==="enum")return this._encodeInt(data,state.args&&state.reverseArgs[0]);else if(tag==="bool")return this._encodeBool(data);else throw new Error("Unsupported tag: "+tag)};Node.prototype._isNumstr=function isNumstr(str){return/^[0-9 ]*$/.test(str)};Node.prototype._isPrintstr=function isPrintstr(str){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str)}},{"../base":72,"minimalistic-assert":83}],74:[function(require,module,exports){var inherits=require("inherits");function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}exports.Reporter=Reporter;Reporter.prototype.isError=function isError(obj){return obj instanceof ReporterError};Reporter.prototype.save=function save(){var state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}};Reporter.prototype.restore=function restore(data){var state=this._reporterState;state.obj=data.obj;state.path=state.path.slice(0,data.pathLen)};Reporter.prototype.enterKey=function enterKey(key){return this._reporterState.path.push(key)};Reporter.prototype.exitKey=function exitKey(index){var state=this._reporterState;state.path=state.path.slice(0,index-1)};Reporter.prototype.leaveKey=function leaveKey(index,key,value){var state=this._reporterState;this.exitKey(index);if(state.obj!==null)state.obj[key]=value};Reporter.prototype.path=function path(){return this._reporterState.path.join("/")};Reporter.prototype.enterObject=function enterObject(){var state=this._reporterState;var prev=state.obj;state.obj={};return prev};Reporter.prototype.leaveObject=function leaveObject(prev){var state=this._reporterState;var now=state.obj;state.obj=prev;return now};Reporter.prototype.error=function error(msg){var err;var state=this._reporterState;var inherited=msg instanceof ReporterError;if(inherited){err=msg}else{err=new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack)}if(!state.options.partial)throw err;if(!inherited)state.errors.push(err);return err};Reporter.prototype.wrapResult=function wrapResult(result){var state=this._reporterState;if(!state.options.partial)return result;return{result:this.isError(result)?null:result,errors:state.errors}};function ReporterError(path,msg){this.path=path;this.rethrow(msg)}inherits(ReporterError,Error);ReporterError.prototype.rethrow=function rethrow(msg){this.message=msg+" at: "+(this.path||"(shallow)");if(Error.captureStackTrace)Error.captureStackTrace(this,ReporterError);if(!this.stack){try{throw new Error(this.message)}catch(e){this.stack=e.stack}}return this}},{inherits:200}],75:[function(require,module,exports){var constants=require("../constants");exports.tagClass={0:"universal",1:"application",2:"context",3:"private"};exports.tagClassByName=constants._reverse(exports.tagClass);exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};exports.tagByName=constants._reverse(exports.tag)},{"../constants":76}],76:[function(require,module,exports){var constants=exports;constants._reverse=function reverse(map){var res={};Object.keys(map).forEach(function(key){if((key|0)==key)key=key|0;var value=map[key];res[value]=key});return res};constants.der=require("./der")},{"./der":75}],77:[function(require,module,exports){var inherits=require("inherits");var asn1=require("../../asn1");var base=asn1.base;var bignum=asn1.bignum;var der=asn1.constants.der;function DERDecoder(entity){this.enc="der";this.name=entity.name;this.entity=entity;this.tree=new DERNode;this.tree._init(entity.body)}module.exports=DERDecoder;DERDecoder.prototype.decode=function decode(data,options){if(!(data instanceof base.DecoderBuffer))data=new base.DecoderBuffer(data,options);return this.tree._decode(data,options)};function DERNode(parent){base.Node.call(this,"der",parent)}inherits(DERNode,base.Node);DERNode.prototype._peekTag=function peekTag(buffer,tag,any){if(buffer.isEmpty())return false;var state=buffer.save();var decodedTag=derDecodeTag(buffer,'Failed to peek tag: "'+tag+'"');if(buffer.isError(decodedTag))return decodedTag;buffer.restore(state);return decodedTag.tag===tag||decodedTag.tagStr===tag||decodedTag.tagStr+"of"===tag||any};DERNode.prototype._decodeTag=function decodeTag(buffer,tag,any){var decodedTag=derDecodeTag(buffer,'Failed to decode tag of "'+tag+'"');if(buffer.isError(decodedTag))return decodedTag;var len=derDecodeLen(buffer,decodedTag.primitive,'Failed to get length of "'+tag+'"');if(buffer.isError(len))return len;if(!any&&decodedTag.tag!==tag&&decodedTag.tagStr!==tag&&decodedTag.tagStr+"of"!==tag){return buffer.error('Failed to match tag: "'+tag+'"')}if(decodedTag.primitive||len!==null)return buffer.skip(len,'Failed to match body of: "'+tag+'"');var state=buffer.save();var res=this._skipUntilEnd(buffer,'Failed to skip indefinite length body: "'+this.tag+'"');if(buffer.isError(res))return res;len=buffer.offset-state.offset;buffer.restore(state);return buffer.skip(len,'Failed to match body of: "'+tag+'"')};DERNode.prototype._skipUntilEnd=function skipUntilEnd(buffer,fail){while(true){var tag=derDecodeTag(buffer,fail);if(buffer.isError(tag))return tag;var len=derDecodeLen(buffer,tag.primitive,fail);if(buffer.isError(len))return len;var res;if(tag.primitive||len!==null)res=buffer.skip(len);else res=this._skipUntilEnd(buffer,fail);if(buffer.isError(res))return res;if(tag.tagStr==="end")break}};DERNode.prototype._decodeList=function decodeList(buffer,tag,decoder,options){var result=[];while(!buffer.isEmpty()){var possibleEnd=this._peekTag(buffer,"end");if(buffer.isError(possibleEnd))return possibleEnd;var res=decoder.decode(buffer,"der",options);if(buffer.isError(res)&&possibleEnd)break;result.push(res)}return result};DERNode.prototype._decodeStr=function decodeStr(buffer,tag){if(tag==="bitstr"){var unused=buffer.readUInt8();if(buffer.isError(unused))return unused;return{unused:unused,data:buffer.raw()}}else if(tag==="bmpstr"){var raw=buffer.raw();if(raw.length%2===1)return buffer.error("Decoding of string type: bmpstr length mismatch");var str="";for(var i=0;i>6];var primitive=(tag&32)===0;if((tag&31)===31){var oct=tag;tag=0;while((oct&128)===128){oct=buf.readUInt8(fail);if(buf.isError(oct))return oct;tag<<=7;tag|=oct&127}}else{tag&=31}var tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){var len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&len===128)return null;if((len&128)===0){return len}var num=len&127;if(num>=4)return buf.error("length octect is too long");len=0;for(var i=0;i=256;i>>=8)lenOctets++;var header=new Buffer(1+1+lenOctets);header[0]=encodedTag;header[1]=128|lenOctets;for(var i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=j&255;return this._createEncoderBuffer([header,content])};DERNode.prototype._encodeStr=function encodeStr(str,tag){if(tag==="bitstr"){return this._createEncoderBuffer([str.unused|0,str.data])}else if(tag==="bmpstr"){var buf=new Buffer(str.length*2);for(var i=0;i=40)return this.reporter.error("Second objid identifier OOB");id.splice(0,2,id[0]*40+id[1])}var size=0;for(var i=0;i=128;ident>>=7)size++}var objid=new Buffer(size);var offset=objid.length-1;for(var i=id.length-1;i>=0;i--){var ident=id[i];objid[offset--]=ident&127;while((ident>>=7)>0)objid[offset--]=128|ident&127}return this._createEncoderBuffer(objid)};function two(num){if(num<10)return"0"+num;else return num}DERNode.prototype._encodeTime=function encodeTime(time,tag){var str;var date=new Date(time);if(tag==="gentime"){str=[two(date.getFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join("")}else if(tag==="utctime"){str=[two(date.getFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join("")}else{this.reporter.error("Encoding "+tag+" time is not supported yet")}return this._encodeStr(str,"octstr")};DERNode.prototype._encodeNull=function encodeNull(){return this._createEncoderBuffer("")};DERNode.prototype._encodeInt=function encodeInt(num,values){if(typeof num==="string"){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num)){return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num))}num=values[num]}if(typeof num!=="number"&&!Buffer.isBuffer(num)){var numArray=num.toArray();if(!num.sign&&numArray[0]&128){numArray.unshift(0)}num=new Buffer(numArray)}if(Buffer.isBuffer(num)){var size=num.length;if(num.length===0)size++;var out=new Buffer(size);num.copy(out);if(num.length===0)out[0]=0;return this._createEncoderBuffer(out)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);var size=1;for(var i=num;i>=256;i>>=8)size++;var out=new Array(size);for(var i=out.length-1;i>=0;i--){out[i]=num&255;num>>=8}if(out[0]&128){out.unshift(0)}return this._createEncoderBuffer(new Buffer(out))};DERNode.prototype._encodeBool=function encodeBool(value){return this._createEncoderBuffer(value?255:0)};DERNode.prototype._use=function use(entity,obj){if(typeof entity==="function")entity=entity(obj);return entity._getEncoder("der").tree};DERNode.prototype._skipDefault=function skipDefault(dataBuffer,reporter,parent){var state=this._baseState;var i;if(state["default"]===null)return false;var data=dataBuffer.join();if(state.defaultBuffer===undefined)state.defaultBuffer=this._encodeValue(state["default"],reporter,parent).join();if(data.length!==state.defaultBuffer.length)return false;for(i=0;i=31)return reporter.error("Multi-octet tag encoding unsupported");if(!primitive)res|=32;res|=der.tagClassByName[cls||"universal"]<<6;return res}},{"../../asn1":69,buffer:2,inherits:200}],81:[function(require,module,exports){var encoders=exports;encoders.der=require("./der");encoders.pem=require("./pem")},{"./der":80,"./pem":82}],82:[function(require,module,exports){var inherits=require("inherits");var DEREncoder=require("./der");function PEMEncoder(entity){DEREncoder.call(this,entity);this.enc="pem"}inherits(PEMEncoder,DEREncoder);module.exports=PEMEncoder;PEMEncoder.prototype.encode=function encode(data,options){var buf=DEREncoder.prototype.encode.call(this,data);var p=buf.toString("base64");var out=["-----BEGIN "+options.label+"-----"];for(var i=0;i0){bits.ishrn(shift)}return bits}function bits2octets(bits,q){bits=bits2int(bits,q);bits=bits.mod(q);var out=new Buffer(bits.toArray());if(out.length=q){throw new Error("invalid sig")}}module.exports=verify}).call(this,require("buffer").Buffer)},{"./curves":38,"bn.js":39,buffer:2,elliptic:41,"parse-asn1":68}],104:[function(require,module,exports){(function(Buffer){var elliptic=require("elliptic");var BN=require("bn.js");module.exports=function createECDH(curve){return new ECDH(curve)};var aliases={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};aliases.p224=aliases.secp224r1;aliases.p256=aliases.secp256r1=aliases.prime256v1;aliases.p192=aliases.secp192r1=aliases.prime192v1;aliases.p384=aliases.secp384r1;aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve];if(!this.curveType){this.curveType={name:curve}}this.curve=new elliptic.ec(this.curveType.name);this.keys=void 0}ECDH.prototype.generateKeys=function(enc,format){this.keys=this.curve.genKeyPair();return this.getPublicKey(enc,format)};ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||"utf8";if(!Buffer.isBuffer(other)){other=new Buffer(other,inenc)}var otherPub=this.curve.keyFromPublic(other).getPublic();var out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)};ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format==="compressed",true);if(format==="hybrid"){if(key[key.length-1]%2){key[0]=7}else{key[0]=6}}return formatReturnValue(key,enc)};ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)};ECDH.prototype.setPublicKey=function(pub,enc){enc=enc||"utf8";if(!Buffer.isBuffer(pub)){pub=new Buffer(pub,enc)}this.keys._importPublic(pub);return this};ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||"utf8";if(!Buffer.isBuffer(priv)){priv=new Buffer(priv,enc)}var _priv=new BN(priv);_priv=_priv.toString(16);this.keys._importPrivate(_priv);return this};function formatReturnValue(bn,enc,len){if(!Array.isArray(bn)){bn=bn.toArray()}var buf=new Buffer(bn);if(len&&buf.length=6.0.0 <7.0.0",_npmVersion:"3.10.3",_nodeVersion:"6.3.0",_npmUser:{name:"indutny",email:"fedor@indutny.com"},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},maintainers:[{name:"indutny",email:"fedor@indutny.com"}],_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},directories:{},_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"}},{}],130:[function(require,module,exports){(function(Buffer){"use strict";var inherits=require("inherits");var md5=require("./md5");var rmd160=require("ripemd160");var sha=require("sha.js");var Base=require("cipher-base");function HashNoConstructor(hash){Base.call(this,"digest");this._hash=hash;this.buffers=[]}inherits(HashNoConstructor,Base);HashNoConstructor.prototype._update=function(data){this.buffers.push(data)};HashNoConstructor.prototype._final=function(){var buf=Buffer.concat(this.buffers);var r=this._hash(buf);this.buffers=null;return r};function Hash(hash){Base.call(this,"digest");this._hash=hash}inherits(Hash,Base);Hash.prototype._update=function(data){this._hash.update(data)};Hash.prototype._final=function(){return this._hash.digest()};module.exports=function createHash(alg){alg=alg.toLowerCase();if("md5"===alg)return new HashNoConstructor(md5);if("rmd160"===alg||"ripemd160"===alg)return new HashNoConstructor(rmd160);return new Hash(sha(alg))}}).call(this,require("buffer").Buffer)},{"./md5":132,buffer:2,"cipher-base":133,inherits:200,ripemd160:134,"sha.js":136}],131:[function(require,module,exports){(function(Buffer){"use strict";var intSize=4;var zeroBuffer=new Buffer(intSize);zeroBuffer.fill(0);var chrsz=8;function toArray(buf,bigEndian){if(buf.length%intSize!==0){var len=buf.length+(intSize-buf.length%intSize);buf=Buffer.concat([buf,zeroBuffer],len)}var arr=[];var fn=bigEndian?buf.readInt32BE:buf.readInt32LE;for(var i=0;i>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":131}],133:[function(require,module,exports){arguments[4][23][0].apply(exports,arguments)},{buffer:2,dup:23,inherits:200,stream:219,string_decoder:220}],134:[function(require,module,exports){(function(Buffer){var zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13];var zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11];var sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6];var sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];var hl=[0,1518500249,1859775393,2400959708,2840853838];var hr=[1352829926,1548603684,1836072691,2053994217,0];function bytesToWords(bytes){var words=[];for(var i=0,b=0;i>>5]|=bytes[i]<<24-b%32}return words}function wordsToBytes(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes}function processBlock(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t}function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message==="string"){message=new Buffer(message,"utf8")}var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}module.exports=ripemd160}).call(this,require("buffer").Buffer)},{buffer:2}],135:[function(require,module,exports){(function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.update=function(data,enc){if(typeof data==="string"){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};module.exports=Hash}).call(this,require("buffer").Buffer)},{buffer:2}],136:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha");exports.sha1=require("./sha1");exports.sha224=require("./sha224");exports.sha256=require("./sha256");exports.sha384=require("./sha384");exports.sha512=require("./sha512")},{"./sha":137,"./sha1":138,"./sha224":139,"./sha256":140,"./sha384":141,"./sha512":142}],137:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha,Hash);Sha.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],138:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha1(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha1.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha1.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha1}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],139:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Sha256=require("./sha256");var Hash=require("./hash");var W=new Array(64);function Sha224(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha224,Sha256);Sha224.prototype.init=function(){this._a=3238371032;this._b=914150663;this._c=812702999;this._d=4144912697;this._e=4290775857;this._f=1750603025;this._g=1694076839;this._h=3204075428;return this};Sha224.prototype._hash=function(){var H=new Buffer(28);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);return H};module.exports=Sha224}).call(this,require("buffer").Buffer)},{"./hash":135,"./sha256":140,buffer:2,inherits:200}],140:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703;this._b=3144134277;this._c=1013904242;this._d=2773480762;this._e=1359893119;this._f=2600822924;this._g=528734635;this._h=1541459225;return this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;var f=this._f|0;var g=this._g|0;var h=this._h|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<64;++i)W[i]=gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W[j]|0;var T2=sigma0(a)+maj(a,b,c)|0;h=g;g=f;f=e;e=d+T1|0;d=c;c=b;b=a;a=T1+T2|0}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};module.exports=Sha256}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],141:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var SHA512=require("./sha512");var Hash=require("./hash");var W=new Array(160);function Sha384(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha384,SHA512);Sha384.prototype.init=function(){this._ah=3418070365;this._bh=1654270250;this._ch=2438529370;this._dh=355462360;this._eh=1731405415;this._fh=2394180231;this._gh=3675008525;this._hh=1203062813;this._al=3238371032;this._bl=914150663;this._cl=812702999;this._dl=4144912697;this._el=4290775857;this._fl=1750603025;this._gl=1694076839;this._hl=3204075428;return this};Sha384.prototype._hash=function(){var H=new Buffer(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);return H};module.exports=Sha384}).call(this,require("buffer").Buffer)},{"./hash":135, +"./sha512":142,buffer:2,inherits:200}],142:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._ah=1779033703;this._bh=3144134277;this._ch=1013904242;this._dh=2773480762;this._eh=1359893119;this._fh=2600822924;this._gh=528734635;this._hh=1541459225;this._al=4089235720;this._bl=2227873595;this._cl=4271175723;this._dl=1595750129;this._el=2917565137;this._fl=725511199;this._gl=4215389547;this._hl=327033209;return this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}Sha512.prototype._update=function(M){var W=this._w;var ah=this._ah|0;var bh=this._bh|0;var ch=this._ch|0;var dh=this._dh|0;var eh=this._eh|0;var fh=this._fh|0;var gh=this._gh|0;var hh=this._hh|0;var al=this._al|0;var bl=this._bl|0;var cl=this._cl|0;var dl=this._dl|0;var el=this._el|0;var fl=this._fl|0;var gl=this._gl|0;var hl=this._hl|0;for(var i=0;i<32;i+=2){W[i]=M.readInt32BE(i*4);W[i+1]=M.readInt32BE(i*4+4)}for(;i<160;i+=2){var xh=W[i-15*2];var xl=W[i-15*2+1];var gamma0=Gamma0(xh,xl);var gamma0l=Gamma0l(xl,xh);xh=W[i-2*2];xl=W[i-2*2+1];var gamma1=Gamma1(xh,xl);var gamma1l=Gamma1l(xl,xh);var Wi7h=W[i-7*2];var Wi7l=W[i-7*2+1];var Wi16h=W[i-16*2];var Wi16l=W[i-16*2+1];var Wil=gamma0l+Wi7l|0;var Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0;Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0;Wil=Wil+Wi16l|0;Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0;W[i]=Wih;W[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W[j];Wil=W[j+1];var majh=maj(ah,bh,ch);var majl=maj(al,bl,cl);var sigma0h=sigma0(ah,al);var sigma0l=sigma0(al,ah);var sigma1h=sigma1(eh,el);var sigma1l=sigma1(el,eh);var Kih=K[j];var Kil=K[j+1];var chh=Ch(eh,fh,gh);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l|0;var t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0;t1h=t1h+chh+getCarry(t1l,chl)|0;t1l=t1l+Kil|0;t1h=t1h+Kih+getCarry(t1l,Kil)|0;t1l=t1l+Wil|0;t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0;var t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh;hl=gl;gh=fh;gl=fl;fh=eh;fl=el;el=dl+t1l|0;eh=dh+t1h+getCarry(el,dl)|0;dh=ch;dl=cl;ch=bh;cl=bl;bh=ah;bl=al;al=t1l+t2l|0;ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._ah=this._ah+ah+getCarry(this._al,al)|0;this._bh=this._bh+bh+getCarry(this._bl,bl)|0;this._ch=this._ch+ch+getCarry(this._cl,cl)|0;this._dh=this._dh+dh+getCarry(this._dl,dl)|0;this._eh=this._eh+eh+getCarry(this._el,el)|0;this._fh=this._fh+fh+getCarry(this._fl,fl)|0;this._gh=this._gh+gh+getCarry(this._gl,gl)|0;this._hh=this._hh+hh+getCarry(this._hl,hl)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);writeInt64BE(this._gh,this._gl,48);writeInt64BE(this._hh,this._hl,56);return H};module.exports=Sha512}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],143:[function(require,module,exports){(function(Buffer){"use strict";var createHash=require("create-hash/browser");var inherits=require("inherits");var Transform=require("stream").Transform;var ZEROS=new Buffer(128);ZEROS.fill(0);function Hmac(alg,key){Transform.call(this);alg=alg.toLowerCase();if(typeof key==="string"){key=new Buffer(key)}var blocksize=alg==="sha512"||alg==="sha384"?128:64;this._alg=alg;this._key=key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.lengthbits){num.ishrn(1)}if(num.isEven()){num.iadd(ONE)}if(!num.testn(1)){num.iadd(TWO)}if(!gen.cmp(TWO)){while(num.mod(TWENTYFOUR).cmp(ELEVEN)){num.iadd(FOUR)}}else if(!gen.cmp(FIVE)){while(num.mod(TEN).cmp(THREE)){num.iadd(FOUR)}}n2=num.shrn(1);if(simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num)){return num}}}},{"bn.js":148,"miller-rabin":149,randombytes:198}],147:[function(require,module,exports){module.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],148:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39}],149:[function(require,module,exports){var bn=require("bn.js");var brorand=require("brorand");function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin;MillerRabin.create=function create(rand){return new MillerRabin(rand)};MillerRabin.prototype._rand=function _rand(n){var len=n.bitLength();var buf=this.rand.generate(Math.ceil(len/8));buf[0]|=3;var mask=len&7;if(mask!==0)buf[buf.length-1]>>=7-mask;return new bn(buf)};MillerRabin.prototype.test=function test(n,k,cb){var len=n.bitLength();var red=bn.mont(n);var rone=new bn(1).toRed(red);if(!k)k=Math.max(1,len/48|0);var n1=n.subn(1);var n2=n1.subn(1);for(var s=0;!n1.testn(s);s++){}var d=n.shrn(s);var rn1=n1.toRed(red);var prime=true;for(;k>0;k--){var a=this._rand(n2);if(cb)cb(a);var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i0;k--){var a=this._rand(n2);var g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i=6?"utf-8":"binary"}exports.pbkdf2Sync=function(password,salt,iterations,keylen,digest){if(!Buffer.isBuffer(password))password=new Buffer(password,defaultEncoding);if(!Buffer.isBuffer(salt))salt=new Buffer(salt,defaultEncoding);checkParameters(iterations,keylen);digest=digest||"sha1";var hLen;var l=1;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);var r;var T;for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen}U.copy(T,0,0,hLen);for(var j=1;jMAX_ALLOC||keylen!==keylen){throw new TypeError("Bad key length")}}},{}],153:[function(require,module,exports){exports.publicEncrypt=require("./publicEncrypt");exports.privateDecrypt=require("./privateDecrypt");exports.privateEncrypt=function privateEncrypt(key,buf){return exports.publicEncrypt(key,buf,true)};exports.publicDecrypt=function publicDecrypt(key,buf){return exports.privateDecrypt(key,buf,true)}},{"./privateDecrypt":194,"./publicEncrypt":195}],154:[function(require,module,exports){(function(Buffer){var createHash=require("create-hash");module.exports=function(seed,len){var t=new Buffer("");var i=0,c;while(t.lengthk||new bn(enc).cmp(key.modulus)>=0){throw new Error("decryption error")}var msg;if(reverse){msg=withPublic(new bn(enc),key)}else{msg=crt(enc,key)}var zBuffer=new Buffer(k-msg.length);zBuffer.fill(0);msg=Buffer.concat([zBuffer,msg],k);if(padding===4){return oaep(key,msg)}else if(padding===1){return pkcs1(key,msg,reverse)}else if(padding===3){return msg}else{throw new Error("unknown padding")}};function oaep(key,msg){var n=key.modulus;var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(msg[0]!==0){throw new Error("decryption error")}var maskedSeed=msg.slice(1,hLen+1);var maskedDb=msg.slice(hLen+1);var seed=xor(maskedSeed,mgf(maskedDb,hLen));var db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen))){throw new Error("decryption error")}var i=hLen;while(db[i]===0){i++}if(db[i++]!==1){throw new Error("decryption error")}return db.slice(i)}function pkcs1(key,msg,reverse){var p1=msg.slice(0,2);var i=2;var status=0;while(msg[i++]!==0){if(i>=msg.length){status++;break}}var ps=msg.slice(2,i-1);var p2=msg.slice(i-1,i);if(p1.toString("hex")!=="0002"&&!reverse||p1.toString("hex")!=="0001"&&reverse){status++}if(ps.length<8){status++}if(status){throw new Error("decryption error")}return msg.slice(i)}function compare(a,b){a=new Buffer(a);b=new Buffer(b);var dif=0;var len=a.length;if(a.length!==b.length){dif++;len=Math.min(a.length,b.length)}var i=-1;while(++i=0){throw new Error("data too long for modulus")}}else{throw new Error("unknown padding")}if(reverse){return crt(paddedMsg,key)}else{return withPublic(paddedMsg,key)}};function oaep(key,msg){var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(mLen>k-hLen2-2){throw new Error("message too long")}var ps=new Buffer(k-mLen-hLen2-2);ps.fill(0);var dblen=k-hLen-1;var seed=randomBytes(hLen);var maskedDb=xor(Buffer.concat([iHash,ps,new Buffer([1]),msg],dblen),mgf(seed,dblen));var maskedSeed=xor(seed,mgf(maskedDb,hLen));return new bn(Buffer.concat([new Buffer([0]),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length;var k=key.modulus.byteLength();if(mLen>k-11){throw new Error("message too long")}var ps;if(reverse){ps=new Buffer(k-mLen-3);ps.fill(255)}else{ps=nonZero(k-mLen-3)}return new bn(Buffer.concat([new Buffer([0,reverse?1:2]),ps,new Buffer([0]),msg],k))}function nonZero(len,crypto){var out=new Buffer(len);var i=0;var cache=randomBytes(len*2);var cur=0;var num;while(i65536)throw new Error("requested too many random bytes");var rawBytes=new global.Uint8Array(size);if(size>0){crypto.getRandomValues(rawBytes)}var bytes=new Buffer(rawBytes.buffer);if(typeof cb==="function"){return process.nextTick(function(){cb(null,bytes)})}return bytes}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{_process:202,buffer:2}],199:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],200:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],201:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],202:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var _i=0;_i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}var Duplex;function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode; +if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function writableStateGetBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var Duplex;function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:2,"buffer-shims":210}],210:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:2}],211:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":201}],212:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],213:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:2}],221:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(obj){if(Object.keys)return Object.keys(obj);else{var res=[];for(var key in obj)res.push(key);return res}};var forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);else for(var i=0;i2&&arguments[2]!==undefined?arguments[2]:{};var _ref$password=_ref.password;var password=_ref$password===undefined?{length:12}:_ref$password;var _ref$counter=_ref.counter;var counter=_ref$counter===undefined?1:_ref$counter;var salt=site+counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",hash).update(salt).digest("hex");return derivedHash.substring(0,password.length)}function _getTemplate(){var passwordTypes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:["strong"];var passwordTypesInfo={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return passwordTypes.map(function(passwordType){return passwordTypesInfo[passwordType]}).sort(function(passwordType1,passwordType2){return passwordType1.order>passwordType2.order}).map(function(passwordType){return passwordType.value}).join("")}function _prettyPrint(hash,template){var password="";_string2charCodes(hash).forEach(function(charCode,index){var charType=_getCharType(template,index);password+=_getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i dist/lesspass.min.js", "babelify": "babel src/lesspass.js -o lib/lesspass.js", "build": "rm -rf dist lib && mkdir dist lib && npm run browserify && npm run babelify", @@ -39,8 +39,7 @@ "karma-ava": "0.0.1", "karma-chrome-launcher": "^1.0.1", "karma-firefox-launcher": "^1.0.0", - "uglify-js": "^2.6.4", - "xo": "^0.16.0" + "uglify-js": "^2.6.4" }, "babel": { "presets": [ @@ -52,20 +51,6 @@ "babelify" ] }, - "xo": { - "esnext": true, - "space": true, - "envs": [ - "browser", - "webextensions", - "shared-node-browser", - "es6" - ], - "ignores": [ - "lib/**", - "tests/node.js" - ] - }, "ava": { "files": [ "tests/*.js", diff --git a/src/lesspass2.js b/src/lesspass2.js new file mode 100644 index 0000000..b8ada88 --- /dev/null +++ b/src/lesspass2.js @@ -0,0 +1,86 @@ +import crypto from 'crypto'; + +export default { + encryptLogin(login, masterPassword) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) + }, + + renderPassword(site, encryptedLogin, passwordOptions) { + const derivedHash = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); + const template = this._getPasswordTemplate(passwordOptions); + return this._prettyPrint(derivedHash, template); + }, + + _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { + const salt = site + passwordOptions.counter.toString(); + const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); + return derivedHash.substring(0, passwordOptions.length); + }, + + _getPasswordTemplate(passwordTypes) { + const templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + let template = ''; + for (let templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] + } + } + return template; + }, + + _prettyPrint(hash, template) { + let password = ''; + + this._string2charCodes(hash).forEach((charCode, index) => { + const charType = this._getCharType(template, index); + password += this._getPasswordChar(charType, charCode); + }); + return password; + }, + + _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; + }, + + _getCharType(template, index) { + return template[index % template.length]; + }, + + _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; + } +} diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js new file mode 100644 index 0000000..d612fc6 --- /dev/null +++ b/tests/deriveEncryptedLogin.tests.js @@ -0,0 +1,62 @@ +import test from 'ava'; +import lesspass from '../src/lesspass2'; + +test('should derive encrypted login with default length', t => { + const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + t.is(12, lesspass._deriveEncryptedLogin(encryptedLogin, site).length); +}); + +test('should derive encrypted login with default options', t => { + const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + const site = 'lesspass.com'; + const option = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + }; + t.is( + lesspass._deriveEncryptedLogin(encryptedLogin, site), + lesspass._deriveEncryptedLogin(encryptedLogin, site, option) + ); +}); + +test('should derive encrypted login with defined length', t => { + const encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; + const site = 'lesspass.com'; + const option = { + counter: 1, + length: 10, + }; + t.is(10, lesspass._deriveEncryptedLogin(encryptedLogin, site, option).length); +}); + +test('should return two different passwords if site different', t => { + const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'google.com'; + const site2 = 'facebook.com'; + t.not( + lesspass._deriveEncryptedLogin(encryptedLogin, site), + lesspass._deriveEncryptedLogin(encryptedLogin, site2) + ); +}); + +test('should return two different passwords if counter different', t => { + const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option = {counter: 1}; + const option2 = {counter: 2}; + t.not( + lesspass._deriveEncryptedLogin(encryptedLogin, site, option), + lesspass._deriveEncryptedLogin(encryptedLogin, site, option2) + ); +}); + +test('should derive encrypted login with sha 256', t => { + const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + t.is('be00f942fc8a', lesspass._deriveEncryptedLogin(encryptedLogin, site)); +}); diff --git a/tests/getPasswordTemplate.tests.js b/tests/getPasswordTemplate.tests.js new file mode 100644 index 0000000..90d4703 --- /dev/null +++ b/tests/getPasswordTemplate.tests.js @@ -0,0 +1,55 @@ +import test from 'ava'; +import lesspass from '../src/lesspass2'; + +test('should get default template', t => { + t.is('vcVCns', lesspass._getPasswordTemplate({ + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + })); +}); + +test('should get template from password setting', t => { + t.is('vc', lesspass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: false, + symbols: false + })); + t.is('VC', lesspass._getPasswordTemplate({ + lowercase: false, + uppercase: true, + numbers: false, + symbols: false + })); + t.is('n', lesspass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: true, + symbols: false + })); + t.is('s', lesspass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + })); +}); + +test('should concatenate template if two password settings', t => { + t.is('vcVC', lesspass._getPasswordTemplate({ + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + })); + t.is('vcns', lesspass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: true, + symbols: true + })); +}); diff --git a/tests/karma.conf.js b/tests/karma.conf.js deleted file mode 100644 index eb97c35..0000000 --- a/tests/karma.conf.js +++ /dev/null @@ -1,20 +0,0 @@ -module.exports = function (config) { - config.set({ - basePath: '..', - frameworks: ['mocha', 'chai'], - files: [ - 'src/**/*.js', - 'test/**/*.js' - ], - exclude: [], - preprocessors: {}, - reporters: ['progress'], - port: 9876, - colors: true, - logLevel: config.LOG_DISABLE, - singleRun: false, - autoWatch: true, - browsers: ['Firefox', 'Chrome'], - concurrency: Infinity - }); -}; diff --git a/tests/new.api.tests.js b/tests/new.api.tests.js new file mode 100644 index 0000000..5856f70 --- /dev/null +++ b/tests/new.api.tests.js @@ -0,0 +1,28 @@ +import test from 'ava'; +import lesspass from '../src/lesspass2'; + +test('encrypt login', t => { + return lesspass.encryptLogin('test@example.org', 'password').then(encryptedLogin => { + t.is('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); + }) +}); + +test('encrypt login with utf8 parameter', t => { + return lesspass.encryptLogin('test@example.org', '♥ LessPass ♥').then(encryptedLogin => { + t.is('063092c809334979f505df88ed37845d298c01f7e8a03cbd661edbc084c650ca', encryptedLogin); + }) +}); + +test('render password', t => { + const site = 'lesspass.com'; + const encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + const passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + t.is('azYS7,olOL2]', lesspass.renderPassword(site, encryptedLogin, passwordOptions)); +}); diff --git a/tests/prettyPrint.js b/tests/prettyPrint.js new file mode 100644 index 0000000..c4e51fe --- /dev/null +++ b/tests/prettyPrint.js @@ -0,0 +1,37 @@ +import test from 'ava'; +import lesspass from '../src/lesspass2'; + +test('should print different password if templates different', t => { + const encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; + t.not(lesspass._prettyPrint(encryptedLogin, 'cv'), lesspass._prettyPrint(encryptedLogin, 'vc')); +}); + +test('must return a string of the same length as the input', t => { + const hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; + t.is(hash.length, lesspass._prettyPrint(hash, 'cv').length); +}); + +test('should return char inside a string based on modulo of the index', t => { + const template = 'cv'; + t.is('c', lesspass._getCharType(template, 0)); + t.is('v', lesspass._getCharType(template, 1)); + t.is('c', lesspass._getCharType(template, 10)); +}); + +test('should convert a string into an array of char code', t => { + const charCodes = lesspass._string2charCodes('ab40f6ee71'); + t.is(97, charCodes[0]); + t.is(98, charCodes[1]); + t.is(10, charCodes.length); +}); + +test('should get password char based on its type and index', t => { + const typeVowel = 'V'; + t.is('A', lesspass._getPasswordChar(typeVowel, 0)); +}); + +test('should modulo if overflow', t => { + const typeVowel = 'V'; + t.is('E', lesspass._getPasswordChar(typeVowel, 1)); + t.is('E', lesspass._getPasswordChar(typeVowel, 7)); +}); From 76c69ce04e87cad61fa496b514972d636061af45 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 30 Sep 2016 17:45:02 +0200 Subject: [PATCH 033/124] clean test with new api --- src/lesspass.js | 172 ++++++++--------- src/lesspass2.js | 86 --------- tests/api.tests.js | 358 +++++++++++++++++++++++------------- tests/deriveEncryptedLogin.tests.js | 2 +- tests/getPasswordTemplate.tests.js | 2 +- tests/index.html | 17 +- tests/lesspass.tests.js | 137 -------------- tests/new.api.tests.js | 28 --- tests/node.js | 19 +- tests/prettyPrint.js | 2 +- 10 files changed, 327 insertions(+), 496 deletions(-) delete mode 100644 src/lesspass2.js delete mode 100644 tests/lesspass.tests.js delete mode 100644 tests/new.api.tests.js diff --git a/src/lesspass.js b/src/lesspass.js index 6ce3240..ed29748 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -1,108 +1,86 @@ import crypto from 'crypto'; -module.exports = { - generatePassword: _generatePassword, - encryptLogin: _encryptLogin, - renderPassword: _renderPassword, - _deriveHash, - _prettyPrint, - _getTemplate, - _getCharType, - _getPasswordChar, - _string2charCodes -}; +export default { + encryptLogin(login, masterPassword) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) + }, -function _generatePassword(login, masterPassword, site, options) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword || !site) { - reject('generatePassword invalid parameter'); - } + deriveEncryptedLogin(encryptedLogin, site, passwordOptions) { + const derivedHash = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); + const template = this._getPasswordTemplate(passwordOptions); + return this._prettyPrint(derivedHash, template); + }, - _encryptLogin(login, masterPassword).then(hash => { - resolve(_renderPassword(hash, site, options)); - }); - }); -} + _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { + const salt = site + passwordOptions.counter.toString(); + const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); + return derivedHash.substring(0, passwordOptions.length); + }, -function _renderPassword(hash, site, options) { - const derivedHash = _deriveHash(hash, site, options); - const template = _getTemplate(options.password.settings); - return _prettyPrint(derivedHash, template); -} + _getPasswordTemplate(passwordTypes) { + const templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + let template = ''; + for (let templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] + } + } + return template; + }, -function _encryptLogin(login, masterPassword) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword) { - reject('encryptLogin parameter could not be empty'); - } - const iterations = 8192; - const keylen = 32; - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }); -} + _prettyPrint(hash, template) { + let password = ''; -function _deriveHash(hash, site, {password = {length: 12}, counter = 1} = {}) { - const salt = site + counter.toString(); - const derivedHash = crypto.createHmac('sha256', hash).update(salt).digest('hex'); - return derivedHash.substring(0, password.length); -} + this._string2charCodes(hash).forEach((charCode, index) => { + const charType = this._getCharType(template, index); + password += this._getPasswordChar(charType, charCode); + }); + return password; + }, -function _getTemplate(passwordTypes = ['strong']) { - const passwordTypesInfo = { - lowercase: {value: 'vc', order: 1}, - uppercase: {value: 'VC', order: 2}, - numbers: {value: 'n', order: 3}, - symbols: {value: 's', order: 4}, - strong: {value: 'Cvcvns', order: 5} - }; - return passwordTypes - .map(passwordType => passwordTypesInfo[passwordType]) - .sort((passwordType1, passwordType2) => passwordType1.order > passwordType2.order) - .map(passwordType => passwordType.value) - .join(''); -} + _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; + }, -function _prettyPrint(hash, template) { - let password = ''; + _getCharType(template, index) { + return template[index % template.length]; + }, - _string2charCodes(hash).forEach((charCode, index) => { - const charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; -} - -function _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} - -function _getCharType(template, index) { - return template[index % template.length]; -} - -function _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; + _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; + } } - diff --git a/src/lesspass2.js b/src/lesspass2.js deleted file mode 100644 index b8ada88..0000000 --- a/src/lesspass2.js +++ /dev/null @@ -1,86 +0,0 @@ -import crypto from 'crypto'; - -export default { - encryptLogin(login, masterPassword) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); - } - const iterations = 8192; - const keylen = 32; - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }) - }, - - renderPassword(site, encryptedLogin, passwordOptions) { - const derivedHash = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); - const template = this._getPasswordTemplate(passwordOptions); - return this._prettyPrint(derivedHash, template); - }, - - _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { - const salt = site + passwordOptions.counter.toString(); - const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); - return derivedHash.substring(0, passwordOptions.length); - }, - - _getPasswordTemplate(passwordTypes) { - const templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - let template = ''; - for (let templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] - } - } - return template; - }, - - _prettyPrint(hash, template) { - let password = ''; - - this._string2charCodes(hash).forEach((charCode, index) => { - const charType = this._getCharType(template, index); - password += this._getPasswordChar(charType, charCode); - }); - return password; - }, - - _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; - }, - - _getCharType(template, index) { - return template[index % template.length]; - }, - - _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; - } -} diff --git a/tests/api.tests.js b/tests/api.tests.js index c3aff6a..e26f7d4 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -1,144 +1,242 @@ import test from 'ava'; import lesspass from '../src/lesspass'; -test('generate password', t => { - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; - const site = 'lesspass.com'; - const options = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } - }; - return lesspass.generatePassword(login, masterPassword, site, options).then(password => { - t.is(password, 'azYS7,olOL2]'); - }); +test('encrypt login', t => { + return lesspass.encryptLogin('test@example.org', 'password').then(encryptedLogin => { + t.is('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); + }) }); -test('generate password2', t => { - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; - const site = 'lesspass.com'; - const options = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } - }; - return lesspass.generatePassword(login, masterPassword, site, options).then(password => { - t.is(password, 'azYS7,olOL2]'); - }); +test('encrypt login with utf8 parameter', t => { + return lesspass.encryptLogin('test@example.org', '♥ LessPass ♥').then(encryptedLogin => { + t.is('063092c809334979f505df88ed37845d298c01f7e8a03cbd661edbc084c650ca', encryptedLogin); + }) }); -test('generate password3', t => { - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; - const site = 'lesspass.com'; - const options = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } - }; - return lesspass.generatePassword(login, masterPassword, site, options).then(password => { - t.is(password, 'azYS7,olOL2]'); - }); +test('render password', t => { + const site = 'lesspass.com'; + const encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + const passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + t.is('azYS7,olOL2]', lesspass.deriveEncryptedLogin(encryptedLogin, site, passwordOptions)); }); -test('auto generated password', t => { - const promises = []; - const entries = [ - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'azYS7,olOL2]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 14, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'azYS7,olOL2]iz' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase']}}, - generatedPassword: 'azyseqololat' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'AZ3[EQ7@OL2]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['numbers', 'symbols']}}, - generatedPassword: '4?3[7,7@7@2]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['symbols']}}, - generatedPassword: '[?=[&,:@:@[]' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers']}}, - generatedPassword: 'azYS7uwAW8at' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase']}}, - generatedPassword: 'azYSeqOLolAT' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 2, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'obYT2=olOV9=' - }, - { - login: 'lesspass', - masterPassword: 'password', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'erOC1%imIW3,' - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password2', - site: 'lesspass.com', - options: {counter: 1, password: {length: 12, settings: ['lowercase', 'uppercase', 'numbers', 'symbols']}}, - generatedPassword: 'uvUM5_ucUP5=' + +test('auto generated encrypt login tests', t => { + const promises = []; + const passwords = [ + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'lesspass', + masterPassword: 'password', + encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password2', + encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', + } + ]; + + for (const entry of passwords) { + promises.push(lesspass.encryptLogin(entry.login, entry.masterPassword)); } - ]; - for (const entry of entries) { - promises.push(lesspass.generatePassword(entry.login, entry.masterPassword, entry.site, entry.options)); - } + t.plan(passwords.length); + return Promise.all(promises).then(values => { + for (let i = 0; i < values.length; i++) { + t.is(passwords[i].encryptedLogin, values[i]); + } + }); +}); + +test('auto generated derive encrypted login tests', t => { + const passwords = [ + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'azYS7,olOL2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 14, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'azYS7,olOL2]iz' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: false, + numbers: false, + symbols: false, + generatedPassword: 'azyseqololat' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'AZ3[EQ7@OL2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: true, + symbols: true, + generatedPassword: '4?3[7,7@7@2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: false, + symbols: true, + generatedPassword: '[?=[&,:@:@[]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + generatedPassword: 'azYS7uwAW8at' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: false, + symbols: false, + generatedPassword: 'azYSeqOLolAT' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 2, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'obYT2=olOV9=' + }, + { + encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'erOC1%imIW3,' + }, + { + encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'uvUM5_ucUP5=' + } + ]; + - t.plan(entries.length); - return Promise.all(promises).then(values => { - for (let i = 0; i < values.length; i++) { - t.is(entries[i].generatedPassword, values[i], JSON.stringify(entries[i], null, 2)); + t.plan(passwords.length); + for (let i = 0; i < passwords.length; i++) { + let password = passwords[i]; + let passwordOption = { + counter: password.counter, + length: password.length, + lowercase: password.lowercase, + uppercase: password.uppercase, + numbers: password.numbers, + symbols: password.symbols, + }; + t.is(password.generatedPassword, lesspass.deriveEncryptedLogin(password.encryptedLogin, password.site, passwordOption)); } - }); }); diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js index d612fc6..b851206 100644 --- a/tests/deriveEncryptedLogin.tests.js +++ b/tests/deriveEncryptedLogin.tests.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass2'; +import lesspass from '../src/lesspass'; test('should derive encrypted login with default length', t => { const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; diff --git a/tests/getPasswordTemplate.tests.js b/tests/getPasswordTemplate.tests.js index 90d4703..2946429 100644 --- a/tests/getPasswordTemplate.tests.js +++ b/tests/getPasswordTemplate.tests.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass2'; +import lesspass from '../src/lesspass'; test('should get default template', t => { t.is('vcVCns', lesspass._getPasswordTemplate({ diff --git a/tests/index.html b/tests/index.html index ef2ea22..3b8c66f 100644 --- a/tests/index.html +++ b/tests/index.html @@ -6,21 +6,24 @@ - \ No newline at end of file + diff --git a/tests/lesspass.tests.js b/tests/lesspass.tests.js deleted file mode 100644 index d255daf..0000000 --- a/tests/lesspass.tests.js +++ /dev/null @@ -1,137 +0,0 @@ -import test from 'ava'; -import lesspass from '../src/lesspass'; - -test('should create encrypted hash with pbkdf2 (8192 iterations and sha 256)', t => { - const login = 'test@lesspass.com'; - const masterPassword = 'password'; - - return lesspass.encryptLogin(login, masterPassword).then(hash => { - t.is('90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d', hash); - }); -}); - -test('should create encrypted hash with 64 chars length', t => { - return lesspass.encryptLogin('♥', '♥ ♥').then(hash => { - t.is(64, hash.length); - }); -}); - -test('should reject promise if no parameter', t => { - t.plan(1); - return lesspass.encryptLogin('', '').catch(() => { - t.pass('promise rejected with empty parameter'); - }); -}); - -test('should derive hash with default length', t => { - const hash = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - t.is(12, lesspass._deriveHash(hash, site).length); -}); - -test('should derive hash with default options', t => { - const hash = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - const option = { - counter: 1, - password: { - length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } - }; - t.is( - lesspass._deriveHash(hash, site), - lesspass._deriveHash(hash, site, option) - ); -}); - -test('should derive hash with defined length', t => { - const hash = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - const site = 'lesspass.com'; - const option = { - counter: 1, - password: { - length: 10 - } - }; - t.is(10, lesspass._deriveHash(hash, site, option).length); -}); - -test('should return two different passwords if site different', t => { - const hash = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'google.com'; - const site2 = 'facebook.com'; - t.not( - lesspass._deriveHash(hash, site), - lesspass._deriveHash(hash, site2) - ); -}); - -test('should return two different passwords if counter different', t => { - const hash = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option = {counter: 1}; - const option2 = {counter: 2}; - t.not( - lesspass._deriveHash(hash, site, option), - lesspass._deriveHash(hash, site, option2) - ); -}); - -test('should print different password if templates different', t => { - const hash = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; - t.not(lesspass._prettyPrint(hash, 'cv'), lesspass._prettyPrint(hash, 'vc')); -}); - -test('must return a string of the same length as the input', t => { - const hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; - t.is(hash.length, lesspass._prettyPrint(hash, 'cv').length); -}); - -test('should return char inside a string based on modulo of the index', t => { - const template = 'cv'; - t.is('c', lesspass._getCharType(template, 0)); - t.is('v', lesspass._getCharType(template, 1)); - t.is('c', lesspass._getCharType(template, 10)); -}); - -test('should convert a string into an array of char code', t => { - const charCodes = lesspass._string2charCodes('ab40f6ee71'); - t.is(97, charCodes[0]); - t.is(98, charCodes[1]); - t.is(10, charCodes.length); -}); - -test('should get password char based on its type and index', t => { - const typeVowel = 'V'; - t.is('A', lesspass._getPasswordChar(typeVowel, 0)); -}); - -test('should modulo if overflow', t => { - const typeVowel = 'V'; - t.is('E', lesspass._getPasswordChar(typeVowel, 1)); - t.is('E', lesspass._getPasswordChar(typeVowel, 7)); -}); - -test('should get default template', t => { - t.is('Cvcvns', lesspass._getTemplate()); -}); - -test('should get template from password setting', t => { - t.is('vc', lesspass._getTemplate(['lowercase'])); - t.is('VC', lesspass._getTemplate(['uppercase'])); - t.is('n', lesspass._getTemplate(['numbers'])); - t.is('s', lesspass._getTemplate(['symbols'])); -}); - -test('should concatenate template if two password settings', t => { - t.is('vcVC', lesspass._getTemplate(['lowercase', 'uppercase'])); - t.is('vcns', lesspass._getTemplate(['lowercase', 'numbers', 'symbols'])); -}); - -test('should not care about order of password settings', t => { - t.is( - lesspass._getTemplate(['uppercase', 'lowercase']), - lesspass._getTemplate(['lowercase', 'uppercase']) - ); -}); diff --git a/tests/new.api.tests.js b/tests/new.api.tests.js deleted file mode 100644 index 5856f70..0000000 --- a/tests/new.api.tests.js +++ /dev/null @@ -1,28 +0,0 @@ -import test from 'ava'; -import lesspass from '../src/lesspass2'; - -test('encrypt login', t => { - return lesspass.encryptLogin('test@example.org', 'password').then(encryptedLogin => { - t.is('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); - }) -}); - -test('encrypt login with utf8 parameter', t => { - return lesspass.encryptLogin('test@example.org', '♥ LessPass ♥').then(encryptedLogin => { - t.is('063092c809334979f505df88ed37845d298c01f7e8a03cbd661edbc084c650ca', encryptedLogin); - }) -}); - -test('render password', t => { - const site = 'lesspass.com'; - const encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - const passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - t.is('azYS7,olOL2]', lesspass.renderPassword(site, encryptedLogin, passwordOptions)); -}); diff --git a/tests/node.js b/tests/node.js index f1bba6e..263582f 100644 --- a/tests/node.js +++ b/tests/node.js @@ -1,16 +1,19 @@ var lesspass = require('../lib/lesspass'); +var assert = require('assert'); +var site = 'lesspass.com'; var login = 'contact@lesspass.com'; var masterPassword = 'password'; -var site = 'lesspass.com'; var options = { - counter: 1, - password: { + counter: 1, length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } + lowercase: true, + uppercase: true, + numbers: true, + symbols: true }; -lesspass.generatePassword(login, masterPassword, site, options).then(function (generatedPassword) { - console.log(generatedPassword); //azYS7,olOL2] -}); +lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) => { + var generatedPassword = lesspass.deriveEncryptedLogin(encryptedLogin, site, options); + assert(generatedPassword, 'azYS7,olOL2]'); +}); diff --git a/tests/prettyPrint.js b/tests/prettyPrint.js index c4e51fe..94e56cf 100644 --- a/tests/prettyPrint.js +++ b/tests/prettyPrint.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass2'; +import lesspass from '../src/lesspass'; test('should print different password if templates different', t => { const encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; From 60490410fdec0f42e557b409ec5b8ffda495617d Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 30 Sep 2016 18:10:36 +0200 Subject: [PATCH 034/124] update api and documentation --- dist/lesspass.min.js | 2 +- src/lesspass.js | 155 +++++++++++++++++++++++++++------------------------ tests/api.tests.js | 4 +- tests/index.html | 6 +- tests/node.js | 9 +-- 5 files changed, 94 insertions(+), 82 deletions(-) diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js index 4a63eda..9ae4fb3 100644 --- a/dist/lesspass.min.js +++ b/dist/lesspass.min.js @@ -10,4 +10,4 @@ inherits(DecoderBuffer,Reporter);exports.DecoderBuffer=DecoderBuffer;DecoderBuff "./modes":90,dup:10}],87:[function(require,module,exports){arguments[4][11][0].apply(exports,arguments)},{"./aes":84,"./authCipher":85,"./modes":90,"./modes/cbc":91,"./modes/cfb":92,"./modes/cfb1":93,"./modes/cfb8":94,"./modes/ctr":95,"./modes/ecb":96,"./modes/ofb":97,"./streamCipher":100,buffer:2,"cipher-base":99,dup:11,evp_bytestokey:101,inherits:200}],88:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{"./aes":84,"./authCipher":85,"./modes":90,"./modes/cbc":91,"./modes/cfb":92,"./modes/cfb1":93,"./modes/cfb8":94,"./modes/ctr":95,"./modes/ecb":96,"./modes/ofb":97,"./streamCipher":100,buffer:2,"cipher-base":99,dup:12,evp_bytestokey:101,inherits:200}],89:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{buffer:2,dup:13}],90:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],91:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{"buffer-xor":98,dup:15}],92:[function(require,module,exports){arguments[4][16][0].apply(exports,arguments)},{buffer:2,"buffer-xor":98,dup:16}],93:[function(require,module,exports){arguments[4][17][0].apply(exports,arguments)},{buffer:2,dup:17}],94:[function(require,module,exports){arguments[4][18][0].apply(exports,arguments)},{buffer:2,dup:18}],95:[function(require,module,exports){arguments[4][19][0].apply(exports,arguments)},{buffer:2,"buffer-xor":98,dup:19}],96:[function(require,module,exports){arguments[4][20][0].apply(exports,arguments)},{dup:20}],97:[function(require,module,exports){arguments[4][21][0].apply(exports,arguments)},{buffer:2,"buffer-xor":98,dup:21}],98:[function(require,module,exports){arguments[4][22][0].apply(exports,arguments)},{buffer:2,dup:22}],99:[function(require,module,exports){arguments[4][23][0].apply(exports,arguments)},{buffer:2,dup:23,inherits:200,stream:219,string_decoder:220}],100:[function(require,module,exports){arguments[4][24][0].apply(exports,arguments)},{"./aes":84,buffer:2,"cipher-base":99,dup:24,inherits:200}],101:[function(require,module,exports){arguments[4][35][0].apply(exports,arguments)},{buffer:2,"create-hash/md5":132,dup:35}],102:[function(require,module,exports){(function(Buffer){var createHmac=require("create-hmac");var crt=require("browserify-rsa");var curves=require("./curves");var elliptic=require("elliptic");var parseKeys=require("parse-asn1");var BN=require("bn.js");var EC=elliptic.ec;function sign(hash,key,hashType,signType){var priv=parseKeys(key);if(priv.curve){if(signType!=="ecdsa")throw new Error("wrong private key type");return ecSign(hash,priv)}else if(priv.type==="dsa"){if(signType!=="dsa"){throw new Error("wrong private key type")}return dsaSign(hash,priv,hashType)}else{if(signType!=="rsa")throw new Error("wrong private key type")}var len=priv.modulus.byteLength();var pad=[0,1];while(hash.length+pad.length+10){bits.ishrn(shift)}return bits}function bits2octets(bits,q){bits=bits2int(bits,q);bits=bits.mod(q);var out=new Buffer(bits.toArray());if(out.length=q){throw new Error("invalid sig")}}module.exports=verify}).call(this,require("buffer").Buffer)},{"./curves":38,"bn.js":39,buffer:2,elliptic:41,"parse-asn1":68}],104:[function(require,module,exports){(function(Buffer){var elliptic=require("elliptic");var BN=require("bn.js");module.exports=function createECDH(curve){return new ECDH(curve)};var aliases={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};aliases.p224=aliases.secp224r1;aliases.p256=aliases.secp256r1=aliases.prime256v1;aliases.p192=aliases.secp192r1=aliases.prime192v1;aliases.p384=aliases.secp384r1;aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve];if(!this.curveType){this.curveType={name:curve}}this.curve=new elliptic.ec(this.curveType.name);this.keys=void 0}ECDH.prototype.generateKeys=function(enc,format){this.keys=this.curve.genKeyPair();return this.getPublicKey(enc,format)};ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||"utf8";if(!Buffer.isBuffer(other)){other=new Buffer(other,inenc)}var otherPub=this.curve.keyFromPublic(other).getPublic();var out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)};ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format==="compressed",true);if(format==="hybrid"){if(key[key.length-1]%2){key[0]=7}else{key[0]=6}}return formatReturnValue(key,enc)};ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)};ECDH.prototype.setPublicKey=function(pub,enc){enc=enc||"utf8";if(!Buffer.isBuffer(pub)){pub=new Buffer(pub,enc)}this.keys._importPublic(pub);return this};ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||"utf8";if(!Buffer.isBuffer(priv)){priv=new Buffer(priv,enc)}var _priv=new BN(priv);_priv=_priv.toString(16);this.keys._importPrivate(_priv);return this};function formatReturnValue(bn,enc,len){if(!Array.isArray(bn)){bn=bn.toArray()}var buf=new Buffer(bn);if(len&&buf.length=6.0.0 <7.0.0",_npmVersion:"3.10.3",_nodeVersion:"6.3.0",_npmUser:{name:"indutny",email:"fedor@indutny.com"},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},maintainers:[{name:"indutny",email:"fedor@indutny.com"}],_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},directories:{},_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"}},{}],130:[function(require,module,exports){(function(Buffer){"use strict";var inherits=require("inherits");var md5=require("./md5");var rmd160=require("ripemd160");var sha=require("sha.js");var Base=require("cipher-base");function HashNoConstructor(hash){Base.call(this,"digest");this._hash=hash;this.buffers=[]}inherits(HashNoConstructor,Base);HashNoConstructor.prototype._update=function(data){this.buffers.push(data)};HashNoConstructor.prototype._final=function(){var buf=Buffer.concat(this.buffers);var r=this._hash(buf);this.buffers=null;return r};function Hash(hash){Base.call(this,"digest");this._hash=hash}inherits(Hash,Base);Hash.prototype._update=function(data){this._hash.update(data)};Hash.prototype._final=function(){return this._hash.digest()};module.exports=function createHash(alg){alg=alg.toLowerCase();if("md5"===alg)return new HashNoConstructor(md5);if("rmd160"===alg||"ripemd160"===alg)return new HashNoConstructor(rmd160);return new Hash(sha(alg))}}).call(this,require("buffer").Buffer)},{"./md5":132,buffer:2,"cipher-base":133,inherits:200,ripemd160:134,"sha.js":136}],131:[function(require,module,exports){(function(Buffer){"use strict";var intSize=4;var zeroBuffer=new Buffer(intSize);zeroBuffer.fill(0);var chrsz=8;function toArray(buf,bigEndian){if(buf.length%intSize!==0){var len=buf.length+(intSize-buf.length%intSize);buf=Buffer.concat([buf,zeroBuffer],len)}var arr=[];var fn=bigEndian?buf.readInt32BE:buf.readInt32LE;for(var i=0;i>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":131}],133:[function(require,module,exports){arguments[4][23][0].apply(exports,arguments)},{buffer:2,dup:23,inherits:200,stream:219,string_decoder:220}],134:[function(require,module,exports){(function(Buffer){var zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13];var zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11];var sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6];var sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];var hl=[0,1518500249,1859775393,2400959708,2840853838];var hr=[1352829926,1548603684,1836072691,2053994217,0];function bytesToWords(bytes){var words=[];for(var i=0,b=0;i>>5]|=bytes[i]<<24-b%32}return words}function wordsToBytes(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes}function processBlock(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t}function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message==="string"){message=new Buffer(message,"utf8")}var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}module.exports=ripemd160}).call(this,require("buffer").Buffer)},{buffer:2}],135:[function(require,module,exports){(function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.update=function(data,enc){if(typeof data==="string"){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};module.exports=Hash}).call(this,require("buffer").Buffer)},{buffer:2}],136:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha");exports.sha1=require("./sha1");exports.sha224=require("./sha224");exports.sha256=require("./sha256");exports.sha384=require("./sha384");exports.sha512=require("./sha512")},{"./sha":137,"./sha1":138,"./sha224":139,"./sha256":140,"./sha384":141,"./sha512":142}],137:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha,Hash);Sha.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],138:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha1(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha1.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha1.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha1}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],139:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Sha256=require("./sha256");var Hash=require("./hash");var W=new Array(64);function Sha224(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha224,Sha256);Sha224.prototype.init=function(){this._a=3238371032;this._b=914150663;this._c=812702999;this._d=4144912697;this._e=4290775857;this._f=1750603025;this._g=1694076839;this._h=3204075428;return this};Sha224.prototype._hash=function(){var H=new Buffer(28);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);return H};module.exports=Sha224}).call(this,require("buffer").Buffer)},{"./hash":135,"./sha256":140,buffer:2,inherits:200}],140:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703;this._b=3144134277;this._c=1013904242;this._d=2773480762;this._e=1359893119;this._f=2600822924;this._g=528734635;this._h=1541459225;return this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;var f=this._f|0;var g=this._g|0;var h=this._h|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<64;++i)W[i]=gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W[j]|0;var T2=sigma0(a)+maj(a,b,c)|0;h=g;g=f;f=e;e=d+T1|0;d=c;c=b;b=a;a=T1+T2|0}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};module.exports=Sha256}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],141:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var SHA512=require("./sha512");var Hash=require("./hash");var W=new Array(160);function Sha384(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha384,SHA512);Sha384.prototype.init=function(){this._ah=3418070365;this._bh=1654270250;this._ch=2438529370;this._dh=355462360;this._eh=1731405415;this._fh=2394180231;this._gh=3675008525;this._hh=1203062813;this._al=3238371032;this._bl=914150663;this._cl=812702999;this._dl=4144912697;this._el=4290775857;this._fl=1750603025;this._gl=1694076839;this._hl=3204075428;return this};Sha384.prototype._hash=function(){var H=new Buffer(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);return H};module.exports=Sha384}).call(this,require("buffer").Buffer)},{"./hash":135, "./sha512":142,buffer:2,inherits:200}],142:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._ah=1779033703;this._bh=3144134277;this._ch=1013904242;this._dh=2773480762;this._eh=1359893119;this._fh=2600822924;this._gh=528734635;this._hh=1541459225;this._al=4089235720;this._bl=2227873595;this._cl=4271175723;this._dl=1595750129;this._el=2917565137;this._fl=725511199;this._gl=4215389547;this._hl=327033209;return this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}Sha512.prototype._update=function(M){var W=this._w;var ah=this._ah|0;var bh=this._bh|0;var ch=this._ch|0;var dh=this._dh|0;var eh=this._eh|0;var fh=this._fh|0;var gh=this._gh|0;var hh=this._hh|0;var al=this._al|0;var bl=this._bl|0;var cl=this._cl|0;var dl=this._dl|0;var el=this._el|0;var fl=this._fl|0;var gl=this._gl|0;var hl=this._hl|0;for(var i=0;i<32;i+=2){W[i]=M.readInt32BE(i*4);W[i+1]=M.readInt32BE(i*4+4)}for(;i<160;i+=2){var xh=W[i-15*2];var xl=W[i-15*2+1];var gamma0=Gamma0(xh,xl);var gamma0l=Gamma0l(xl,xh);xh=W[i-2*2];xl=W[i-2*2+1];var gamma1=Gamma1(xh,xl);var gamma1l=Gamma1l(xl,xh);var Wi7h=W[i-7*2];var Wi7l=W[i-7*2+1];var Wi16h=W[i-16*2];var Wi16l=W[i-16*2+1];var Wil=gamma0l+Wi7l|0;var Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0;Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0;Wil=Wil+Wi16l|0;Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0;W[i]=Wih;W[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W[j];Wil=W[j+1];var majh=maj(ah,bh,ch);var majl=maj(al,bl,cl);var sigma0h=sigma0(ah,al);var sigma0l=sigma0(al,ah);var sigma1h=sigma1(eh,el);var sigma1l=sigma1(el,eh);var Kih=K[j];var Kil=K[j+1];var chh=Ch(eh,fh,gh);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l|0;var t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0;t1h=t1h+chh+getCarry(t1l,chl)|0;t1l=t1l+Kil|0;t1h=t1h+Kih+getCarry(t1l,Kil)|0;t1l=t1l+Wil|0;t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0;var t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh;hl=gl;gh=fh;gl=fl;fh=eh;fl=el;el=dl+t1l|0;eh=dh+t1h+getCarry(el,dl)|0;dh=ch;dl=cl;ch=bh;cl=bl;bh=ah;bl=al;al=t1l+t2l|0;ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._ah=this._ah+ah+getCarry(this._al,al)|0;this._bh=this._bh+bh+getCarry(this._bl,bl)|0;this._ch=this._ch+ch+getCarry(this._cl,cl)|0;this._dh=this._dh+dh+getCarry(this._dl,dl)|0;this._eh=this._eh+eh+getCarry(this._el,el)|0;this._fh=this._fh+fh+getCarry(this._fl,fl)|0;this._gh=this._gh+gh+getCarry(this._gl,gl)|0;this._hh=this._hh+hh+getCarry(this._hl,hl)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);writeInt64BE(this._gh,this._gl,48);writeInt64BE(this._hh,this._hl,56);return H};module.exports=Sha512}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],143:[function(require,module,exports){(function(Buffer){"use strict";var createHash=require("create-hash/browser");var inherits=require("inherits");var Transform=require("stream").Transform;var ZEROS=new Buffer(128);ZEROS.fill(0);function Hmac(alg,key){Transform.call(this);alg=alg.toLowerCase();if(typeof key==="string"){key=new Buffer(key)}var blocksize=alg==="sha512"||alg==="sha384"?128:64;this._alg=alg;this._key=key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.lengthbits){num.ishrn(1)}if(num.isEven()){num.iadd(ONE)}if(!num.testn(1)){num.iadd(TWO)}if(!gen.cmp(TWO)){while(num.mod(TWENTYFOUR).cmp(ELEVEN)){num.iadd(FOUR)}}else if(!gen.cmp(FIVE)){while(num.mod(TEN).cmp(THREE)){num.iadd(FOUR)}}n2=num.shrn(1);if(simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num)){return num}}}},{"bn.js":148,"miller-rabin":149,randombytes:198}],147:[function(require,module,exports){module.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],148:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39}],149:[function(require,module,exports){var bn=require("bn.js");var brorand=require("brorand");function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin;MillerRabin.create=function create(rand){return new MillerRabin(rand)};MillerRabin.prototype._rand=function _rand(n){var len=n.bitLength();var buf=this.rand.generate(Math.ceil(len/8));buf[0]|=3;var mask=len&7;if(mask!==0)buf[buf.length-1]>>=7-mask;return new bn(buf)};MillerRabin.prototype.test=function test(n,k,cb){var len=n.bitLength();var red=bn.mont(n);var rone=new bn(1).toRed(red);if(!k)k=Math.max(1,len/48|0);var n1=n.subn(1);var n2=n1.subn(1);for(var s=0;!n1.testn(s);s++){}var d=n.shrn(s);var rn1=n1.toRed(red);var prime=true;for(;k>0;k--){var a=this._rand(n2);if(cb)cb(a);var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i0;k--){var a=this._rand(n2);var g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i=6?"utf-8":"binary"}exports.pbkdf2Sync=function(password,salt,iterations,keylen,digest){if(!Buffer.isBuffer(password))password=new Buffer(password,defaultEncoding);if(!Buffer.isBuffer(salt))salt=new Buffer(salt,defaultEncoding);checkParameters(iterations,keylen);digest=digest||"sha1";var hLen;var l=1;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);var r;var T;for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen}U.copy(T,0,0,hLen);for(var j=1;jMAX_ALLOC||keylen!==keylen){throw new TypeError("Bad key length")}}},{}],153:[function(require,module,exports){exports.publicEncrypt=require("./publicEncrypt");exports.privateDecrypt=require("./privateDecrypt");exports.privateEncrypt=function privateEncrypt(key,buf){return exports.publicEncrypt(key,buf,true)};exports.publicDecrypt=function publicDecrypt(key,buf){return exports.privateDecrypt(key,buf,true)}},{"./privateDecrypt":194,"./publicEncrypt":195}],154:[function(require,module,exports){(function(Buffer){var createHash=require("create-hash");module.exports=function(seed,len){var t=new Buffer("");var i=0,c;while(t.lengthk||new bn(enc).cmp(key.modulus)>=0){throw new Error("decryption error")}var msg;if(reverse){msg=withPublic(new bn(enc),key)}else{msg=crt(enc,key)}var zBuffer=new Buffer(k-msg.length);zBuffer.fill(0);msg=Buffer.concat([zBuffer,msg],k);if(padding===4){return oaep(key,msg)}else if(padding===1){return pkcs1(key,msg,reverse)}else if(padding===3){return msg}else{throw new Error("unknown padding")}};function oaep(key,msg){var n=key.modulus;var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(msg[0]!==0){throw new Error("decryption error")}var maskedSeed=msg.slice(1,hLen+1);var maskedDb=msg.slice(hLen+1);var seed=xor(maskedSeed,mgf(maskedDb,hLen));var db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen))){throw new Error("decryption error")}var i=hLen;while(db[i]===0){i++}if(db[i++]!==1){throw new Error("decryption error")}return db.slice(i)}function pkcs1(key,msg,reverse){var p1=msg.slice(0,2);var i=2;var status=0;while(msg[i++]!==0){if(i>=msg.length){status++;break}}var ps=msg.slice(2,i-1);var p2=msg.slice(i-1,i);if(p1.toString("hex")!=="0002"&&!reverse||p1.toString("hex")!=="0001"&&reverse){status++}if(ps.length<8){status++}if(status){throw new Error("decryption error")}return msg.slice(i)}function compare(a,b){a=new Buffer(a);b=new Buffer(b);var dif=0;var len=a.length;if(a.length!==b.length){dif++;len=Math.min(a.length,b.length)}var i=-1;while(++i=0){throw new Error("data too long for modulus")}}else{throw new Error("unknown padding")}if(reverse){return crt(paddedMsg,key)}else{return withPublic(paddedMsg,key)}};function oaep(key,msg){var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(mLen>k-hLen2-2){throw new Error("message too long")}var ps=new Buffer(k-mLen-hLen2-2);ps.fill(0);var dblen=k-hLen-1;var seed=randomBytes(hLen);var maskedDb=xor(Buffer.concat([iHash,ps,new Buffer([1]),msg],dblen),mgf(seed,dblen));var maskedSeed=xor(seed,mgf(maskedDb,hLen));return new bn(Buffer.concat([new Buffer([0]),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length;var k=key.modulus.byteLength();if(mLen>k-11){throw new Error("message too long")}var ps;if(reverse){ps=new Buffer(k-mLen-3);ps.fill(255)}else{ps=nonZero(k-mLen-3)}return new bn(Buffer.concat([new Buffer([0,reverse?1:2]),ps,new Buffer([0]),msg],k))}function nonZero(len,crypto){var out=new Buffer(len);var i=0;var cache=randomBytes(len*2);var cur=0;var num;while(i65536)throw new Error("requested too many random bytes");var rawBytes=new global.Uint8Array(size);if(size>0){crypto.getRandomValues(rawBytes)}var bytes=new Buffer(rawBytes.buffer);if(typeof cb==="function"){return process.nextTick(function(){cb(null,bytes)})}return bytes}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{_process:202,buffer:2}],199:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],200:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],201:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],202:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var _i=0;_i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}var Duplex;function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode; -if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function writableStateGetBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var Duplex;function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:2,"buffer-shims":210}],210:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:2}],211:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":201}],212:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],213:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:2}],221:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(obj){if(Object.keys)return Object.keys(obj);else{var res=[];for(var key in obj)res.push(key);return res}};var forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);else for(var i=0;i2&&arguments[2]!==undefined?arguments[2]:{};var _ref$password=_ref.password;var password=_ref$password===undefined?{length:12}:_ref$password;var _ref$counter=_ref.counter;var counter=_ref$counter===undefined?1:_ref$counter;var salt=site+counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",hash).update(salt).digest("hex");return derivedHash.substring(0,password.length)}function _getTemplate(){var passwordTypes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:["strong"];var passwordTypesInfo={lowercase:{value:"vc",order:1},uppercase:{value:"VC",order:2},numbers:{value:"n",order:3},symbols:{value:"s",order:4},strong:{value:"Cvcvns",order:5}};return passwordTypes.map(function(passwordType){return passwordTypesInfo[passwordType]}).sort(function(passwordType1,passwordType2){return passwordType1.order>passwordType2.order}).map(function(passwordType){return passwordType.value}).join("")}function _prettyPrint(hash,template){var password="";_string2charCodes(hash).forEach(function(charCode,index){var charType=_getCharType(template,index);password+=_getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:2,"buffer-shims":210}],210:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:2}],211:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":201}],212:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],213:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:2}],221:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(obj){if(Object.keys)return Object.keys(obj);else{var res=[];for(var key in obj)res.push(key);return res}};var forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);else for(var i=0;i2&&arguments[2]!==undefined?arguments[2]:{length:12,counter:1};var salt=site+passwordOptions.counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",encryptedLogin).update(salt).digest("hex");return derivedHash.substring(0,passwordOptions.length)}function _getPasswordTemplate(passwordTypes){var templates={lowercase:"vc",uppercase:"VC",numbers:"n",symbols:"s"};var template="";for(var templateKey in templates){if(passwordTypes.hasOwnProperty(templateKey)&&passwordTypes[templateKey]){template+=templates[templateKey]}}return template}function _prettyPrint(hash,template){var _this=this;var password="";this._string2charCodes(hash).forEach(function(charCode,index){var charType=_this._getCharType(template,index);password+=_this._getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); +module.exports = { + encryptLogin: _encryptLogin, + renderPassword: _renderPassword, + _deriveEncryptedLogin, + _getPasswordTemplate, + _prettyPrint, + _string2charCodes, + _getCharType, + _getPasswordChar, +}; + +function _encryptLogin(login, masterPassword) { + return new Promise((resolve, reject) => { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); } - const iterations = 8192; - const keylen = 32; - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }) - }, + }); + }) +} - deriveEncryptedLogin(encryptedLogin, site, passwordOptions) { - const derivedHash = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); - const template = this._getPasswordTemplate(passwordOptions); - return this._prettyPrint(derivedHash, template); - }, +function _renderPassword(encryptedLogin, site, passwordOptions) { + const derivedEncryptedLogin = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); + const template = this._getPasswordTemplate(passwordOptions); + return this._prettyPrint(derivedEncryptedLogin, template); +} - _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { - const salt = site + passwordOptions.counter.toString(); - const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); - return derivedHash.substring(0, passwordOptions.length); - }, +function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { + const salt = site + passwordOptions.counter.toString(); + const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); + return derivedHash.substring(0, passwordOptions.length); +} - _getPasswordTemplate(passwordTypes) { - const templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - let template = ''; - for (let templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] - } +function _getPasswordTemplate(passwordTypes) { + const templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + let template = ''; + for (let templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] } - return template; - }, + } + return template; +} - _prettyPrint(hash, template) { - let password = ''; +function _prettyPrint(hash, template) { + let password = ''; - this._string2charCodes(hash).forEach((charCode, index) => { - const charType = this._getCharType(template, index); - password += this._getPasswordChar(charType, charCode); - }); - return password; - }, + this._string2charCodes(hash).forEach((charCode, index) => { + const charType = this._getCharType(template, index); + password += this._getPasswordChar(charType, charCode); + }); + return password; +} - _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; - }, +function _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} - _getCharType(template, index) { - return template[index % template.length]; - }, +function _getCharType(template, index) { + return template[index % template.length]; +} - _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; - } +function _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; } diff --git a/tests/api.tests.js b/tests/api.tests.js index e26f7d4..6f28919 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -24,7 +24,7 @@ test('render password', t => { numbers: true, symbols: true }; - t.is('azYS7,olOL2]', lesspass.deriveEncryptedLogin(encryptedLogin, site, passwordOptions)); + t.is('azYS7,olOL2]', lesspass.renderPassword(encryptedLogin, site, passwordOptions)); }); @@ -237,6 +237,6 @@ test('auto generated derive encrypted login tests', t => { numbers: password.numbers, symbols: password.symbols, }; - t.is(password.generatedPassword, lesspass.deriveEncryptedLogin(password.encryptedLogin, password.site, passwordOption)); + t.is(password.generatedPassword, lesspass.renderPassword(password.encryptedLogin, password.site, passwordOption)); } }); diff --git a/tests/index.html b/tests/index.html index 3b8c66f..8ef6471 100644 --- a/tests/index.html +++ b/tests/index.html @@ -18,10 +18,12 @@ symbols: true }; - lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) => { - var generatedPassword = lesspass.deriveEncryptedLogin(encryptedLogin, site, options); + lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { + var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); if (generatedPassword === 'azYS7,olOL2]') { document.body.innerHTML = "generatePassword ok"; + } else { + document.body.innerHTML = "generatePassword not ok " + generatedPassword + ' not equals azYS7,olOL2]'; } }); diff --git a/tests/node.js b/tests/node.js index 263582f..59c0803 100644 --- a/tests/node.js +++ b/tests/node.js @@ -12,8 +12,9 @@ var options = { numbers: true, symbols: true }; - -lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) => { - var generatedPassword = lesspass.deriveEncryptedLogin(encryptedLogin, site, options); - assert(generatedPassword, 'azYS7,olOL2]'); +lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { + var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); + assert.equal(generatedPassword, 'azYS7,olOL2]'); +}).catch(function (err) { + console.log(err); }); From d348db6dbaded6493c44dbad6a18db419e501e07 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 30 Sep 2016 18:10:58 +0200 Subject: [PATCH 035/124] 4.0.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b1646b8..8c5dcb7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "3.2.0", + "version": "4.0.0", "author": "Guillaume Vincent ", "description": "lesspass javascript module to generate idempotent passwords", "main": "lib/lesspass.js", From 976b2f289175f13c093a5fbb2a24a7684e3a5062 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 30 Sep 2016 18:16:25 +0200 Subject: [PATCH 036/124] update documentation --- readme.md | 85 +++++++++++++++++------------------------------------- tests/api.tests.js | 2 +- 2 files changed, 27 insertions(+), 60 deletions(-) diff --git a/readme.md b/readme.md index 41d3e3f..2def304 100644 --- a/readme.md +++ b/readme.md @@ -24,14 +24,16 @@ It works with the browser and NodeJs var masterPassword = 'password'; var site = 'lesspass.com'; var options = { - counter: 1, - password: { + counter: 1, length: 12, - settings: ['lowercase', 'uppercase', 'numbers', 'symbols'] - } + lowercase: true, + uppercase: true, + numbers: true, + symbols: true }; - lesspass.generatePassword(login, masterPassword, site, options).then(function (generatedPassword) { - console.log(generatedPassword); //azYS7,olOL2] + lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { + var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); + console.log(generatedPassword); //azYS7,olOL2] }); @@ -44,63 +46,28 @@ It works with the browser and NodeJs - + -## API - -### `generatePassword(login, masterPassword, site, options)` - -generate unique password based on login, masterPassword, site and options. - -paramaters : - - * `login`: string - * `masterPassword`: string - * `site`: string - * option: dict with lesspass options - * `counter`: integer (default: 1) - * `password.length`: integer between 6 and 64 (default: 12) - * `password.settings`: array of string in `lowercase`, `uppercase`, `numbers` or `symbols` (default: `['lowercase', 'uppercase', 'numbers', 'symbols']`) - -exemple : - - var options = { - counter: 2, - password: { - length: 14, - settings: ['lowercase', 'uppercase', 'numbers'] - } - }; - - -return a promise with generated password : - - - lesspass.generatePassword(login, masterPassword, site, options) - .then(function (generatedPassword) { - console.log(generatedPassword); - }) - .catch(function (error) { - console.log(error); - }); - see [tests/api.tests.js](tests/api.tests.js) for more examples @@ -109,4 +76,4 @@ see [tests/api.tests.js](tests/api.tests.js) for more examples npm test -see [LessPass](https://github.com/lesspass/lesspass) project \ No newline at end of file +see [LessPass](https://github.com/lesspass/lesspass) project diff --git a/tests/api.tests.js b/tests/api.tests.js index 6f28919..9e712ff 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -1,7 +1,7 @@ import test from 'ava'; import lesspass from '../src/lesspass'; -test('encrypt login', t => { +test('encrypt login with pbkdf2 8192 iterations and sha256', t => { return lesspass.encryptLogin('test@example.org', 'password').then(encryptedLogin => { t.is('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); }) From 03421432b5054948130620cf85e571511a49b88e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 6 Oct 2016 00:22:23 +0200 Subject: [PATCH 037/124] add issue template --- ISSUE_TEMPLATE | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 ISSUE_TEMPLATE diff --git a/ISSUE_TEMPLATE b/ISSUE_TEMPLATE new file mode 100644 index 0000000..6b2ed8e --- /dev/null +++ b/ISSUE_TEMPLATE @@ -0,0 +1,9 @@ +**Thank you for taking your time to fill out an issue.** + +To make it easier to manage, can you put this issue in LessPass super project ? + +https://github.com/lesspass/lesspass/issues + +:heart: + +Thanks \ No newline at end of file From 8980726f963c2581ba6d57ed4e74ed40dd216552 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 15:43:09 +0200 Subject: [PATCH 038/124] stop building lesspass/core for browser --- dist/lesspass.min.js | 13 ----- index.js | 95 +++++++++++++++++++++++++++++++++++++ package.json | 52 ++++++-------------- readme.md | 59 +++++------------------ src/lesspass.js | 95 ------------------------------------- tests/api.tests.js | 2 +- tests/deriveEncryptedLogin.tests.js | 2 +- tests/getPasswordTemplate.tests.js | 2 +- tests/index.html | 31 ------------ tests/node.js | 27 ++++++----- tests/prettyPrint.js | 2 +- 11 files changed, 141 insertions(+), 239 deletions(-) delete mode 100644 dist/lesspass.min.js create mode 100644 index.js delete mode 100644 src/lesspass.js delete mode 100644 tests/index.html diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js deleted file mode 100644 index 9ae4fb3..0000000 --- a/dist/lesspass.min.js +++ /dev/null @@ -1,13 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.lesspass=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint); -}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:4,isarray:5}],3:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],4:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],6:[function(require,module,exports){"use strict";exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=require("randombytes");exports.createHash=exports.Hash=require("create-hash");exports.createHmac=exports.Hmac=require("create-hmac");var hashes=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(Object.keys(require("browserify-sign/algos")));exports.getHashes=function(){return hashes};var p=require("pbkdf2");exports.pbkdf2=p.pbkdf2;exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require("browserify-cipher");["Cipher","createCipher","Cipheriv","createCipheriv","Decipher","createDecipher","Decipheriv","createDecipheriv","getCiphers","listCiphers"].forEach(function(key){exports[key]=aes[key]});var dh=require("diffie-hellman");["DiffieHellmanGroup","createDiffieHellmanGroup","getDiffieHellman","createDiffieHellman","DiffieHellman"].forEach(function(key){exports[key]=dh[key]});var sign=require("browserify-sign");["createSign","Sign","createVerify","Verify"].forEach(function(key){exports[key]=sign[key]});exports.createECDH=require("create-ecdh");var publicEncrypt=require("public-encrypt");["publicEncrypt","privateEncrypt","publicDecrypt","privateDecrypt"].forEach(function(key){exports[key]=publicEncrypt[key]});["createCredentials"].forEach(function(name){exports[name]=function(){throw new Error(["sorry, "+name+" is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))}})},{"browserify-cipher":7,"browserify-sign":37,"browserify-sign/algos":36,"create-ecdh":104,"create-hash":130,"create-hmac":143,"diffie-hellman":144,pbkdf2:151,"public-encrypt":153,randombytes:198}],7:[function(require,module,exports){var ebtk=require("evp_bytestokey");var aes=require("browserify-aes/browser");var DES=require("browserify-des");var desModes=require("browserify-des/modes");var aesModes=require("browserify-aes/modes");function createCipher(suite,password){var keyLen,ivLen;suite=suite.toLowerCase();if(aesModes[suite]){keyLen=aesModes[suite].key;ivLen=aesModes[suite].iv}else if(desModes[suite]){keyLen=desModes[suite].key*8;ivLen=desModes[suite].iv}else{throw new TypeError("invalid suite type")}var keys=ebtk(password,false,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){var keyLen,ivLen;suite=suite.toLowerCase();if(aesModes[suite]){keyLen=aesModes[suite].key;ivLen=aesModes[suite].iv}else if(desModes[suite]){keyLen=desModes[suite].key*8;ivLen=desModes[suite].iv}else{throw new TypeError("invalid suite type")}var keys=ebtk(password,false,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){suite=suite.toLowerCase();if(aesModes[suite]){return aes.createCipheriv(suite,key,iv)}else if(desModes[suite]){return new DES({key:key,iv:iv,mode:suite})}else{throw new TypeError("invalid suite type")}}function createDecipheriv(suite,key,iv){suite=suite.toLowerCase();if(aesModes[suite]){return aes.createDecipheriv(suite,key,iv)}else if(desModes[suite]){return new DES({key:key,iv:iv,mode:suite,decrypt:true})}else{throw new TypeError("invalid suite type")}}exports.createCipher=exports.Cipher=createCipher;exports.createCipheriv=exports.Cipheriv=createCipheriv;exports.createDecipher=exports.Decipher=createDecipher;exports.createDecipheriv=exports.Decipheriv=createDecipheriv;function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":10,"browserify-aes/modes":14,"browserify-des":25,"browserify-des/modes":26,evp_bytestokey:35}],8:[function(require,module,exports){(function(Buffer){var uint_max=Math.pow(2,32);function fixup_uint32(x){var ret,x_pos;ret=x>uint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x;return ret}function scrub_vec(v){for(var i=0;i>>8^sx&255^99;this.SBOX[x]=sx;this.INV_SBOX[sx]=x;x2=d[x];x4=d[x2];x8=d[x4];t=d[sx]*257^sx*16843008;this.SUB_MIX[0][x]=t<<24|t>>>8;this.SUB_MIX[1][x]=t<<16|t>>>16;this.SUB_MIX[2][x]=t<<8|t>>>24;this.SUB_MIX[3][x]=t;t=x8*16843009^x4*65537^x2*257^x*16843008;this.INV_SUB_MIX[0][sx]=t<<24|t>>>8;this.INV_SUB_MIX[1][sx]=t<<16|t>>>16;this.INV_SUB_MIX[2][sx]=t<<8|t>>>24;this.INV_SUB_MIX[3][sx]=t;if(x===0){x=xi=1}else{x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]]}}return true};var G=new Global;AES.blockSize=4*4;AES.prototype.blockSize=AES.blockSize;AES.keySize=256/8;AES.prototype.keySize=AES.keySize;function bufferToArray(buf){var len=buf.length/4;var out=new Array(len);var i=-1;while(++i>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255],t^=G.RCON[ksRow/keySize|0]<<24):keySize>6&&ksRow%keySize===4?t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255]:void 0,this._keySchedule[ksRow-keySize]^t)}this._invKeySchedule=[];for(invKsRow=0;invKsRow>>24]]^G.INV_SUB_MIX[1][G.SBOX[t>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[t>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[t&255]]}return true};AES.prototype.encryptBlock=function(M){M=bufferToArray(new Buffer(M));var out=this._doCryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[1],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[3],12);return buf};AES.prototype.decryptBlock=function(M){M=bufferToArray(new Buffer(M));var temp=[M[3],M[1]];M[1]=temp[0];M[3]=temp[1];var out=this._doCryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[3],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[1],12);return buf};AES.prototype.scrub=function(){scrub_vec(this._keySchedule);scrub_vec(this._invKeySchedule);scrub_vec(this._key)};AES.prototype._doCryptBlock=function(M,keySchedule,SUB_MIX,SBOX){var ksRow,s0,s1,s2,s3,t0,t1,t2,t3;s0=M[0]^keySchedule[0];s1=M[1]^keySchedule[1];s2=M[2]^keySchedule[2];s3=M[3]^keySchedule[3];ksRow=4;for(var round=1;round>>24]^SUB_MIX[1][s1>>>16&255]^SUB_MIX[2][s2>>>8&255]^SUB_MIX[3][s3&255]^keySchedule[ksRow++];t1=SUB_MIX[0][s1>>>24]^SUB_MIX[1][s2>>>16&255]^SUB_MIX[2][s3>>>8&255]^SUB_MIX[3][s0&255]^keySchedule[ksRow++];t2=SUB_MIX[0][s2>>>24]^SUB_MIX[1][s3>>>16&255]^SUB_MIX[2][s0>>>8&255]^SUB_MIX[3][s1&255]^keySchedule[ksRow++];t3=SUB_MIX[0][s3>>>24]^SUB_MIX[1][s0>>>16&255]^SUB_MIX[2][s1>>>8&255]^SUB_MIX[3][s2&255]^keySchedule[ksRow++];s0=t0;s1=t1;s2=t2;s3=t3}t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++];t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++];t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++];t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++];return[fixup_uint32(t0),fixup_uint32(t1),fixup_uint32(t2),fixup_uint32(t3)]};exports.AES=AES}).call(this,require("buffer").Buffer)},{buffer:2}],9:[function(require,module,exports){(function(Buffer){var aes=require("./aes");var Transform=require("cipher-base");var inherits=require("inherits");var GHASH=require("./ghash");var xor=require("buffer-xor");inherits(StreamCipher,Transform);module.exports=StreamCipher;function StreamCipher(mode,key,iv,decrypt){if(!(this instanceof StreamCipher)){return new StreamCipher(mode,key,iv)}Transform.call(this);this._finID=Buffer.concat([iv,new Buffer([0,0,0,1])]);iv=Buffer.concat([iv,new Buffer([0,0,0,2])]);this._cipher=new aes.AES(key);this._prev=new Buffer(iv.length);this._cache=new Buffer("");this._secCache=new Buffer("");this._decrypt=decrypt;this._alen=0;this._len=0;iv.copy(this._prev);this._mode=mode;var h=new Buffer(4);h.fill(0);this._ghash=new GHASH(this._cipher.encryptBlock(h));this._authTag=null;this._called=false}StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;if(rump<16){rump=new Buffer(rump);rump.fill(0);this._ghash.update(rump)}}this._called=true;var out=this._mode.encrypt(this,chunk);if(this._decrypt){this._ghash.update(chunk)}else{this._ghash.update(out)}this._len+=chunk.length;return out};StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag){throw new Error("Unsupported state or unable to authenticate data")}var tag=xor(this._ghash.final(this._alen*8,this._len*8),this._cipher.encryptBlock(this._finID));if(this._decrypt){if(xorTest(tag,this._authTag)){throw new Error("Unsupported state or unable to authenticate data")}}else{this._authTag=tag}this._cipher.scrub()};StreamCipher.prototype.getAuthTag=function getAuthTag(){if(!this._decrypt&&Buffer.isBuffer(this._authTag)){return this._authTag}else{throw new Error("Attempting to get auth tag in unsupported state")}};StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(this._decrypt){this._authTag=tag}else{throw new Error("Attempting to set auth tag in unsupported state")}};StreamCipher.prototype.setAAD=function setAAD(buf){if(!this._called){this._ghash.update(buf);this._alen+=buf.length}else{throw new Error("Attempting to set AAD in unsupported state")}};function xorTest(a,b){var out=0;if(a.length!==b.length){out++}var len=Math.min(a.length,b.length);var i=-1;while(++i16){out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}}else{if(this.cache.length>=16){out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}}return null};Splitter.prototype.flush=function(){if(this.cache.length){return this.cache}};function unpad(last){var padded=last[15];var i=-1;while(++i15){var out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}return null};Splitter.prototype.flush=function(){var len=16-this.cache.length;var padBuff=new Buffer(len);var i=-1;while(++i0;j--){Vi[j]=Vi[j]>>>1|(Vi[j-1]&1)<<31}Vi[0]=Vi[0]>>>1;if(lsb_Vi){Vi[0]=Vi[0]^225<<24}}this.state=fromArray(Zi)};GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);var chunk;while(this.cache.length>=16){chunk=this.cache.slice(0,16);this.cache=this.cache.slice(16);this.ghash(chunk)}};GHASH.prototype.final=function(abl,bl){if(this.cache.length){this.ghash(Buffer.concat([this.cache,zeros],16))}this.ghash(fromArray([0,abl,0,bl]));return this.state};function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){out=out.map(fixup_uint32);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[1],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[3],12);return buf}var uint_max=Math.pow(2,32);function fixup_uint32(x){var ret,x_pos;ret=x>uint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x;return ret}function xor(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}}).call(this,require("buffer").Buffer)},{buffer:2}],14:[function(require,module,exports){exports["aes-128-ecb"]={cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"};exports["aes-192-ecb"]={cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"};exports["aes-256-ecb"]={cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"};exports["aes-128-cbc"]={cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"};exports["aes-192-cbc"]={cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"};exports["aes-256-cbc"]={cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"};exports["aes128"]=exports["aes-128-cbc"];exports["aes192"]=exports["aes-192-cbc"];exports["aes256"]=exports["aes-256-cbc"];exports["aes-128-cfb"]={cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"};exports["aes-192-cfb"]={cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"};exports["aes-256-cfb"]={cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"};exports["aes-128-cfb8"]={cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"};exports["aes-192-cfb8"]={cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"};exports["aes-256-cfb8"]={cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"};exports["aes-128-cfb1"]={cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"};exports["aes-192-cfb1"]={cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"};exports["aes-256-cfb1"]={cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"};exports["aes-128-ofb"]={cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"};exports["aes-192-ofb"]={cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"};exports["aes-256-ofb"]={cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"};exports["aes-128-ctr"]={cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"};exports["aes-192-ctr"]={cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"};exports["aes-256-ctr"]={cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"};exports["aes-128-gcm"]={cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"};exports["aes-192-gcm"]={cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"};exports["aes-256-gcm"]={cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}},{}],15:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);self._prev=self._cipher.encryptBlock(data);return self._prev};exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":22}],16:[function(require,module,exports){(function(Buffer){var xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){var out=new Buffer("");var len;while(data.length){if(self._cache.length===0){self._cache=self._cipher.encryptBlock(self._prev);self._prev=new Buffer("")}if(self._cache.length<=data.length){len=self._cache.length;out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]);data=data.slice(len)}else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}}return out};function encryptStart(self,data,decrypt){var len=data.length;var out=xor(data,self._cache);self._cache=self._cache.slice(len);self._prev=Buffer.concat([self._prev,decrypt?data:out]);return out}}).call(this,require("buffer").Buffer)},{buffer:2,"buffer-xor":22}],17:[function(require,module,exports){(function(Buffer){function encryptByte(self,byteParam,decrypt){var pad;var i=-1;var len=8;var out=0;var bit,value;while(++i>i%8;self._prev=shiftIn(self._prev,decrypt?bit:value)}return out}exports.encrypt=function(self,chunk,decrypt){var len=chunk.length;var out=new Buffer(len);var i=-1;while(++i>7}return out}}).call(this,require("buffer").Buffer)},{buffer:2}],18:[function(require,module,exports){(function(Buffer){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev);var out=pad[0]^byteParam;self._prev=Buffer.concat([self._prev.slice(1),new Buffer([decrypt?byteParam:out])]);return out}exports.encrypt=function(self,chunk,decrypt){var len=chunk.length;var out=new Buffer(len);var i=-1;while(++i0;count--){inputOff+=this._buffer(data,inputOff);outputOff+=this._flushBuffer(out,outputOff)}inputOff+=this._buffer(data,inputOff);return out};Cipher.prototype.final=function final(buffer){var first;if(buffer)first=this.update(buffer);var last;if(this.type==="encrypt")last=this._finalEncrypt();else last=this._finalDecrypt();if(first)return first.concat(last);else return last};Cipher.prototype._pad=function _pad(buffer,off){if(off===0)return false;while(off>>1];kL=utils.r28shl(kL,shift);kR=utils.r28shl(kR,shift);utils.pc2(kL,kR,state.keys,i)}};DES.prototype._update=function _update(inp,inOff,out,outOff){var state=this._desState;var l=utils.readUInt32BE(inp,inOff);var r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0);l=state.tmp[0];r=state.tmp[1];if(this.type==="encrypt")this._encrypt(state,l,r,state.tmp,0);else this._decrypt(state,l,r,state.tmp,0);l=state.tmp[0];r=state.tmp[1];utils.writeUInt32BE(out,l,outOff);utils.writeUInt32BE(out,r,outOff+4)};DES.prototype._pad=function _pad(buffer,off){var value=buffer.length-off;for(var i=off;i>>0;l=t}utils.rip(r,l,out,off)};DES.prototype._decrypt=function _decrypt(state,lStart,rStart,out,off){var l=rStart;var r=lStart;for(var i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i];var keyR=state.keys[i+1];utils.expand(l,state.tmp,0);keyL^=state.tmp[0];keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR);var f=utils.permute(s);var t=l;l=(r^f)>>>0;r=t}utils.rip(l,r,out,off)}},{"../des":28,inherits:200,"minimalistic-assert":34}],32:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");var des=require("../des");var Cipher=des.Cipher;var DES=des.DES;function EDEState(type,key){assert.equal(key.length,24,"Invalid key length");var k1=key.slice(0,8);var k2=key.slice(8,16);var k3=key.slice(16,24);if(type==="encrypt"){this.ciphers=[DES.create({type:"encrypt",key:k1}),DES.create({type:"decrypt",key:k2}),DES.create({type:"encrypt",key:k3})]}else{this.ciphers=[DES.create({type:"decrypt",key:k3}),DES.create({type:"encrypt",key:k2}),DES.create({type:"decrypt",key:k1})]}}function EDE(options){Cipher.call(this,options);var state=new EDEState(this.type,this.options.key);this._edeState=state}inherits(EDE,Cipher);module.exports=EDE;EDE.create=function create(options){return new EDE(options)};EDE.prototype._update=function _update(inp,inOff,out,outOff){var state=this._edeState;state.ciphers[0]._update(inp,inOff,out,outOff);state.ciphers[1]._update(out,outOff,out,outOff);state.ciphers[2]._update(out,outOff,out,outOff)};EDE.prototype._pad=DES.prototype._pad;EDE.prototype._unpad=DES.prototype._unpad},{"../des":28,inherits:200,"minimalistic-assert":34}],33:[function(require,module,exports){"use strict";exports.readUInt32BE=function readUInt32BE(bytes,off){var res=bytes[0+off]<<24|bytes[1+off]<<16|bytes[2+off]<<8|bytes[3+off];return res>>>0};exports.writeUInt32BE=function writeUInt32BE(bytes,value,off){bytes[0+off]=value>>>24;bytes[1+off]=value>>>16&255;bytes[2+off]=value>>>8&255;bytes[3+off]=value&255};exports.ip=function ip(inL,inR,out,off){var outL=0;var outR=0;for(var i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>>j+i&1}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inL>>>j+i&1}}for(var i=6;i>=0;i-=2){for(var j=1;j<=25;j+=8){outR<<=1;outR|=inR>>>j+i&1}for(var j=1;j<=25;j+=8){outR<<=1;outR|=inL>>>j+i&1}}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.rip=function rip(inL,inR,out,off){var outL=0;var outR=0;for(var i=0;i<4;i++){for(var j=24;j>=0;j-=8){outL<<=1;outL|=inR>>>j+i&1;outL<<=1;outL|=inL>>>j+i&1}}for(var i=4;i<8;i++){for(var j=24;j>=0;j-=8){outR<<=1;outR|=inR>>>j+i&1;outR<<=1;outR|=inL>>>j+i&1}}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.pc1=function pc1(inL,inR,out,off){var outL=0;var outR=0;for(var i=7;i>=5;i--){for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>j+i&1}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inL>>j+i&1}}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>j+i&1}for(var i=1;i<=3;i++){for(var j=0;j<=24;j+=8){outR<<=1;outR|=inR>>j+i&1}for(var j=0;j<=24;j+=8){outR<<=1;outR|=inL>>j+i&1}}for(var j=0;j<=24;j+=8){outR<<=1;outR|=inL>>j+i&1}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.r28shl=function r28shl(num,shift){return num<>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function pc2(inL,inR,out,off){var outL=0;var outR=0;var len=pc2table.length>>>1;for(var i=0;i>>pc2table[i]&1}for(var i=len;i>>pc2table[i]&1}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.expand=function expand(r,out,off){var outL=0;var outR=0;outL=(r&1)<<5|r>>>27;for(var i=23;i>=15;i-=4){outL<<=6;outL|=r>>>i&63}for(var i=11;i>=3;i-=4){outR|=r>>>i&63;outR<<=6}outR|=(r&31)<<1|r>>>31;out[off+0]=outL>>>0;out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function substitute(inL,inR){var out=0;for(var i=0;i<4;i++){var b=inL>>>18-i*6&63;var sb=sTable[i*64+b];out<<=4;out|=sb}for(var i=0;i<4;i++){var b=inR>>>18-i*6&63;var sb=sTable[4*64+i*64+b];out<<=4;out|=sb}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function permute(num){var out=0;for(var i=0;i>>permuteTable[i]&1}return out>>>0};exports.padSplit=function padSplit(num,size,group){var str=num.toString(2);while(str.length0){bufs.push(md_buf)}bufs.push(password);if(salt){bufs.push(salt)}md_buf=md5(Buffer.concat(bufs));bufs=[];i=0;if(keyLen>0){while(true){if(keyLen===0){break}if(i===md_buf.length){break}key[ki++]=md_buf[i];keyLen--;i++}}if(ivLen>0&&i!==md_buf.length){while(true){if(ivLen===0){break}if(i===md_buf.length){break}iv[ii++]=md_buf[i];ivLen--;i++}}if(keyLen===0&&ivLen===0){break}}for(i=0;i0)return left;return right};BN.min=function min(left,right){if(left.cmp(right)<0)return left;return right};BN.prototype._init=function init(number,base,endian){if(typeof number==="number"){return this._initNumber(number,base,endian)}if(typeof number==="object"){return this._initArray(number,base,endian)}if(base==="hex"){base=16}assert(base===(base|0)&&base>=2&&base<=36);number=number.toString().replace(/\s+/g,"");var start=0;if(number[0]==="-"){start++}if(base===16){this._parseHex(number,start)}else{this._parseBase(number,base,start)}if(number[0]==="-"){this.negative=1}this.strip();if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initNumber=function _initNumber(number,base,endian){if(number<0){this.negative=1;number=-number}if(number<67108864){this.words=[number&67108863];this.length=1}else if(number<4503599627370496){this.words=[number&67108863,number/67108864&67108863];this.length=2}else{assert(number<9007199254740992);this.words=[number&67108863,number/67108864&67108863,1];this.length=3}if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initArray=function _initArray(number,base,endian){assert(typeof number.length==="number");if(number.length<=0){this.words=[0];this.length=1;return this}this.length=Math.ceil(number.length/3);this.words=new Array(this.length);for(var i=0;i=0;i-=3){w=number[i]|number[i-1]<<8|number[i-2]<<16;this.words[j]|=w<>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}else if(endian==="le"){for(i=0,j=0;i>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}return this.strip()};function parseHex(str,start,end){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49&&c<=54){r|=c-49+10}else if(c>=17&&c<=22){r|=c-17+10}else{r|=c&15}}return r}BN.prototype._parseHex=function _parseHex(number,start){this.length=Math.ceil((number.length-start)/6);this.words=new Array(this.length);for(var i=0;i=start;i-=6){w=parseHex(number,i,i+6);this.words[j]|=w<>>26-off&4194303;off+=24;if(off>=26){off-=26;j++}}if(i+6!==start){w=parseHex(number,start,i+6);this.words[j]|=w<>>26-off&4194303}this.strip()};function parseBase(str,start,end,mul){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49){r+=c-49+10}else if(c>=17){r+=c-17+10}else{r+=c}}return r}BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0];this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base){limbLen++}limbLen--;limbPow=limbPow/base|0;var total=number.length-start;var mod=total%limbLen;var end=Math.min(total,total-mod)+start;var word=0;for(var i=start;i1&&this.words[this.length-1]===0){this.length--}return this._normSign()};BN.prototype._normSign=function _normSign(){if(this.length===1&&this.words[0]===0){this.negative=0}return this};BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];var groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];var groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10;padding=padding|0||1;var out;if(base===16||base==="hex"){out="";var off=0;var carry=0;for(var i=0;i>>24-off&16777215;if(carry!==0||i!==this.length-1){out=zeros[6-word.length]+word+out}else{out=word+out}off+=2;if(off>=26){off-=26;i--}}if(carry!==0){out=carry.toString(16)+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base];var groupBase=groupBases[base];out="";var c=this.clone();c.negative=0;while(!c.isZero()){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase);if(!c.isZero()){out=zeros[groupSize-r.length]+r+out}else{out=r+out}}if(this.isZero()){out="0"+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}assert(false,"Base should be between 2 and 36")};BN.prototype.toNumber=function toNumber(){var ret=this.words[0];if(this.length===2){ret+=this.words[1]*67108864}else if(this.length===3&&this.words[2]===1){ret+=4503599627370496+this.words[1]*67108864}else if(this.length>2){assert(false,"Number can only safely store up to 53 bits")}return this.negative!==0?-ret:ret};BN.prototype.toJSON=function toJSON(){return this.toString(16)};BN.prototype.toBuffer=function toBuffer(endian,length){assert(typeof Buffer!=="undefined");return this.toArrayLike(Buffer,endian,length)};BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength();var reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length");assert(reqLength>0,"Requested array length <= 0");this.strip();var littleEndian=endian==="le";var res=new ArrayType(reqLength);var b,i;var q=this.clone();if(!littleEndian){for(i=0;i=4096){r+=13;t>>>=13}if(t>=64){r+=7;t>>>=7}if(t>=8){r+=4;t>>>=4}if(t>=2){r+=2;t>>>=2}return r+t}}BN.prototype._zeroBits=function _zeroBits(w){if(w===0)return 26;var t=w;var r=0;if((t&8191)===0){r+=13;t>>>=13}if((t&127)===0){r+=7;t>>>=7}if((t&15)===0){r+=4;t>>>=4}if((t&3)===0){r+=2;t>>>=2}if((t&1)===0){r++}return r};BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1];var hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){var w=new Array(num.bitLength());for(var bit=0;bit>>wbit}return w}BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;var r=0;for(var i=0;inum.length)return this.clone().ior(num);return num.clone().ior(this)};BN.prototype.uor=function uor(num){if(this.length>num.length)return this.clone().iuor(num);return num.clone().iuor(this)};BN.prototype.iuand=function iuand(num){var b;if(this.length>num.length){b=num}else{b=this}for(var i=0;inum.length)return this.clone().iand(num);return num.clone().iand(this)};BN.prototype.uand=function uand(num){if(this.length>num.length)return this.clone().iuand(num);return num.clone().iuand(this)};BN.prototype.iuxor=function iuxor(num){var a;var b;if(this.length>num.length){a=this;b=num}else{a=num;b=this}for(var i=0;inum.length)return this.clone().ixor(num);return num.clone().ixor(this)};BN.prototype.uxor=function uxor(num){if(this.length>num.length)return this.clone().iuxor(num);return num.clone().iuxor(this)};BN.prototype.inotn=function inotn(width){assert(typeof width==="number"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0;var bitsLeft=width%26;this._expand(bytesNeeded);if(bitsLeft>0){bytesNeeded--}for(var i=0;i0){this.words[i]=~this.words[i]&67108863>>26-bitsLeft}return this.strip()};BN.prototype.notn=function notn(width){return this.clone().inotn(width)};BN.prototype.setn=function setn(bit,val){assert(typeof bit==="number"&&bit>=0);var off=bit/26|0;var wbit=bit%26;this._expand(off+1);if(val){this.words[off]=this.words[off]|1<num.length){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>>26}for(;carry!==0&&i>>26}this.length=a.length;if(carry!==0){this.words[this.length]=carry;this.length++; -}else if(a!==this){for(;inum.length)return this.clone().iadd(num);return num.clone().iadd(this)};BN.prototype.isub=function isub(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);num.negative=1;return r._normSign()}else if(this.negative!==0){this.negative=0;this.iadd(num);this.negative=1;return this._normSign()}var cmp=this.cmp(num);if(cmp===0){this.negative=0;this.length=1;this.words[0]=0;return this}var a,b;if(cmp>0){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>26;this.words[i]=r&67108863}for(;carry!==0&&i>26;this.words[i]=r&67108863}if(carry===0&&i>>26;var rword=carry&67108863;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=self.words[i]|0;b=num.words[j]|0;r=a*b+rword;ncarry+=r/67108864|0;rword=r&67108863}out.words[k]=rword|0;carry=ncarry|0}if(carry!==0){out.words[k]=carry|0}else{out.length--}return out.strip()}var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words;var b=num.words;var o=out.words;var c=0;var lo;var mid;var hi;var a0=a[0]|0;var al0=a0&8191;var ah0=a0>>>13;var a1=a[1]|0;var al1=a1&8191;var ah1=a1>>>13;var a2=a[2]|0;var al2=a2&8191;var ah2=a2>>>13;var a3=a[3]|0;var al3=a3&8191;var ah3=a3>>>13;var a4=a[4]|0;var al4=a4&8191;var ah4=a4>>>13;var a5=a[5]|0;var al5=a5&8191;var ah5=a5>>>13;var a6=a[6]|0;var al6=a6&8191;var ah6=a6>>>13;var a7=a[7]|0;var al7=a7&8191;var ah7=a7>>>13;var a8=a[8]|0;var al8=a8&8191;var ah8=a8>>>13;var a9=a[9]|0;var al9=a9&8191;var ah9=a9>>>13;var b0=b[0]|0;var bl0=b0&8191;var bh0=b0>>>13;var b1=b[1]|0;var bl1=b1&8191;var bh1=b1>>>13;var b2=b[2]|0;var bl2=b2&8191;var bh2=b2>>>13;var b3=b[3]|0;var bl3=b3&8191;var bh3=b3>>>13;var b4=b[4]|0;var bl4=b4&8191;var bh4=b4>>>13;var b5=b[5]|0;var bl5=b5&8191;var bh5=b5>>>13;var b6=b[6]|0;var bl6=b6&8191;var bh6=b6>>>13;var b7=b[7]|0;var bl7=b7&8191;var bh7=b7>>>13;var b8=b[8]|0;var bl8=b8&8191;var bh8=b8>>>13;var b9=b[9]|0;var bl9=b9&8191;var bh9=b9>>>13;out.negative=self.negative^num.negative;out.length=19;lo=Math.imul(al0,bl0);mid=Math.imul(al0,bh0);mid=mid+Math.imul(ah0,bl0)|0;hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0;w0&=67108863;lo=Math.imul(al1,bl0);mid=Math.imul(al1,bh0);mid=mid+Math.imul(ah1,bl0)|0;hi=Math.imul(ah1,bh0);lo=lo+Math.imul(al0,bl1)|0;mid=mid+Math.imul(al0,bh1)|0;mid=mid+Math.imul(ah0,bl1)|0;hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0;w1&=67108863;lo=Math.imul(al2,bl0);mid=Math.imul(al2,bh0);mid=mid+Math.imul(ah2,bl0)|0;hi=Math.imul(ah2,bh0);lo=lo+Math.imul(al1,bl1)|0;mid=mid+Math.imul(al1,bh1)|0;mid=mid+Math.imul(ah1,bl1)|0;hi=hi+Math.imul(ah1,bh1)|0;lo=lo+Math.imul(al0,bl2)|0;mid=mid+Math.imul(al0,bh2)|0;mid=mid+Math.imul(ah0,bl2)|0;hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0;w2&=67108863;lo=Math.imul(al3,bl0);mid=Math.imul(al3,bh0);mid=mid+Math.imul(ah3,bl0)|0;hi=Math.imul(ah3,bh0);lo=lo+Math.imul(al2,bl1)|0;mid=mid+Math.imul(al2,bh1)|0;mid=mid+Math.imul(ah2,bl1)|0;hi=hi+Math.imul(ah2,bh1)|0;lo=lo+Math.imul(al1,bl2)|0;mid=mid+Math.imul(al1,bh2)|0;mid=mid+Math.imul(ah1,bl2)|0;hi=hi+Math.imul(ah1,bh2)|0;lo=lo+Math.imul(al0,bl3)|0;mid=mid+Math.imul(al0,bh3)|0;mid=mid+Math.imul(ah0,bl3)|0;hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0;w3&=67108863;lo=Math.imul(al4,bl0);mid=Math.imul(al4,bh0);mid=mid+Math.imul(ah4,bl0)|0;hi=Math.imul(ah4,bh0);lo=lo+Math.imul(al3,bl1)|0;mid=mid+Math.imul(al3,bh1)|0;mid=mid+Math.imul(ah3,bl1)|0;hi=hi+Math.imul(ah3,bh1)|0;lo=lo+Math.imul(al2,bl2)|0;mid=mid+Math.imul(al2,bh2)|0;mid=mid+Math.imul(ah2,bl2)|0;hi=hi+Math.imul(ah2,bh2)|0;lo=lo+Math.imul(al1,bl3)|0;mid=mid+Math.imul(al1,bh3)|0;mid=mid+Math.imul(ah1,bl3)|0;hi=hi+Math.imul(ah1,bh3)|0;lo=lo+Math.imul(al0,bl4)|0;mid=mid+Math.imul(al0,bh4)|0;mid=mid+Math.imul(ah0,bl4)|0;hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0;w4&=67108863;lo=Math.imul(al5,bl0);mid=Math.imul(al5,bh0);mid=mid+Math.imul(ah5,bl0)|0;hi=Math.imul(ah5,bh0);lo=lo+Math.imul(al4,bl1)|0;mid=mid+Math.imul(al4,bh1)|0;mid=mid+Math.imul(ah4,bl1)|0;hi=hi+Math.imul(ah4,bh1)|0;lo=lo+Math.imul(al3,bl2)|0;mid=mid+Math.imul(al3,bh2)|0;mid=mid+Math.imul(ah3,bl2)|0;hi=hi+Math.imul(ah3,bh2)|0;lo=lo+Math.imul(al2,bl3)|0;mid=mid+Math.imul(al2,bh3)|0;mid=mid+Math.imul(ah2,bl3)|0;hi=hi+Math.imul(ah2,bh3)|0;lo=lo+Math.imul(al1,bl4)|0;mid=mid+Math.imul(al1,bh4)|0;mid=mid+Math.imul(ah1,bl4)|0;hi=hi+Math.imul(ah1,bh4)|0;lo=lo+Math.imul(al0,bl5)|0;mid=mid+Math.imul(al0,bh5)|0;mid=mid+Math.imul(ah0,bl5)|0;hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0;w5&=67108863;lo=Math.imul(al6,bl0);mid=Math.imul(al6,bh0);mid=mid+Math.imul(ah6,bl0)|0;hi=Math.imul(ah6,bh0);lo=lo+Math.imul(al5,bl1)|0;mid=mid+Math.imul(al5,bh1)|0;mid=mid+Math.imul(ah5,bl1)|0;hi=hi+Math.imul(ah5,bh1)|0;lo=lo+Math.imul(al4,bl2)|0;mid=mid+Math.imul(al4,bh2)|0;mid=mid+Math.imul(ah4,bl2)|0;hi=hi+Math.imul(ah4,bh2)|0;lo=lo+Math.imul(al3,bl3)|0;mid=mid+Math.imul(al3,bh3)|0;mid=mid+Math.imul(ah3,bl3)|0;hi=hi+Math.imul(ah3,bh3)|0;lo=lo+Math.imul(al2,bl4)|0;mid=mid+Math.imul(al2,bh4)|0;mid=mid+Math.imul(ah2,bl4)|0;hi=hi+Math.imul(ah2,bh4)|0;lo=lo+Math.imul(al1,bl5)|0;mid=mid+Math.imul(al1,bh5)|0;mid=mid+Math.imul(ah1,bl5)|0;hi=hi+Math.imul(ah1,bh5)|0;lo=lo+Math.imul(al0,bl6)|0;mid=mid+Math.imul(al0,bh6)|0;mid=mid+Math.imul(ah0,bl6)|0;hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0;w6&=67108863;lo=Math.imul(al7,bl0);mid=Math.imul(al7,bh0);mid=mid+Math.imul(ah7,bl0)|0;hi=Math.imul(ah7,bh0);lo=lo+Math.imul(al6,bl1)|0;mid=mid+Math.imul(al6,bh1)|0;mid=mid+Math.imul(ah6,bl1)|0;hi=hi+Math.imul(ah6,bh1)|0;lo=lo+Math.imul(al5,bl2)|0;mid=mid+Math.imul(al5,bh2)|0;mid=mid+Math.imul(ah5,bl2)|0;hi=hi+Math.imul(ah5,bh2)|0;lo=lo+Math.imul(al4,bl3)|0;mid=mid+Math.imul(al4,bh3)|0;mid=mid+Math.imul(ah4,bl3)|0;hi=hi+Math.imul(ah4,bh3)|0;lo=lo+Math.imul(al3,bl4)|0;mid=mid+Math.imul(al3,bh4)|0;mid=mid+Math.imul(ah3,bl4)|0;hi=hi+Math.imul(ah3,bh4)|0;lo=lo+Math.imul(al2,bl5)|0;mid=mid+Math.imul(al2,bh5)|0;mid=mid+Math.imul(ah2,bl5)|0;hi=hi+Math.imul(ah2,bh5)|0;lo=lo+Math.imul(al1,bl6)|0;mid=mid+Math.imul(al1,bh6)|0;mid=mid+Math.imul(ah1,bl6)|0;hi=hi+Math.imul(ah1,bh6)|0;lo=lo+Math.imul(al0,bl7)|0;mid=mid+Math.imul(al0,bh7)|0;mid=mid+Math.imul(ah0,bl7)|0;hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0;w7&=67108863;lo=Math.imul(al8,bl0);mid=Math.imul(al8,bh0);mid=mid+Math.imul(ah8,bl0)|0;hi=Math.imul(ah8,bh0);lo=lo+Math.imul(al7,bl1)|0;mid=mid+Math.imul(al7,bh1)|0;mid=mid+Math.imul(ah7,bl1)|0;hi=hi+Math.imul(ah7,bh1)|0;lo=lo+Math.imul(al6,bl2)|0;mid=mid+Math.imul(al6,bh2)|0;mid=mid+Math.imul(ah6,bl2)|0;hi=hi+Math.imul(ah6,bh2)|0;lo=lo+Math.imul(al5,bl3)|0;mid=mid+Math.imul(al5,bh3)|0;mid=mid+Math.imul(ah5,bl3)|0;hi=hi+Math.imul(ah5,bh3)|0;lo=lo+Math.imul(al4,bl4)|0;mid=mid+Math.imul(al4,bh4)|0;mid=mid+Math.imul(ah4,bl4)|0;hi=hi+Math.imul(ah4,bh4)|0;lo=lo+Math.imul(al3,bl5)|0;mid=mid+Math.imul(al3,bh5)|0;mid=mid+Math.imul(ah3,bl5)|0;hi=hi+Math.imul(ah3,bh5)|0;lo=lo+Math.imul(al2,bl6)|0;mid=mid+Math.imul(al2,bh6)|0;mid=mid+Math.imul(ah2,bl6)|0;hi=hi+Math.imul(ah2,bh6)|0;lo=lo+Math.imul(al1,bl7)|0;mid=mid+Math.imul(al1,bh7)|0;mid=mid+Math.imul(ah1,bl7)|0;hi=hi+Math.imul(ah1,bh7)|0;lo=lo+Math.imul(al0,bl8)|0;mid=mid+Math.imul(al0,bh8)|0;mid=mid+Math.imul(ah0,bl8)|0;hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0;w8&=67108863;lo=Math.imul(al9,bl0);mid=Math.imul(al9,bh0);mid=mid+Math.imul(ah9,bl0)|0;hi=Math.imul(ah9,bh0);lo=lo+Math.imul(al8,bl1)|0;mid=mid+Math.imul(al8,bh1)|0;mid=mid+Math.imul(ah8,bl1)|0;hi=hi+Math.imul(ah8,bh1)|0;lo=lo+Math.imul(al7,bl2)|0;mid=mid+Math.imul(al7,bh2)|0;mid=mid+Math.imul(ah7,bl2)|0;hi=hi+Math.imul(ah7,bh2)|0;lo=lo+Math.imul(al6,bl3)|0;mid=mid+Math.imul(al6,bh3)|0;mid=mid+Math.imul(ah6,bl3)|0;hi=hi+Math.imul(ah6,bh3)|0;lo=lo+Math.imul(al5,bl4)|0;mid=mid+Math.imul(al5,bh4)|0;mid=mid+Math.imul(ah5,bl4)|0;hi=hi+Math.imul(ah5,bh4)|0;lo=lo+Math.imul(al4,bl5)|0;mid=mid+Math.imul(al4,bh5)|0;mid=mid+Math.imul(ah4,bl5)|0;hi=hi+Math.imul(ah4,bh5)|0;lo=lo+Math.imul(al3,bl6)|0;mid=mid+Math.imul(al3,bh6)|0;mid=mid+Math.imul(ah3,bl6)|0;hi=hi+Math.imul(ah3,bh6)|0;lo=lo+Math.imul(al2,bl7)|0;mid=mid+Math.imul(al2,bh7)|0;mid=mid+Math.imul(ah2,bl7)|0;hi=hi+Math.imul(ah2,bh7)|0;lo=lo+Math.imul(al1,bl8)|0;mid=mid+Math.imul(al1,bh8)|0;mid=mid+Math.imul(ah1,bl8)|0;hi=hi+Math.imul(ah1,bh8)|0;lo=lo+Math.imul(al0,bl9)|0;mid=mid+Math.imul(al0,bh9)|0;mid=mid+Math.imul(ah0,bl9)|0;hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0;w9&=67108863;lo=Math.imul(al9,bl1);mid=Math.imul(al9,bh1);mid=mid+Math.imul(ah9,bl1)|0;hi=Math.imul(ah9,bh1);lo=lo+Math.imul(al8,bl2)|0;mid=mid+Math.imul(al8,bh2)|0;mid=mid+Math.imul(ah8,bl2)|0;hi=hi+Math.imul(ah8,bh2)|0;lo=lo+Math.imul(al7,bl3)|0;mid=mid+Math.imul(al7,bh3)|0;mid=mid+Math.imul(ah7,bl3)|0;hi=hi+Math.imul(ah7,bh3)|0;lo=lo+Math.imul(al6,bl4)|0;mid=mid+Math.imul(al6,bh4)|0;mid=mid+Math.imul(ah6,bl4)|0;hi=hi+Math.imul(ah6,bh4)|0;lo=lo+Math.imul(al5,bl5)|0;mid=mid+Math.imul(al5,bh5)|0;mid=mid+Math.imul(ah5,bl5)|0;hi=hi+Math.imul(ah5,bh5)|0;lo=lo+Math.imul(al4,bl6)|0;mid=mid+Math.imul(al4,bh6)|0;mid=mid+Math.imul(ah4,bl6)|0;hi=hi+Math.imul(ah4,bh6)|0;lo=lo+Math.imul(al3,bl7)|0;mid=mid+Math.imul(al3,bh7)|0;mid=mid+Math.imul(ah3,bl7)|0;hi=hi+Math.imul(ah3,bh7)|0;lo=lo+Math.imul(al2,bl8)|0;mid=mid+Math.imul(al2,bh8)|0;mid=mid+Math.imul(ah2,bl8)|0;hi=hi+Math.imul(ah2,bh8)|0;lo=lo+Math.imul(al1,bl9)|0;mid=mid+Math.imul(al1,bh9)|0;mid=mid+Math.imul(ah1,bl9)|0;hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0;w10&=67108863;lo=Math.imul(al9,bl2);mid=Math.imul(al9,bh2);mid=mid+Math.imul(ah9,bl2)|0;hi=Math.imul(ah9,bh2);lo=lo+Math.imul(al8,bl3)|0;mid=mid+Math.imul(al8,bh3)|0;mid=mid+Math.imul(ah8,bl3)|0;hi=hi+Math.imul(ah8,bh3)|0;lo=lo+Math.imul(al7,bl4)|0;mid=mid+Math.imul(al7,bh4)|0;mid=mid+Math.imul(ah7,bl4)|0;hi=hi+Math.imul(ah7,bh4)|0;lo=lo+Math.imul(al6,bl5)|0;mid=mid+Math.imul(al6,bh5)|0;mid=mid+Math.imul(ah6,bl5)|0;hi=hi+Math.imul(ah6,bh5)|0;lo=lo+Math.imul(al5,bl6)|0;mid=mid+Math.imul(al5,bh6)|0;mid=mid+Math.imul(ah5,bl6)|0;hi=hi+Math.imul(ah5,bh6)|0;lo=lo+Math.imul(al4,bl7)|0;mid=mid+Math.imul(al4,bh7)|0;mid=mid+Math.imul(ah4,bl7)|0;hi=hi+Math.imul(ah4,bh7)|0;lo=lo+Math.imul(al3,bl8)|0;mid=mid+Math.imul(al3,bh8)|0;mid=mid+Math.imul(ah3,bl8)|0;hi=hi+Math.imul(ah3,bh8)|0;lo=lo+Math.imul(al2,bl9)|0;mid=mid+Math.imul(al2,bh9)|0;mid=mid+Math.imul(ah2,bl9)|0;hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0;w11&=67108863;lo=Math.imul(al9,bl3);mid=Math.imul(al9,bh3);mid=mid+Math.imul(ah9,bl3)|0;hi=Math.imul(ah9,bh3);lo=lo+Math.imul(al8,bl4)|0;mid=mid+Math.imul(al8,bh4)|0;mid=mid+Math.imul(ah8,bl4)|0;hi=hi+Math.imul(ah8,bh4)|0;lo=lo+Math.imul(al7,bl5)|0;mid=mid+Math.imul(al7,bh5)|0;mid=mid+Math.imul(ah7,bl5)|0;hi=hi+Math.imul(ah7,bh5)|0;lo=lo+Math.imul(al6,bl6)|0;mid=mid+Math.imul(al6,bh6)|0;mid=mid+Math.imul(ah6,bl6)|0;hi=hi+Math.imul(ah6,bh6)|0;lo=lo+Math.imul(al5,bl7)|0;mid=mid+Math.imul(al5,bh7)|0;mid=mid+Math.imul(ah5,bl7)|0;hi=hi+Math.imul(ah5,bh7)|0;lo=lo+Math.imul(al4,bl8)|0;mid=mid+Math.imul(al4,bh8)|0;mid=mid+Math.imul(ah4,bl8)|0;hi=hi+Math.imul(ah4,bh8)|0;lo=lo+Math.imul(al3,bl9)|0;mid=mid+Math.imul(al3,bh9)|0;mid=mid+Math.imul(ah3,bl9)|0;hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0;w12&=67108863;lo=Math.imul(al9,bl4);mid=Math.imul(al9,bh4);mid=mid+Math.imul(ah9,bl4)|0;hi=Math.imul(ah9,bh4);lo=lo+Math.imul(al8,bl5)|0;mid=mid+Math.imul(al8,bh5)|0;mid=mid+Math.imul(ah8,bl5)|0;hi=hi+Math.imul(ah8,bh5)|0;lo=lo+Math.imul(al7,bl6)|0;mid=mid+Math.imul(al7,bh6)|0;mid=mid+Math.imul(ah7,bl6)|0;hi=hi+Math.imul(ah7,bh6)|0;lo=lo+Math.imul(al6,bl7)|0;mid=mid+Math.imul(al6,bh7)|0;mid=mid+Math.imul(ah6,bl7)|0;hi=hi+Math.imul(ah6,bh7)|0;lo=lo+Math.imul(al5,bl8)|0;mid=mid+Math.imul(al5,bh8)|0;mid=mid+Math.imul(ah5,bl8)|0;hi=hi+Math.imul(ah5,bh8)|0;lo=lo+Math.imul(al4,bl9)|0;mid=mid+Math.imul(al4,bh9)|0;mid=mid+Math.imul(ah4,bl9)|0;hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0;w13&=67108863;lo=Math.imul(al9,bl5);mid=Math.imul(al9,bh5);mid=mid+Math.imul(ah9,bl5)|0;hi=Math.imul(ah9,bh5);lo=lo+Math.imul(al8,bl6)|0;mid=mid+Math.imul(al8,bh6)|0;mid=mid+Math.imul(ah8,bl6)|0;hi=hi+Math.imul(ah8,bh6)|0;lo=lo+Math.imul(al7,bl7)|0;mid=mid+Math.imul(al7,bh7)|0;mid=mid+Math.imul(ah7,bl7)|0;hi=hi+Math.imul(ah7,bh7)|0;lo=lo+Math.imul(al6,bl8)|0;mid=mid+Math.imul(al6,bh8)|0;mid=mid+Math.imul(ah6,bl8)|0;hi=hi+Math.imul(ah6,bh8)|0;lo=lo+Math.imul(al5,bl9)|0;mid=mid+Math.imul(al5,bh9)|0;mid=mid+Math.imul(ah5,bl9)|0;hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0;w14&=67108863;lo=Math.imul(al9,bl6);mid=Math.imul(al9,bh6);mid=mid+Math.imul(ah9,bl6)|0;hi=Math.imul(ah9,bh6);lo=lo+Math.imul(al8,bl7)|0;mid=mid+Math.imul(al8,bh7)|0;mid=mid+Math.imul(ah8,bl7)|0;hi=hi+Math.imul(ah8,bh7)|0;lo=lo+Math.imul(al7,bl8)|0;mid=mid+Math.imul(al7,bh8)|0;mid=mid+Math.imul(ah7,bl8)|0;hi=hi+Math.imul(ah7,bh8)|0;lo=lo+Math.imul(al6,bl9)|0;mid=mid+Math.imul(al6,bh9)|0;mid=mid+Math.imul(ah6,bl9)|0;hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0;w15&=67108863;lo=Math.imul(al9,bl7);mid=Math.imul(al9,bh7);mid=mid+Math.imul(ah9,bl7)|0;hi=Math.imul(ah9,bh7);lo=lo+Math.imul(al8,bl8)|0;mid=mid+Math.imul(al8,bh8)|0;mid=mid+Math.imul(ah8,bl8)|0;hi=hi+Math.imul(ah8,bh8)|0;lo=lo+Math.imul(al7,bl9)|0;mid=mid+Math.imul(al7,bh9)|0;mid=mid+Math.imul(ah7,bl9)|0;hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0;w16&=67108863;lo=Math.imul(al9,bl8);mid=Math.imul(al9,bh8);mid=mid+Math.imul(ah9,bl8)|0;hi=Math.imul(ah9,bh8);lo=lo+Math.imul(al8,bl9)|0;mid=mid+Math.imul(al8,bh9)|0;mid=mid+Math.imul(ah8,bl9)|0;hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0;w17&=67108863;lo=Math.imul(al9,bl9);mid=Math.imul(al9,bh9);mid=mid+Math.imul(ah9,bl9)|0;hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w18>>>26)|0;w18&=67108863;o[0]=w0;o[1]=w1;o[2]=w2;o[3]=w3;o[4]=w4;o[5]=w5;o[6]=w6;o[7]=w7;o[8]=w8;o[9]=w9;o[10]=w10;o[11]=w11;o[12]=w12;o[13]=w13;o[14]=w14;o[15]=w15;o[16]=w16;o[17]=w17;o[18]=w18;if(c!==0){o[19]=c;out.length++}return out};if(!Math.imul){comb10MulTo=smallMulTo}function bigMulTo(self,num,out){out.negative=num.negative^self.negative;out.length=self.length+num.length;var carry=0;var hncarry=0;for(var k=0;k>>26)|0;hncarry+=ncarry>>>26;ncarry&=67108863}out.words[k]=rword;carry=ncarry;ncarry=hncarry}if(carry!==0){out.words[k]=carry}else{out.length--}return out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}BN.prototype.mulTo=function mulTo(num,out){var res;var len=this.length+num.length;if(this.length===10&&num.length===10){res=comb10MulTo(this,num,out)}else if(len<63){res=smallMulTo(this,num,out)}else if(len<1024){res=bigMulTo(this,num,out)}else{res=jumboMulTo(this,num,out)}return res};function FFTM(x,y){this.x=x;this.y=y}FFTM.prototype.makeRBT=function makeRBT(N){var t=new Array(N);var l=BN.prototype._countBits(N)-1;for(var i=0;i>=1}return rb};FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1){i++}return 1<>>13;rws[2*i+1]=carry&8191;carry=carry>>>13}for(i=2*len;i>=26;carry+=w/67108864|0;carry+=lo>>>26;this.words[i]=lo&67108863}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.muln=function muln(num){return this.clone().imuln(num)};BN.prototype.sqr=function sqr(){return this.mul(this)};BN.prototype.isqr=function isqr(){return this.imul(this.clone())};BN.prototype.pow=function pow(num){var w=toBitArray(num);if(w.length===0)return new BN(1);var res=this;for(var i=0;i=0);var r=bits%26;var s=(bits-r)/26;var carryMask=67108863>>>26-r<<26-r;var i;if(r!==0){var carry=0;for(i=0;i>>26-r}if(carry){this.words[i]=carry;this.length++}}if(s!==0){for(i=this.length-1;i>=0;i--){this.words[i+s]=this.words[i]}for(i=0;i=0);var h;if(hint){h=(hint-hint%26)/26}else{h=0}var r=bits%26;var s=Math.min((bits-r)/26,this.length);var mask=67108863^67108863>>>r<s){this.length-=s;for(i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r;carry=word&mask}if(maskedWords&&carry!==0){maskedWords.words[maskedWords.length++]=carry}if(this.length===0){this.words[0]=0;this.length=1}return this.strip()};BN.prototype.ishrn=function ishrn(bits,hint,extended){assert(this.negative===0);return this.iushrn(bits,hint,extended)};BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)};BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)};BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)};BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)};BN.prototype.testn=function testn(bit){assert(typeof bit==="number"&&bit>=0);var r=bit%26;var s=(bit-r)/26;var q=1<=0);var r=bits%26;var s=(bits-r)/26;assert(this.negative===0,"imaskn works only with positive numbers");if(this.length<=s){return this}if(r!==0){s++}this.length=Math.min(s,this.length);if(r!==0){var mask=67108863^67108863>>>r<=67108864;i++){this.words[i]-=67108864;if(i===this.length-1){this.words[i+1]=1}else{this.words[i+1]++}}this.length=Math.max(this.length,i+1);return this};BN.prototype.isubn=function isubn(num){assert(typeof num==="number");assert(num<67108864);if(num<0)return this.iaddn(-num);if(this.negative!==0){this.negative=0;this.iaddn(num);this.negative=1;return this}this.words[0]-=num;if(this.length===1&&this.words[0]<0){this.words[0]=-this.words[0];this.negative=1}else{for(var i=0;i>26)-(right/67108864|0);this.words[i+shift]=w&67108863}for(;i>26;this.words[i+shift]=w&67108863}if(carry===0)return this.strip();assert(carry===-1);carry=0;for(i=0;i>26;this.words[i]=w&67108863}this.negative=1;return this.strip()};BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length;var a=this.clone();var b=num;var bhi=b.words[b.length-1]|0;var bhiBits=this._countBits(bhi);shift=26-bhiBits;if(shift!==0){b=b.ushln(shift);a.iushln(shift);bhi=b.words[b.length-1]|0}var m=a.length-b.length;var q;if(mode!=="mod"){q=new BN(null);q.length=m+1;q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);qj=Math.min(qj/bhi|0,67108863);a._ishlnsubmul(b,qj,j);while(a.negative!==0){qj--;a.negative=0;a._ishlnsubmul(b,1,j);if(!a.isZero()){a.negative^=1}}if(q){q.words[j]=qj}}if(q){q.strip()}a.strip();if(mode!=="div"&&shift!==0){a.iushrn(shift)}return{div:q||null,mod:a}};BN.prototype.divmod=function divmod(num,mode,positive){assert(!num.isZero());if(this.isZero()){return{div:new BN(0),mod:new BN(0)}}var div,mod,res;if(this.negative!==0&&num.negative===0){res=this.neg().divmod(num,mode);if(mode!=="mod"){div=res.div.neg()}if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.iadd(num)}}return{div:div,mod:mod}}if(this.negative===0&&num.negative!==0){res=this.divmod(num.neg(),mode);if(mode!=="mod"){div=res.div.neg()}return{div:div,mod:res.mod}}if((this.negative&num.negative)!==0){res=this.neg().divmod(num.neg(),mode);if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.isub(num)}}return{div:res.div,mod:mod}}if(num.length>this.length||this.cmp(num)<0){return{div:new BN(0),mod:this}}if(num.length===1){if(mode==="div"){return{div:this.divn(num.words[0]),mod:null}}if(mode==="mod"){return{div:null,mod:new BN(this.modn(num.words[0]))}}return{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}}return this._wordDiv(num,mode)};BN.prototype.div=function div(num){return this.divmod(num,"div",false).div};BN.prototype.mod=function mod(num){return this.divmod(num,"mod",false).mod};BN.prototype.umod=function umod(num){return this.divmod(num,"mod",true).mod};BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0?dm.mod.isub(num):dm.mod;var half=num.ushrn(1);var r2=num.andln(1);var cmp=mod.cmp(half);if(cmp<0||r2===1&&cmp===0)return dm.div;return dm.div.negative!==0?dm.div.isubn(1):dm.div.iaddn(1)};BN.prototype.modn=function modn(num){assert(num<=67108863);var p=(1<<26)%num;var acc=0;for(var i=this.length-1;i>=0;i--){acc=(p*acc+(this.words[i]|0))%num}return acc};BN.prototype.idivn=function idivn(num){assert(num<=67108863);var carry=0;for(var i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0;carry=w%num}return this.strip()};BN.prototype.divn=function divn(num){return this.clone().idivn(num)};BN.prototype.egcd=function egcd(p){assert(p.negative===0);assert(!p.isZero());var x=this;var y=p.clone();if(x.negative!==0){x=x.umod(p)}else{x=x.clone()}var A=new BN(1);var B=new BN(0);var C=new BN(0);var D=new BN(1);var g=0;while(x.isEven()&&y.isEven()){x.iushrn(1);y.iushrn(1);++g}var yp=y.clone();var xp=x.clone();while(!x.isZero()){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){x.iushrn(i);while(i-- >0){if(A.isOdd()||B.isOdd()){A.iadd(yp);B.isub(xp)}A.iushrn(1);B.iushrn(1)}}for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){y.iushrn(j);while(j-- >0){if(C.isOdd()||D.isOdd()){C.iadd(yp);D.isub(xp)}C.iushrn(1);D.iushrn(1)}}if(x.cmp(y)>=0){x.isub(y);A.isub(C);B.isub(D)}else{y.isub(x);C.isub(A);D.isub(B)}}return{a:C,b:D,gcd:y.iushln(g)}};BN.prototype._invmp=function _invmp(p){assert(p.negative===0);assert(!p.isZero());var a=this;var b=p.clone();if(a.negative!==0){a=a.umod(p)}else{a=a.clone()}var x1=new BN(1);var x2=new BN(0);var delta=b.clone();while(a.cmpn(1)>0&&b.cmpn(1)>0){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){a.iushrn(i);while(i-- >0){if(x1.isOdd()){x1.iadd(delta)}x1.iushrn(1)}}for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){b.iushrn(j);while(j-- >0){if(x2.isOdd()){x2.iadd(delta)}x2.iushrn(1)}}if(a.cmp(b)>=0){a.isub(b);x1.isub(x2)}else{b.isub(a);x2.isub(x1)}}var res;if(a.cmpn(1)===0){res=x1}else{res=x2}if(res.cmpn(0)<0){res.iadd(p)}return res};BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone();var b=num.clone();a.negative=0;b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++){a.iushrn(1);b.iushrn(1)}do{while(a.isEven()){a.iushrn(1)}while(b.isEven()){b.iushrn(1)}var r=a.cmp(b);if(r<0){var t=a;a=b;b=t}else if(r===0||b.cmpn(1)===0){break}a.isub(b)}while(true);return b.iushln(shift)};BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)};BN.prototype.isEven=function isEven(){return(this.words[0]&1)===0};BN.prototype.isOdd=function isOdd(){return(this.words[0]&1)===1};BN.prototype.andln=function andln(num){return this.words[0]&num};BN.prototype.bincn=function bincn(bit){assert(typeof bit==="number");var r=bit%26;var s=(bit-r)/26;var q=1<>>26;w&=67108863;this.words[i]=w}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.isZero=function isZero(){return this.length===1&&this.words[0]===0};BN.prototype.cmpn=function cmpn(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1){res=1}else{if(negative){num=-num}assert(num<=67108863,"Number is too big");var w=this.words[0]|0;res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0;var b=num.words[i]|0;if(a===b)continue;if(ab){res=1}break}return res};BN.prototype.gtn=function gtn(num){return this.cmpn(num)===1};BN.prototype.gt=function gt(num){return this.cmp(num)===1};BN.prototype.gten=function gten(num){return this.cmpn(num)>=0};BN.prototype.gte=function gte(num){return this.cmp(num)>=0};BN.prototype.ltn=function ltn(num){return this.cmpn(num)===-1};BN.prototype.lt=function lt(num){return this.cmp(num)===-1};BN.prototype.lten=function lten(num){return this.cmpn(num)<=0};BN.prototype.lte=function lte(num){return this.cmp(num)<=0};BN.prototype.eqn=function eqn(num){return this.cmpn(num)===0};BN.prototype.eq=function eq(num){return this.cmp(num)===0};BN.red=function red(num){return new Red(num)};BN.prototype.toRed=function toRed(ctx){assert(!this.red,"Already a number in reduction context");assert(this.negative===0,"red works only with positives");return ctx.convertTo(this)._forceRed(ctx)};BN.prototype.fromRed=function fromRed(){assert(this.red,"fromRed works only with numbers in reduction context");return this.red.convertFrom(this)};BN.prototype._forceRed=function _forceRed(ctx){ -this.red=ctx;return this};BN.prototype.forceRed=function forceRed(ctx){assert(!this.red,"Already a number in reduction context");return this._forceRed(ctx)};BN.prototype.redAdd=function redAdd(num){assert(this.red,"redAdd works only with red numbers");return this.red.add(this,num)};BN.prototype.redIAdd=function redIAdd(num){assert(this.red,"redIAdd works only with red numbers");return this.red.iadd(this,num)};BN.prototype.redSub=function redSub(num){assert(this.red,"redSub works only with red numbers");return this.red.sub(this,num)};BN.prototype.redISub=function redISub(num){assert(this.red,"redISub works only with red numbers");return this.red.isub(this,num)};BN.prototype.redShl=function redShl(num){assert(this.red,"redShl works only with red numbers");return this.red.shl(this,num)};BN.prototype.redMul=function redMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.mul(this,num)};BN.prototype.redIMul=function redIMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.imul(this,num)};BN.prototype.redSqr=function redSqr(){assert(this.red,"redSqr works only with red numbers");this.red._verify1(this);return this.red.sqr(this)};BN.prototype.redISqr=function redISqr(){assert(this.red,"redISqr works only with red numbers");this.red._verify1(this);return this.red.isqr(this)};BN.prototype.redSqrt=function redSqrt(){assert(this.red,"redSqrt works only with red numbers");this.red._verify1(this);return this.red.sqrt(this)};BN.prototype.redInvm=function redInvm(){assert(this.red,"redInvm works only with red numbers");this.red._verify1(this);return this.red.invm(this)};BN.prototype.redNeg=function redNeg(){assert(this.red,"redNeg works only with red numbers");this.red._verify1(this);return this.red.neg(this)};BN.prototype.redPow=function redPow(num){assert(this.red&&!num.red,"redPow(normalNum)");this.red._verify1(this);return this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name;this.p=new BN(p,16);this.n=this.p.bitLength();this.k=new BN(1).iushln(this.n).isub(this.p);this.tmp=this._tmp()}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);tmp.words=new Array(Math.ceil(this.n/13));return tmp};MPrime.prototype.ireduce=function ireduce(num){var r=num;var rlen;do{this.split(r,this.tmp);r=this.imulK(r);r=r.iadd(this.tmp);rlen=r.bitLength()}while(rlen>this.n);var cmp=rlen0){r.isub(this.p)}else{r.strip()}return r};MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)};MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)};function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}inherits(K256,MPrime);K256.prototype.split=function split(input,output){var mask=4194303;var outLen=Math.min(input.length,9);for(var i=0;i>>22;prev=next}prev>>>=22;input.words[i-10]=prev;if(prev===0&&input.length>10){input.length-=10}else{input.length-=9}};K256.prototype.imulK=function imulK(num){num.words[num.length]=0;num.words[num.length+1]=0;num.length+=2;var lo=0;for(var i=0;i>>=26;num.words[i]=lo;carry=hi}if(carry!==0){num.words[num.length++]=carry}return num};BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if(name==="k256"){prime=new K256}else if(name==="p224"){prime=new P224}else if(name==="p192"){prime=new P192}else if(name==="p25519"){prime=new P25519}else{throw new Error("Unknown prime "+name)}primes[name]=prime;return prime};function Red(m){if(typeof m==="string"){var prime=BN._prime(m);this.m=prime.p;this.prime=prime}else{assert(m.gtn(1),"modulus must be greater than 1");this.m=m;this.prime=null}}Red.prototype._verify1=function _verify1(a){assert(a.negative===0,"red works only with positives");assert(a.red,"red works only with red numbers")};Red.prototype._verify2=function _verify2(a,b){assert((a.negative|b.negative)===0,"red works only with positives");assert(a.red&&a.red===b.red,"red works only with red numbers")};Red.prototype.imod=function imod(a){if(this.prime)return this.prime.ireduce(a)._forceRed(this);return a.umod(this.m)._forceRed(this)};Red.prototype.neg=function neg(a){if(a.isZero()){return a.clone()}return this.m.sub(a)._forceRed(this)};Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res._forceRed(this)};Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res};Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res._forceRed(this)};Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res};Red.prototype.shl=function shl(a,num){this._verify1(a);return this.imod(a.ushln(num))};Red.prototype.imul=function imul(a,b){this._verify2(a,b);return this.imod(a.imul(b))};Red.prototype.mul=function mul(a,b){this._verify2(a,b);return this.imod(a.mul(b))};Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())};Red.prototype.sqr=function sqr(a){return this.mul(a,a)};Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);assert(mod3%2===1);if(mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}var q=this.m.subn(1);var s=0;while(!q.isZero()&&q.andln(1)===0){s++;q.iushrn(1)}assert(!q.isZero());var one=new BN(1).toRed(this);var nOne=one.redNeg();var lpow=this.m.subn(1).iushrn(1);var z=this.m.bitLength();z=new BN(2*z*z).toRed(this);while(this.pow(z,lpow).cmp(nOne)!==0){z.redIAdd(nOne)}var c=this.pow(z,q);var r=this.pow(a,q.addn(1).iushrn(1));var t=this.pow(a,q);var m=s;while(t.cmp(one)!==0){var tmp=t;for(var i=0;tmp.cmp(one)!==0;i++){tmp=tmp.redSqr()}assert(i=0;i--){var word=num.words[i];for(var j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]){res=this.sqr(res)}if(bit===0&¤t===0){currentLen=0;continue}current<<=1;current|=bit;currentLen++;if(currentLen!==windowSize&&(i!==0||j!==0))continue;res=this.mul(res,wnd[current]);currentLen=0;current=0}start=26}return res};Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r};Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();res.red=null;return res};BN.mont=function mont(num){return new Mont(num)};function Mont(m){Red.call(this,m);this.shift=this.m.bitLength();if(this.shift%26!==0){this.shift+=26-this.shift%26}this.r=new BN(1).iushln(this.shift);this.r2=this.imod(this.r.sqr());this.rinv=this.r._invmp(this.m);this.minv=this.rinv.mul(this.r).isubn(1).div(this.m);this.minv=this.minv.umod(this.r);this.minv=this.r.sub(this.minv)}inherits(Mont,Red);Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))};Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));r.red=null;return r};Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero()){a.words[0]=0;a.length=1;return a}var t=a.imul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module==="undefined"||module,this)},{}],40:[function(require,module,exports){(function(Buffer){var bn=require("bn.js");var randomBytes=require("randombytes");module.exports=crt;function blind(priv){var r=getr(priv);var blinder=r.toRed(bn.mont(priv.modulus)).redPow(new bn(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function crt(msg,priv){var blinds=blind(priv);var len=priv.modulus.byteLength();var mod=bn.mont(priv.modulus);var blinded=new bn(msg).mul(blinds.blinder).umod(priv.modulus);var c1=blinded.toRed(bn.mont(priv.prime1));var c2=blinded.toRed(bn.mont(priv.prime2));var qinv=priv.coefficient;var p=priv.prime1;var q=priv.prime2;var m1=c1.redPow(priv.exponent1);var m2=c2.redPow(priv.exponent2);m1=m1.fromRed();m2=m2.fromRed();var h=m1.isub(m2).imul(qinv).umod(p);h.imul(q);m2.iadd(h);return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false,len))}crt.getr=getr;function getr(priv){var len=priv.modulus.byteLength();var r=new bn(randomBytes(len));while(r.cmp(priv.modulus)>=0||!r.umod(priv.prime1)||!r.umod(priv.prime2)){r=new bn(randomBytes(len))}return r}}).call(this,require("buffer").Buffer)},{"bn.js":39,buffer:2,randombytes:198}],41:[function(require,module,exports){"use strict";var elliptic=exports;elliptic.version=require("../package.json").version;elliptic.utils=require("./elliptic/utils");elliptic.rand=require("brorand");elliptic.hmacDRBG=require("./elliptic/hmac-drbg");elliptic.curve=require("./elliptic/curve");elliptic.curves=require("./elliptic/curves");elliptic.ec=require("./elliptic/ec");elliptic.eddsa=require("./elliptic/eddsa")},{"../package.json":64,"./elliptic/curve":44,"./elliptic/curves":47,"./elliptic/ec":48,"./elliptic/eddsa":51,"./elliptic/hmac-drbg":54,"./elliptic/utils":56,brorand:57}],42:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var getNAF=utils.getNAF;var getJSF=utils.getJSF;var assert=utils.assert;function BaseCurve(type,conf){this.type=type;this.p=new BN(conf.p,16);this.red=conf.prime?BN.red(conf.prime):BN.mont(this.p);this.zero=new BN(0).toRed(this.red);this.one=new BN(1).toRed(this.red);this.two=new BN(2).toRed(this.red);this.n=conf.n&&new BN(conf.n,16);this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed);this._wnafT1=new Array(4);this._wnafT2=new Array(4);this._wnafT3=new Array(4);this._wnafT4=new Array(4);var adjustCount=this.n&&this.p.div(this.n);if(!adjustCount||adjustCount.cmpn(100)>0){this.redN=null}else{this._maxwellTrick=true;this.redN=this.n.toRed(this.red)}}module.exports=BaseCurve;BaseCurve.prototype.point=function point(){throw new Error("Not implemented")};BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")};BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert(p.precomputed);var doubles=p._getDoubles();var naf=getNAF(k,1);var I=(1<=j;k--)nafW=(nafW<<1)+naf[k];repr.push(nafW)}var a=this.jpoint(null,null,null);var b=this.jpoint(null,null,null);for(var i=I;i>0;i--){for(var j=0;j=0;i--){for(var k=0;i>=0&&naf[i]===0;i--)k++;if(i>=0)k++;acc=acc.dblp(k);if(i<0)break;var z=naf[i];assert(z!==0);if(p.type==="affine"){if(z>0)acc=acc.mixedAdd(wnd[z-1>>1]);else acc=acc.mixedAdd(wnd[-z-1>>1].neg())}else{if(z>0)acc=acc.add(wnd[z-1>>1]);else acc=acc.add(wnd[-z-1>>1].neg())}}return p.type==="affine"?acc.toP():acc};BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1;var wnd=this._wnafT2;var naf=this._wnafT3;var max=0;for(var i=0;i=1;i-=2){var a=i-1;var b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a]);naf[b]=getNAF(coeffs[b],wndWidth[b]);max=Math.max(naf[a].length,max);max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];if(points[a].y.cmp(points[b].y)===0){comb[1]=points[a].add(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}else if(points[a].y.cmp(points[b].y.redNeg())===0){comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].add(points[b].neg())}else{comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}var index=[-3,-1,-5,-7,0,7,5,1,3];var jsf=getJSF(coeffs[a],coeffs[b]);max=Math.max(jsf[0].length,max);naf[a]=new Array(max);naf[b]=new Array(max);for(var j=0;j=0;i--){var k=0;while(i>=0){var zero=true;for(var j=0;j=0)k++;acc=acc.dblp(k);if(i<0)break;for(var j=0;j0)p=wnd[j][z-1>>1];else if(z<0)p=wnd[j][-z-1>>1].neg();if(p.type==="affine")acc=acc.mixedAdd(p);else acc=acc.add(p)}}for(var i=0;i=Math.ceil((k.bitLength()+1)/doubles.step)};BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;var doubles=[this];var acc=this;for(var i=0;i";return""};Point.prototype.isInfinity=function isInfinity(){return this.x.cmpn(0)===0&&this.y.cmp(this.z)===0};Point.prototype._extDbl=function _extDbl(){var a=this.x.redSqr();var b=this.y.redSqr();var c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a);var e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);var g=d.redAdd(b);var f=g.redSub(c);var h=d.redSub(b);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projDbl=function _projDbl(){var b=this.x.redAdd(this.y).redSqr();var c=this.x.redSqr();var d=this.y.redSqr();var nx;var ny;var nz;if(this.curve.twisted){var e=this.curve._mulA(c);var f=e.redAdd(d);if(this.zOne){nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));ny=f.redMul(e.redSub(d));nz=f.redSqr().redSub(f).redSub(f)}else{var h=this.z.redSqr();var j=f.redSub(h).redISub(h);nx=b.redSub(c).redISub(d).redMul(j);ny=f.redMul(e.redSub(d));nz=f.redMul(j)}}else{var e=c.redAdd(d);var h=this.curve._mulC(this.c.redMul(this.z)).redSqr();var j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j);ny=this.curve._mulC(e).redMul(c.redISub(d));nz=e.redMul(j)}return this.curve.point(nx,ny,nz)};Point.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.extended)return this._extDbl();else return this._projDbl()};Point.prototype._extAdd=function _extAdd(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x));var b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));var c=this.t.redMul(this.curve.dd).redMul(p.t);var d=this.z.redMul(p.z.redAdd(p.z));var e=b.redSub(a);var f=d.redSub(c);var g=d.redAdd(c);var h=b.redAdd(a);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projAdd=function _projAdd(p){var a=this.z.redMul(p.z);var b=a.redSqr();var c=this.x.redMul(p.x);var d=this.y.redMul(p.y);var e=this.curve.d.redMul(c).redMul(d);var f=b.redSub(e);var g=b.redAdd(e);var tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);var nx=a.redMul(f).redMul(tmp);var ny;var nz;if(this.curve.twisted){ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));nz=f.redMul(g)}else{ny=a.redMul(g).redMul(d.redSub(c));nz=this.curve._mulC(f).redMul(g)}return this.curve.point(nx,ny,nz)};Point.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;if(this.curve.extended)return this._extAdd(p);else return this._projAdd(p)};Point.prototype.mul=function mul(k){if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,false)};Point.prototype.jmulAdd=function jmulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,true)};Point.prototype.normalize=function normalize(){if(this.zOne)return this;var zi=this.z.redInvm();this.x=this.x.redMul(zi);this.y=this.y.redMul(zi);if(this.t)this.t=this.t.redMul(zi);this.z=this.curve.one;this.zOne=true;return this};Point.prototype.neg=function neg(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};Point.prototype.getY=function getY(){this.normalize();return this.y.fromRed()};Point.prototype.eq=function eq(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0};Point.prototype.eqXToP=function eqXToP(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(this.z);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}return false};Point.prototype.toP=Point.prototype.normalize;Point.prototype.mixedAdd=Point.prototype.add},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:200}],44:[function(require,module,exports){"use strict";var curve=exports;curve.base=require("./base");curve.short=require("./short");curve.mont=require("./mont");curve.edwards=require("./edwards")},{"./base":42,"./edwards":43,"./mont":45,"./short":46}],45:[function(require,module,exports){"use strict";var curve=require("../curve");var BN=require("bn.js");var inherits=require("inherits");var Base=curve.base;var elliptic=require("../../elliptic");var utils=elliptic.utils;function MontCurve(conf){Base.call(this,"mont",conf);this.a=new BN(conf.a,16).toRed(this.red);this.b=new BN(conf.b,16).toRed(this.red);this.i4=new BN(4).toRed(this.red).redInvm();this.two=new BN(2).toRed(this.red);this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits(MontCurve,Base);module.exports=MontCurve;MontCurve.prototype.validate=function validate(point){var x=point.normalize().x;var x2=x.redSqr();var rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);var y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point(curve,x,z){Base.BasePoint.call(this,curve,"projective");if(x===null&&z===null){this.x=this.curve.one;this.z=this.curve.zero}else{this.x=new BN(x,16);this.z=new BN(z,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red)}}inherits(Point,Base.BasePoint);MontCurve.prototype.decodePoint=function decodePoint(bytes,enc){return this.point(utils.toArray(bytes,enc),1)};MontCurve.prototype.point=function point(x,z){return new Point(this,x,z)};MontCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)};Point.prototype.precompute=function precompute(){};Point.prototype._encode=function _encode(){return this.getX().toArray("be",this.curve.p.byteLength())};Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"";return""};Point.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};Point.prototype.dbl=function dbl(){var a=this.x.redAdd(this.z);var aa=a.redSqr();var b=this.x.redSub(this.z);var bb=b.redSqr();var c=aa.redSub(bb);var nx=aa.redMul(bb);var nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)};Point.prototype.add=function add(){throw new Error("Not supported on Montgomery curve")};Point.prototype.diffAdd=function diffAdd(p,diff){var a=this.x.redAdd(this.z);var b=this.x.redSub(this.z);var c=p.x.redAdd(p.z);var d=p.x.redSub(p.z);var da=d.redMul(a);var cb=c.redMul(b);var nx=diff.z.redMul(da.redAdd(cb).redSqr());var nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)};Point.prototype.mul=function mul(k){var t=k.clone();var a=this;var b=this.curve.point(null,null);var c=this;for(var bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--){if(bits[i]===0){a=a.diffAdd(b,c);b=b.dbl()}else{b=a.diffAdd(b,c);a=a.dbl()}}return b};Point.prototype.mulAdd=function mulAdd(){throw new Error("Not supported on Montgomery curve")};Point.prototype.jumlAdd=function jumlAdd(){throw new Error("Not supported on Montgomery curve")};Point.prototype.eq=function eq(other){return this.getX().cmp(other.getX())===0};Point.prototype.normalize=function normalize(){this.x=this.x.redMul(this.z.redInvm());this.z=this.curve.one;return this};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()}},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:200}],46:[function(require,module,exports){"use strict";var curve=require("../curve");var elliptic=require("../../elliptic");var BN=require("bn.js");var inherits=require("inherits");var Base=curve.base;var assert=elliptic.utils.assert;function ShortCurve(conf){Base.call(this,"short",conf);this.a=new BN(conf.a,16).toRed(this.red);this.b=new BN(conf.b,16).toRed(this.red);this.tinv=this.two.redInvm();this.zeroA=this.a.fromRed().cmpn(0)===0;this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0;this.endo=this._getEndomorphism(conf);this._endoWnafT1=new Array(4);this._endoWnafT2=new Array(4)}inherits(ShortCurve,Base);module.exports=ShortCurve;ShortCurve.prototype._getEndomorphism=function _getEndomorphism(conf){if(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)return;var beta;var lambda;if(conf.beta){beta=new BN(conf.beta,16).toRed(this.red)}else{var betas=this._getEndoRoots(this.p);beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1];beta=beta.toRed(this.red)}if(conf.lambda){lambda=new BN(conf.lambda,16)}else{var lambdas=this._getEndoRoots(this.n);if(this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))===0){lambda=lambdas[0]}else{lambda=lambdas[1];assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))===0)}}var basis;if(conf.basis){basis=conf.basis.map(function(vec){return{a:new BN(vec.a,16),b:new BN(vec.b,16)}})}else{basis=this._getEndoBasis(lambda)}return{beta:beta,lambda:lambda,basis:basis}};ShortCurve.prototype._getEndoRoots=function _getEndoRoots(num){var red=num===this.p?this.red:BN.mont(num);var tinv=new BN(2).toRed(red).redInvm();var ntinv=tinv.redNeg();var s=new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);var l1=ntinv.redAdd(s).fromRed();var l2=ntinv.redSub(s).fromRed();return[l1,l2]};ShortCurve.prototype._getEndoBasis=function _getEndoBasis(lambda){var aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2));var u=lambda;var v=this.n.clone();var x1=new BN(1);var y1=new BN(0);var x2=new BN(0);var y2=new BN(1);var a0;var b0;var a1;var b1;var a2;var b2;var prevR;var i=0;var r;var x;while(u.cmpn(0)!==0){var q=v.div(u);r=v.sub(q.mul(u));x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0){a0=prevR.neg();b0=x1;a1=r.neg();b1=x}else if(a1&&++i===2){break}prevR=r;v=u;u=r;x2=x1;x1=x;y2=y1;y1=y}a2=r.neg();b2=x;var len1=a1.sqr().add(b1.sqr());var len2=a2.sqr().add(b2.sqr());if(len2.cmp(len1)>=0){a2=a0;b2=b0}if(a1.negative){a1=a1.neg();b1=b1.neg()}if(a2.negative){a2=a2.neg();b2=b2.neg()}return[{a:a1,b:b1},{a:a2,b:b2}]};ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis;var v1=basis[0];var v2=basis[1];var c1=v2.b.mul(k).divRound(this.n);var c2=v1.b.neg().mul(k).divRound(this.n);var p1=c1.mul(v1.a);var p2=c2.mul(v2.a);var q1=c1.mul(v1.b);var q2=c2.mul(v2.b);var k1=k.sub(p1).sub(p2);var k2=q1.add(q2).neg();return{k1:k1,k2:k2}};ShortCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN(x,16);if(!x.red)x=x.toRed(this.red);var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};ShortCurve.prototype.validate=function validate(point){if(point.inf)return true;var x=point.x;var y=point.y;var ax=this.a.redMul(x);var rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0};ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){ -var npoints=this._endoWnafT1;var ncoeffs=this._endoWnafT2;for(var i=0;i";return""};Point.prototype.isInfinity=function isInfinity(){return this.inf};Point.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);if(c.cmpn(0)!==0)c=c.redMul(this.x.redSub(p.x).redInvm());var nx=c.redSqr().redISub(this.x).redISub(p.x);var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a;var x2=this.x.redSqr();var dyinv=ys1.redInvm();var c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);var nx=c.redSqr().redISub(this.x.redAdd(this.x));var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point.prototype.getX=function getX(){return this.x.fromRed()};Point.prototype.getY=function getY(){return this.y.fromRed()};Point.prototype.mul=function mul(k){k=new BN(k,16);if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else if(this.curve.endo)return this.curve._endoWnafMulAdd([this],[k]);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs);else return this.curve._wnafMulAdd(1,points,coeffs,2)};Point.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs,true);else return this.curve._wnafMulAdd(1,points,coeffs,2,true)};Point.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)};Point.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed;var negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res};Point.prototype.toJ=function toJ(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,"jacobian");if(x===null&&y===null&&z===null){this.x=this.curve.one;this.y=this.curve.one;this.z=new BN(0)}else{this.x=new BN(x,16);this.y=new BN(y,16);this.z=new BN(z,16)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);this.zOne=this.z===this.curve.one}inherits(JPoint,Base.BasePoint);ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)};JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm();var zinv2=zinv.redSqr();var ax=this.x.redMul(zinv2);var ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)};JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr();var z2=this.z.redSqr();var u1=this.x.redMul(pz2);var u2=p.x.redMul(z2);var s1=this.y.redMul(pz2.redMul(p.z));var s2=p.y.redMul(z2.redMul(this.z));var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr();var u1=this.x;var u2=p.x.redMul(z2);var s1=this.y;var s2=p.y.redMul(z2).redMul(this.z);var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.dblp=function dblp(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();if(this.curve.zeroA||this.curve.threeA){var r=this;for(var i=0;i=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}return false};JPoint.prototype.inspect=function inspect(){if(this.isInfinity())return"";return""};JPoint.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0}},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:200}],47:[function(require,module,exports){"use strict";var curves=exports;var hash=require("hash.js");var elliptic=require("../elliptic");var assert=elliptic.utils.assert;function PresetCurve(options){if(options.type==="short")this.curve=new elliptic.curve.short(options);else if(options.type==="edwards")this.curve=new elliptic.curve.edwards(options);else this.curve=new elliptic.curve.mont(options);this.g=this.curve.g;this.n=this.curve.n;this.hash=options.hash;assert(this.g.validate(),"Invalid curve");assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}curves.PresetCurve=PresetCurve;function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:true,enumerable:true,get:function(){var curve=new PresetCurve(options);Object.defineProperty(curves,name,{configurable:true,enumerable:true,value:curve});return curve}})}defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:false,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]});defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:false,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]});defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:false,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]});defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f "+"5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 "+"f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:false,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 "+"5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 "+"0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]});defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b "+"99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd "+"3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 "+"f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:false,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 "+"053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 "+"a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 "+"579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 "+"3fad0761 353c7086 a272c240 88be9476 9fd16650"]});defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"0",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["9"]});defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=require("./precomputed/secp256k1")}catch(e){pre=undefined}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:false,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})},{"../elliptic":41,"./precomputed/secp256k1":55,"hash.js":58}],48:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var assert=utils.assert;var KeyPair=require("./key");var Signature=require("./signature");function EC(options){if(!(this instanceof EC))return new EC(options);if(typeof options==="string"){assert(elliptic.curves.hasOwnProperty(options),"Unknown curve "+options);options=elliptic.curves[options]}if(options instanceof elliptic.curves.PresetCurve)options={curve:options};this.curve=options.curve.curve;this.n=this.curve.n;this.nh=this.n.ushrn(1);this.g=this.curve.g;this.g=options.curve.g;this.g.precompute(options.curve.n.bitLength()+1);this.hash=options.hash||options.curve.hash}module.exports=EC;EC.prototype.keyPair=function keyPair(options){return new KeyPair(this,options)};EC.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return KeyPair.fromPrivate(this,priv,enc)};EC.prototype.keyFromPublic=function keyFromPublic(pub,enc){return KeyPair.fromPublic(this,pub,enc)};EC.prototype.genKeyPair=function genKeyPair(options){if(!options)options={};var drbg=new elliptic.hmacDRBG({hash:this.hash,pers:options.pers,entropy:options.entropy||elliptic.rand(this.hash.hmacStrength),nonce:this.n.toArray()});var bytes=this.n.byteLength();var ns2=this.n.sub(new BN(2));do{var priv=new BN(drbg.generate(bytes));if(priv.cmp(ns2)>0)continue;priv.iaddn(1);return this.keyFromPrivate(priv)}while(true)};EC.prototype._truncateToN=function truncateToN(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();if(delta>0)msg=msg.ushrn(delta);if(!truncOnly&&msg.cmp(this.n)>=0)return msg.sub(this.n);else return msg};EC.prototype.sign=function sign(msg,key,enc,options){if(typeof enc==="object"){options=enc;enc=null}if(!options)options={};key=this.keyFromPrivate(key,enc);msg=this._truncateToN(new BN(msg,16));var bytes=this.n.byteLength();var bkey=key.getPrivate().toArray("be",bytes);var nonce=msg.toArray("be",bytes);var drbg=new elliptic.hmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc});var ns1=this.n.sub(new BN(1));for(var iter=0;true;iter++){var k=options.k?options.k(iter):new BN(drbg.generate(this.n.byteLength()));k=this._truncateToN(k,true);if(k.cmpn(1)<=0||k.cmp(ns1)>=0)continue;var kp=this.g.mul(k);if(kp.isInfinity())continue;var kpX=kp.getX();var r=kpX.umod(this.n);if(r.cmpn(0)===0)continue;var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));s=s.umod(this.n);if(s.cmpn(0)===0)continue;var recoveryParam=(kp.getY().isOdd()?1:0)|(kpX.cmp(r)!==0?2:0);if(options.canonical&&s.cmp(this.nh)>0){s=this.n.sub(s);recoveryParam^=1}return new Signature({r:r,s:s,recoveryParam:recoveryParam})}};EC.prototype.verify=function verify(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16));key=this.keyFromPublic(key,enc);signature=new Signature(signature,"hex");var r=signature.r;var s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return false;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return false;var sinv=s.invm(this.n);var u1=sinv.mul(msg).umod(this.n);var u2=sinv.mul(r).umod(this.n);if(!this.curve._maxwellTrick){var p=this.g.mulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.getX().umod(this.n).cmp(r)===0}var p=this.g.jmulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.eqXToP(r)};EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,"The recovery param is more than two bits");signature=new Signature(signature,enc);var n=this.n;var e=new BN(msg);var r=signature.r;var s=signature.s;var isYOdd=j&1;var isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");if(isSecondKey)r=this.curve.pointFromX(r.add(this.curve.n),isYOdd);else r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n);var s1=n.sub(e).mul(rInv).umod(n);var s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)};EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){signature=new Signature(signature,enc);if(signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")}},{"../../elliptic":41,"./key":49,"./signature":50,"bn.js":39}],49:[function(require,module,exports){"use strict";var BN=require("bn.js");function KeyPair(ec,options){this.ec=ec;this.priv=null;this.pub=null;if(options.priv)this._importPrivate(options.priv,options.privEnc);if(options.pub)this._importPublic(options.pub,options.pubEnc)}module.exports=KeyPair;KeyPair.fromPublic=function fromPublic(ec,pub,enc){if(pub instanceof KeyPair)return pub;return new KeyPair(ec,{pub:pub,pubEnc:enc})};KeyPair.fromPrivate=function fromPrivate(ec,priv,enc){if(priv instanceof KeyPair)return priv;return new KeyPair(ec,{priv:priv,privEnc:enc})};KeyPair.prototype.validate=function validate(){var pub=this.getPublic();if(pub.isInfinity())return{result:false,reason:"Invalid public key"};if(!pub.validate())return{result:false,reason:"Public key is not a point"};if(!pub.mul(this.ec.curve.n).isInfinity())return{result:false,reason:"Public key * N != O"};return{result:true,reason:null}};KeyPair.prototype.getPublic=function getPublic(compact,enc){if(typeof compact==="string"){enc=compact;compact=null}if(!this.pub)this.pub=this.ec.g.mul(this.priv);if(!enc)return this.pub;return this.pub.encode(enc,compact)};KeyPair.prototype.getPrivate=function getPrivate(enc){if(enc==="hex")return this.priv.toString(16,2);else return this.priv};KeyPair.prototype._importPrivate=function _importPrivate(key,enc){this.priv=new BN(key,enc||16);this.priv=this.priv.umod(this.ec.curve.n)};KeyPair.prototype._importPublic=function _importPublic(key,enc){if(key.x||key.y){this.pub=this.ec.curve.point(key.x,key.y);return}this.pub=this.ec.curve.decodePoint(key,enc)};KeyPair.prototype.derive=function derive(pub){return pub.mul(this.priv).getX()};KeyPair.prototype.sign=function sign(msg,enc,options){return this.ec.sign(msg,this,enc,options)};KeyPair.prototype.verify=function verify(msg,signature){return this.ec.verify(msg,signature,this)};KeyPair.prototype.inspect=function inspect(){return""}},{"bn.js":39}],50:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;if(this._importDER(options,enc))return;assert(options.r&&options.s,"Signature without r or s");this.r=new BN(options.r,16);this.s=new BN(options.s,16);if(options.recoveryParam===undefined)this.recoveryParam=null;else this.recoveryParam=options.recoveryParam}module.exports=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128)){return initial}var octetLen=initial&15;var val=0;for(var i=0,off=p.place;i>>3);arr.push(octets|128);while(--octets){arr.push(len>>>(octets<<3)&255)}arr.push(len)}Signature.prototype.toDER=function toDER(enc){var r=this.r.toArray();var s=this.s.toArray();if(r[0]&128)r=[0].concat(r);if(s[0]&128)s=[0].concat(s);r=rmPadding(r);s=rmPadding(s);while(!s[0]&&!(s[1]&128)){s=s.slice(1)}var arr=[2];constructLength(arr,r.length);arr=arr.concat(r);arr.push(2);constructLength(arr,s.length);var backHalf=arr.concat(s);var res=[48];constructLength(res,backHalf.length);res=res.concat(backHalf);return utils.encode(res,enc)}},{"../../elliptic":41,"bn.js":39}],51:[function(require,module,exports){"use strict";var hash=require("hash.js");var elliptic=require("../../elliptic");var utils=elliptic.utils;var assert=utils.assert;var parseBytes=utils.parseBytes;var KeyPair=require("./key");var Signature=require("./signature");function EDDSA(curve){assert(curve==="ed25519","only tested with ed25519 so far");if(!(this instanceof EDDSA))return new EDDSA(curve);var curve=elliptic.curves[curve].curve;this.curve=curve;this.g=curve.g;this.g.precompute(curve.n.bitLength()+1);this.pointClass=curve.point().constructor;this.encodingLength=Math.ceil(curve.n.bitLength()/8);this.hash=hash.sha512}module.exports=EDDSA;EDDSA.prototype.sign=function sign(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret);var r=this.hashInt(key.messagePrefix(),message);var R=this.g.mul(r);var Rencoded=this.encodePoint(R);var s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv());var S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})};EDDSA.prototype.verify=function verify(message,sig,pub){message=parseBytes(message);sig=this.makeSignature(sig);var key=this.keyFromPublic(pub);var h=this.hashInt(sig.Rencoded(),key.pubBytes(),message);var SG=this.g.mul(sig.S());var RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)};EDDSA.prototype.hashInt=function hashInt(){var hash=this.hash();for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._init(entropy,nonce,pers)}module.exports=HmacDRBG;HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8);this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._update(entropy.concat(add||[]));this.reseed=1};HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this.reseed>this.reseedInterval)throw new Error("Reseed is required");if(typeof enc!=="string"){addEnc=add;add=enc;enc=null}if(add){add=utils.toArray(add,addEnc);this._update(add)}var temp=[];while(temp.length>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}else if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i=0){var z;if(k.isOdd()){var mod=k.andln(ws-1);if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf.push(z);var shift=k.cmpn(0)!==0&&k.andln(ws-1)===0?w+1:1;for(var i=1;i0||k2.cmpn(-d2)>0){var m14=k1.andln(3)+d1&3;var m24=k2.andln(3)+d2&3;if(m14===3)m14=-1;if(m24===3)m24=-1;var u1;if((m14&1)===0){u1=0}else{var m8=k1.andln(7)+d1&7;if((m8===3||m8===5)&&m24===2)u1=-m14;else u1=m14}jsf[0].push(u1);var u2;if((m24&1)===0){u2=0}else{var m8=k2.andln(7)+d2&7;if((m8===3||m8===5)&&m14===2)u2=-m24;else u2=m24}jsf[1].push(u2);if(2*d1===u1+1)d1=1-d1;if(2*d2===u2+1)d2=1-d2;k1.iushrn(1);k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return this[key]!==undefined?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==="string"?utils.toArray(bytes,"hex"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,"hex","le")}utils.intFromLE=intFromLE},{"bn.js":39}],57:[function(require,module,exports){var r;module.exports=function rand(len){if(!r)r=new Rand(null);return r.generate(len)};function Rand(rand){this.rand=rand}module.exports.Rand=Rand;Rand.prototype.generate=function generate(len){return this._rand(len)};if(typeof window==="object"){if(window.crypto&&window.crypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);window.crypto.getRandomValues(arr);return arr}}else if(window.msCrypto&&window.msCrypto.getRandomValues){Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);window.msCrypto.getRandomValues(arr);return arr}}else{Rand.prototype._rand=function(){throw new Error("Not implemented yet")}}}else{try{var crypto=require("crypto"); -Rand.prototype._rand=function _rand(n){return crypto.randomBytes(n)}}catch(e){Rand.prototype._rand=function _rand(n){var res=new Uint8Array(n);for(var i=0;i=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length);if(this.pending.length===0)this.pending=null;msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255;res[i++]=len>>>16&255;res[i++]=len>>>8&255;res[i++]=len&255}else{res[i++]=len&255;res[i++]=len>>>8&255;res[i++]=len>>>16&255;res[i++]=len>>>24&255;res[i++]=0;res[i++]=0;res[i++]=0;res[i++]=0;for(var t=8;tthis.blockSize)key=(new this.Hash).update(key).digest();assert(key.length<=this.blockSize);for(var i=key.length;i>>3}function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}function ft_1(s,x,y,z){if(s===0)return ch32(x,y,z);if(s===1||s===3)return p32(x,y,z);if(s===2)return maj32(x,y,z)}function ch64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^~xh&zh;if(r<0)r+=4294967296;return r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;if(r<0)r+=4294967296;return r}function maj64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^xh&zh^yh&zh;if(r<0)r+=4294967296;return r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;if(r<0)r+=4294967296;return r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28);var c1_hi=rotr64_hi(xl,xh,2);var c2_hi=rotr64_hi(xl,xh,7);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28);var c1_lo=rotr64_lo(xl,xh,2);var c2_lo=rotr64_lo(xl,xh,7);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14);var c1_hi=rotr64_hi(xh,xl,18);var c2_hi=rotr64_hi(xl,xh,9);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14);var c1_lo=rotr64_lo(xh,xl,18);var c2_lo=rotr64_lo(xl,xh,9);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1);var c1_hi=rotr64_hi(xh,xl,8);var c2_hi=shr64_hi(xh,xl,7);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1);var c1_lo=rotr64_lo(xh,xl,8);var c2_lo=shr64_lo(xh,xl,7);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19);var c1_hi=rotr64_hi(xl,xh,29);var c2_hi=shr64_hi(xh,xl,6);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19);var c1_lo=rotr64_lo(xl,xh,29);var c2_lo=shr64_lo(xh,xl,6);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}},{"../hash":58}],63:[function(require,module,exports){var utils=exports;var inherits=require("inherits");function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==="string"){if(!enc){for(var i=0;i>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}else if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}utils.htonl=htonl;function toHex32(msg,endian){var res="";for(var i=0;i>>0}return res}utils.join32=join32;function split32(msg,endian){var res=new Array(msg.length*4);for(var i=0,k=0;i>>24;res[k+1]=m>>>16&255;res[k+2]=m>>>8&255;res[k+3]=m&255}else{res[k+3]=m>>>24;res[k+2]=m>>>16&255;res[k+1]=m>>>8&255;res[k]=m&255}}return res}utils.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}utils.rotr32=rotr32;function rotl32(w,b){return w<>>32-b}utils.rotl32=rotl32;function sum32(a,b){return a+b>>>0}utils.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}utils.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}utils.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}utils.sum32_5=sum32_5;function assert(cond,msg){if(!cond)throw new Error(msg||"Assertion failed")}utils.assert=assert;utils.inherits=inherits;function sum64(buf,pos,ah,al){var bh=buf[pos];var bl=buf[pos+1];var lo=al+bl>>>0;var hi=(lo>>0;buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0;var hi=(lo>>0}exports.sum64_hi=sum64_hi;function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}exports.sum64_lo=sum64_lo;function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0;var lo=al;lo=lo+bl>>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>0}exports.sum64_4_hi=sum64_4_hi;function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}exports.sum64_4_lo=sum64_4_lo;function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0;var lo=al;lo=lo+bl>>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>0}exports.sum64_5_hi=sum64_5_hi;function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}exports.sum64_5_lo=sum64_5_lo;function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}exports.rotr64_hi=rotr64_hi;function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.rotr64_lo=rotr64_lo;function shr64_hi(ah,al,num){return ah>>>num}exports.shr64_hi=shr64_hi;function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.shr64_lo=shr64_lo},{inherits:200}],64:[function(require,module,exports){module.exports={name:"elliptic",version:"6.3.2",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},keywords:["EC","Elliptic","curve","Cryptography"],author:{name:"Fedor Indutny",email:"fedor@indutny.com"},license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0",inherits:"^2.0.1"},gitHead:"cbace4683a4a548dc0306ef36756151a20299cd5",_id:"elliptic@6.3.2",_shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",_from:"elliptic@>=6.0.0 <7.0.0",_npmVersion:"3.10.3",_nodeVersion:"6.3.0",_npmUser:{name:"indutny",email:"fedor@indutny.com"},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},maintainers:[{name:"indutny",email:"fedor@indutny.com"}],_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},directories:{},_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz",readme:"ERROR: No README data found!"}},{}],65:[function(require,module,exports){module.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],66:[function(require,module,exports){var asn1=require("asn1.js");var RSAPrivateKey=asn1.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});exports.RSAPrivateKey=RSAPrivateKey;var RSAPublicKey=asn1.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});exports.RSAPublicKey=RSAPublicKey;var PublicKey=asn1.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPublicKey").bitstr())});exports.PublicKey=PublicKey;var AlgorithmIdentifier=asn1.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())});var PrivateKeyInfo=asn1.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPrivateKey").octstr())});exports.PrivateKey=PrivateKeyInfo;var EncryptedPrivateKeyInfo=asn1.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});exports.EncryptedPrivateKey=EncryptedPrivateKeyInfo;var DSAPrivateKey=asn1.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});exports.DSAPrivateKey=DSAPrivateKey;exports.DSAparam=asn1.define("DSAparam",function(){this.int()});var ECPrivateKey=asn1.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(ECParameters),this.key("publicKey").optional().explicit(1).bitstr())});exports.ECPrivateKey=ECPrivateKey;var ECParameters=asn1.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});exports.signature=asn1.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"asn1.js":69}],67:[function(require,module,exports){(function(Buffer){var findProc=/Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\r?\n\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n/m;var startRegex=/^-----BEGIN (.*) KEY-----\r?\n/m;var fullRegex=/^-----BEGIN (.*) KEY-----\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n-----END \1 KEY-----$/m;var evp=require("evp_bytestokey");var ciphers=require("browserify-aes");module.exports=function(okey,password){var key=okey.toString();var match=key.match(findProc);var decrypted;if(!match){var match2=key.match(fullRegex);decrypted=new Buffer(match2[2].replace(/\r?\n/g,""),"base64")}else{var suite="aes"+match[1];var iv=new Buffer(match[2],"hex");var cipherText=new Buffer(match[3].replace(/\r?\n/g,""),"base64");var cipherKey=evp(password,iv.slice(0,8),parseInt(match[1],10)).key;var out=[];var cipher=ciphers.createDecipheriv(suite,cipherKey,iv);out.push(cipher.update(cipherText));out.push(cipher.final());decrypted=Buffer.concat(out)}var tag=key.match(startRegex)[1]+" KEY";return{tag:tag,data:decrypted}}}).call(this,require("buffer").Buffer)},{"browserify-aes":86,buffer:2,evp_bytestokey:101}],68:[function(require,module,exports){(function(Buffer){var asn1=require("./asn1");var aesid=require("./aesid.json");var fixProc=require("./fixProc");var ciphers=require("browserify-aes");var compat=require("pbkdf2");module.exports=parseKeys;function parseKeys(buffer){var password;if(typeof buffer==="object"&&!Buffer.isBuffer(buffer)){password=buffer.passphrase;buffer=buffer.key}if(typeof buffer==="string"){buffer=new Buffer(buffer)}var stripped=fixProc(buffer,password);var type=stripped.tag;var data=stripped.data;var subtype,ndata;switch(type){case"PUBLIC KEY":ndata=asn1.PublicKey.decode(data,"der");subtype=ndata.algorithm.algorithm.join(".");switch(subtype){case"1.2.840.113549.1.1.1":return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":ndata.subjectPrivateKey=ndata.subjectPublicKey;return{type:"ec",data:ndata};case"1.2.840.10040.4.1":ndata.algorithm.params.pub_key=asn1.DSAparam.decode(ndata.subjectPublicKey.data,"der");return{type:"dsa",data:ndata.algorithm.params};default:throw new Error("unknown key id "+subtype)}throw new Error("unknown key type "+type);case"ENCRYPTED PRIVATE KEY":data=asn1.EncryptedPrivateKey.decode(data,"der");data=decrypt(data,password);case"PRIVATE KEY":ndata=asn1.PrivateKey.decode(data,"der");subtype=ndata.algorithm.algorithm.join(".");switch(subtype){case"1.2.840.113549.1.1.1":return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:ndata.algorithm.curve,privateKey:asn1.ECPrivateKey.decode(ndata.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":ndata.algorithm.params.priv_key=asn1.DSAparam.decode(ndata.subjectPrivateKey,"der");return{type:"dsa",params:ndata.algorithm.params};default:throw new Error("unknown key id "+subtype)}throw new Error("unknown key type "+type);case"RSA PUBLIC KEY":return asn1.RSAPublicKey.decode(data,"der");case"RSA PRIVATE KEY":return asn1.RSAPrivateKey.decode(data,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:asn1.DSAPrivateKey.decode(data,"der")};case"EC PRIVATE KEY":data=asn1.ECPrivateKey.decode(data,"der");return{curve:data.parameters.value,privateKey:data.privateKey};default:throw new Error("unknown key type "+type)}}parseKeys.signature=asn1.signature;function decrypt(data,password){var salt=data.algorithm.decrypt.kde.kdeparams.salt;var iters=parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(),10);var algo=aesid[data.algorithm.decrypt.cipher.algo.join(".")];var iv=data.algorithm.decrypt.cipher.iv;var cipherText=data.subjectPrivateKey;var keylen=parseInt(algo.split("-")[1],10)/8;var key=compat.pbkdf2Sync(password,salt,iters,keylen);var cipher=ciphers.createDecipheriv(algo,key,iv);var out=[];out.push(cipher.update(cipherText));out.push(cipher.final());return Buffer.concat(out)}}).call(this,require("buffer").Buffer)},{"./aesid.json":65,"./asn1":66,"./fixProc":67,"browserify-aes":86,buffer:2,pbkdf2:151}],69:[function(require,module,exports){var asn1=exports;asn1.bignum=require("bn.js");asn1.define=require("./asn1/api").define;asn1.base=require("./asn1/base");asn1.constants=require("./asn1/constants");asn1.decoders=require("./asn1/decoders");asn1.encoders=require("./asn1/encoders")},{"./asn1/api":70,"./asn1/base":72,"./asn1/constants":76,"./asn1/decoders":78,"./asn1/encoders":81,"bn.js":39}],70:[function(require,module,exports){var asn1=require("../asn1");var inherits=require("inherits");var api=exports;api.define=function define(name,body){return new Entity(name,body)};function Entity(name,body){this.name=name;this.body=body;this.decoders={};this.encoders={}}Entity.prototype._createNamed=function createNamed(base){var named;try{named=require("vm").runInThisContext("(function "+this.name+"(entity) {\n"+" this._initNamed(entity);\n"+"})")}catch(e){named=function(entity){this._initNamed(entity)}}inherits(named,base);named.prototype._initNamed=function initnamed(entity){base.call(this,entity)};return new named(this)};Entity.prototype._getDecoder=function _getDecoder(enc){enc=enc||"der";if(!this.decoders.hasOwnProperty(enc))this.decoders[enc]=this._createNamed(asn1.decoders[enc]);return this.decoders[enc]};Entity.prototype.decode=function decode(data,enc,options){return this._getDecoder(enc).decode(data,options)};Entity.prototype._getEncoder=function _getEncoder(enc){enc=enc||"der";if(!this.encoders.hasOwnProperty(enc))this.encoders[enc]=this._createNamed(asn1.encoders[enc]);return this.encoders[enc]};Entity.prototype.encode=function encode(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},{"../asn1":69,inherits:200,vm:221}],71:[function(require,module,exports){var inherits=require("inherits");var Reporter=require("../base").Reporter;var Buffer=require("buffer").Buffer;function DecoderBuffer(base,options){Reporter.call(this,options);if(!Buffer.isBuffer(base)){this.error("Input not Buffer");return}this.base=base;this.offset=0;this.length=base.length} -inherits(DecoderBuffer,Reporter);exports.DecoderBuffer=DecoderBuffer;DecoderBuffer.prototype.save=function save(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}};DecoderBuffer.prototype.restore=function restore(save){var res=new DecoderBuffer(this.base);res.offset=save.offset;res.length=this.offset;this.offset=save.offset;Reporter.prototype.restore.call(this,save.reporter);return res};DecoderBuffer.prototype.isEmpty=function isEmpty(){return this.offset===this.length};DecoderBuffer.prototype.readUInt8=function readUInt8(fail){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,true);else return this.error(fail||"DecoderBuffer overrun")};DecoderBuffer.prototype.skip=function skip(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");var res=new DecoderBuffer(this.base);res._reporterState=this._reporterState;res.offset=this.offset;res.length=this.offset+bytes;this.offset+=bytes;return res};DecoderBuffer.prototype.raw=function raw(save){return this.base.slice(save?save.offset:this.offset,this.length)};function EncoderBuffer(value,reporter){if(Array.isArray(value)){this.length=0;this.value=value.map(function(item){if(!(item instanceof EncoderBuffer))item=new EncoderBuffer(item,reporter);this.length+=item.length;return item},this)}else if(typeof value==="number"){if(!(0<=value&&value<=255))return reporter.error("non-byte EncoderBuffer value");this.value=value;this.length=1}else if(typeof value==="string"){this.value=value;this.length=Buffer.byteLength(value)}else if(Buffer.isBuffer(value)){this.value=value;this.length=value.length}else{return reporter.error("Unsupported type: "+typeof value)}}exports.EncoderBuffer=EncoderBuffer;EncoderBuffer.prototype.join=function join(out,offset){if(!out)out=new Buffer(this.length);if(!offset)offset=0;if(this.length===0)return out;if(Array.isArray(this.value)){this.value.forEach(function(item){item.join(out,offset);offset+=item.length})}else{if(typeof this.value==="number")out[offset]=this.value;else if(typeof this.value==="string")out.write(this.value,offset);else if(Buffer.isBuffer(this.value))this.value.copy(out,offset);offset+=this.length}return out}},{"../base":72,buffer:2,inherits:200}],72:[function(require,module,exports){var base=exports;base.Reporter=require("./reporter").Reporter;base.DecoderBuffer=require("./buffer").DecoderBuffer;base.EncoderBuffer=require("./buffer").EncoderBuffer;base.Node=require("./node")},{"./buffer":71,"./node":73,"./reporter":74}],73:[function(require,module,exports){var Reporter=require("../base").Reporter;var EncoderBuffer=require("../base").EncoderBuffer;var DecoderBuffer=require("../base").DecoderBuffer;var assert=require("minimalistic-assert");var tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"];var methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags);var overrided=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function Node(enc,parent){var state={};this._baseState=state;state.enc=enc;state.parent=parent||null;state.children=null;state.tag=null;state.args=null;state.reverseArgs=null;state.choice=null;state.optional=false;state.any=false;state.obj=false;state.use=null;state.useDecoder=null;state.key=null;state["default"]=null;state.explicit=null;state.implicit=null;state.contains=null;if(!state.parent){state.children=[];this._wrap()}}module.exports=Node;var stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function clone(){var state=this._baseState;var cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});var res=new this.constructor(cstate.parent);res._baseState=cstate;return res};Node.prototype._wrap=function wrap(){var state=this._baseState;methods.forEach(function(method){this[method]=function _wrappedMethod(){var clone=new this.constructor(this);state.children.push(clone);return clone[method].apply(clone,arguments)}},this)};Node.prototype._init=function init(body){var state=this._baseState;assert(state.parent===null);body.call(this);state.children=state.children.filter(function(child){return child._baseState.parent===this},this);assert.equal(state.children.length,1,"Root node can have only one child")};Node.prototype._useArgs=function useArgs(args){var state=this._baseState;var children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this);if(children.length!==0){assert(state.children===null);state.children=children;children.forEach(function(child){child._baseState.parent=this},this)}if(args.length!==0){assert(state.args===null);state.args=args;state.reverseArgs=args.map(function(arg){if(typeof arg!=="object"||arg.constructor!==Object)return arg;var res={};Object.keys(arg).forEach(function(key){if(key==(key|0))key|=0;var value=arg[key];res[value]=key});return res})}};overrided.forEach(function(method){Node.prototype[method]=function _overrided(){var state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}});tags.forEach(function(tag){Node.prototype[tag]=function _tagMethod(){var state=this._baseState;var args=Array.prototype.slice.call(arguments);assert(state.tag===null);state.tag=tag;this._useArgs(args);return this}});Node.prototype.use=function use(item){var state=this._baseState;assert(state.use===null);state.use=item;return this};Node.prototype.optional=function optional(){var state=this._baseState;state.optional=true;return this};Node.prototype.def=function def(val){var state=this._baseState;assert(state["default"]===null);state["default"]=val;state.optional=true;return this};Node.prototype.explicit=function explicit(num){var state=this._baseState;assert(state.explicit===null&&state.implicit===null);state.explicit=num;return this};Node.prototype.implicit=function implicit(num){var state=this._baseState;assert(state.explicit===null&&state.implicit===null);state.implicit=num;return this};Node.prototype.obj=function obj(){var state=this._baseState;var args=Array.prototype.slice.call(arguments);state.obj=true;if(args.length!==0)this._useArgs(args);return this};Node.prototype.key=function key(newKey){var state=this._baseState;assert(state.key===null);state.key=newKey;return this};Node.prototype.any=function any(){var state=this._baseState;state.any=true;return this};Node.prototype.choice=function choice(obj){var state=this._baseState;assert(state.choice===null);state.choice=obj;this._useArgs(Object.keys(obj).map(function(key){return obj[key]}));return this};Node.prototype.contains=function contains(item){var state=this._baseState;assert(state.use===null);state.contains=item;return this};Node.prototype._decode=function decode(input,options){var state=this._baseState;if(state.parent===null)return input.wrapResult(state.children[0]._decode(input,options));var result=state["default"];var present=true;var prevKey=null;if(state.key!==null)prevKey=input.enterKey(state.key);if(state.optional){var tag=null;if(state.explicit!==null)tag=state.explicit;else if(state.implicit!==null)tag=state.implicit;else if(state.tag!==null)tag=state.tag;if(tag===null&&!state.any){var save=input.save();try{if(state.choice===null)this._decodeGeneric(state.tag,input,options);else this._decodeChoice(input,options);present=true}catch(e){present=false}input.restore(save)}else{present=this._peekTag(input,tag,state.any);if(input.isError(present))return present}}var prevObj;if(state.obj&&present)prevObj=input.enterObject();if(present){if(state.explicit!==null){var explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}var start=input.offset;if(state.use===null&&state.choice===null){if(state.any)var save=input.save();var body=this._decodeTag(input,state.implicit!==null?state.implicit:state.tag,state.any);if(input.isError(body))return body;if(state.any)result=input.raw(save);else input=body}if(options&&options.track&&state.tag!==null)options.track(input.path(),start,input.length,"tagged");if(options&&options.track&&state.tag!==null)options.track(input.path(),input.offset,input.length,"content");if(state.any)result=result;else if(state.choice===null)result=this._decodeGeneric(state.tag,input,options);else result=this._decodeChoice(input,options);if(input.isError(result))return result;if(!state.any&&state.choice===null&&state.children!==null){state.children.forEach(function decodeChildren(child){child._decode(input,options)})}if(state.contains&&(state.tag==="octstr"||state.tag==="bitstr")){var data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}if(state.obj&&present)result=input.leaveObject(prevObj);if(state.key!==null&&(result!==null||present===true))input.leaveKey(prevKey,state.key,result);else if(prevKey!==null)input.exitKey(prevKey);return result};Node.prototype._decodeGeneric=function decodeGeneric(tag,input,options){var state=this._baseState;if(tag==="seq"||tag==="set")return null;if(tag==="seqof"||tag==="setof")return this._decodeList(input,tag,state.args[0],options);else if(/str$/.test(tag))return this._decodeStr(input,tag,options);else if(tag==="objid"&&state.args)return this._decodeObjid(input,state.args[0],state.args[1],options);else if(tag==="objid")return this._decodeObjid(input,null,null,options);else if(tag==="gentime"||tag==="utctime")return this._decodeTime(input,tag,options);else if(tag==="null_")return this._decodeNull(input,options);else if(tag==="bool")return this._decodeBool(input,options);else if(tag==="int"||tag==="enum")return this._decodeInt(input,state.args&&state.args[0],options);if(state.use!==null){return this._getUse(state.use,input._reporterState.obj)._decode(input,options)}else{return input.error("unknown tag: "+tag)}};Node.prototype._getUse=function _getUse(entity,obj){var state=this._baseState;state.useDecoder=this._use(entity,obj);assert(state.useDecoder._baseState.parent===null);state.useDecoder=state.useDecoder._baseState.children[0];if(state.implicit!==state.useDecoder._baseState.implicit){state.useDecoder=state.useDecoder.clone();state.useDecoder._baseState.implicit=state.implicit}return state.useDecoder};Node.prototype._decodeChoice=function decodeChoice(input,options){var state=this._baseState;var result=null;var match=false;Object.keys(state.choice).some(function(key){var save=input.save();var node=state.choice[key];try{var value=node._decode(input,options);if(input.isError(value))return false;result={type:key,value:value};match=true}catch(e){input.restore(save);return false}return true},this);if(!match)return input.error("Choice not matched");return result};Node.prototype._createEncoderBuffer=function createEncoderBuffer(data){return new EncoderBuffer(data,this.reporter)};Node.prototype._encode=function encode(data,reporter,parent){var state=this._baseState;if(state["default"]!==null&&state["default"]===data)return;var result=this._encodeValue(data,reporter,parent);if(result===undefined)return;if(this._skipDefault(result,reporter,parent))return;return result};Node.prototype._encodeValue=function encode(data,reporter,parent){var state=this._baseState;if(state.parent===null)return state.children[0]._encode(data,reporter||new Reporter);var result=null;this.reporter=reporter;if(state.optional&&data===undefined){if(state["default"]!==null)data=state["default"];else return}var content=null;var primitive=false;if(state.any){result=this._createEncoderBuffer(data)}else if(state.choice){result=this._encodeChoice(data,reporter)}else if(state.contains){content=this._getUse(state.contains,parent)._encode(data,reporter);primitive=true}else if(state.children){content=state.children.map(function(child){if(child._baseState.tag==="null_")return child._encode(null,reporter,data);if(child._baseState.key===null)return reporter.error("Child should have a key");var prevKey=reporter.enterKey(child._baseState.key);if(typeof data!=="object")return reporter.error("Child expected, but input is not object");var res=child._encode(data[child._baseState.key],reporter,data);reporter.leaveKey(prevKey);return res},this).filter(function(child){return child});content=this._createEncoderBuffer(content)}else{if(state.tag==="seqof"||state.tag==="setof"){if(!(state.args&&state.args.length===1))return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");var child=this.clone();child._baseState.implicit=null;content=this._createEncoderBuffer(data.map(function(item){var state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else if(state.use!==null){result=this._getUse(state.use,parent)._encode(data,reporter)}else{content=this._encodePrimitive(state.tag,data);primitive=true}}var result;if(!state.any&&state.choice===null){var tag=state.implicit!==null?state.implicit:state.tag;var cls=state.implicit===null?"universal":"context";if(tag===null){if(state.use===null)reporter.error("Tag could be ommited only for .use()")}else{if(state.use===null)result=this._encodeComposite(tag,primitive,cls,content)}}if(state.explicit!==null)result=this._encodeComposite(state.explicit,false,"context",result);return result};Node.prototype._encodeChoice=function encodeChoice(data,reporter){var state=this._baseState;var node=state.choice[data.type];if(!node){assert(false,data.type+" not found in "+JSON.stringify(Object.keys(state.choice)))}return node._encode(data.value,reporter)};Node.prototype._encodePrimitive=function encodePrimitive(tag,data){var state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);else if(tag==="objid"&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);else if(tag==="objid")return this._encodeObjid(data,null,null);else if(tag==="gentime"||tag==="utctime")return this._encodeTime(data,tag);else if(tag==="null_")return this._encodeNull();else if(tag==="int"||tag==="enum")return this._encodeInt(data,state.args&&state.reverseArgs[0]);else if(tag==="bool")return this._encodeBool(data);else throw new Error("Unsupported tag: "+tag)};Node.prototype._isNumstr=function isNumstr(str){return/^[0-9 ]*$/.test(str)};Node.prototype._isPrintstr=function isPrintstr(str){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str)}},{"../base":72,"minimalistic-assert":83}],74:[function(require,module,exports){var inherits=require("inherits");function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}exports.Reporter=Reporter;Reporter.prototype.isError=function isError(obj){return obj instanceof ReporterError};Reporter.prototype.save=function save(){var state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}};Reporter.prototype.restore=function restore(data){var state=this._reporterState;state.obj=data.obj;state.path=state.path.slice(0,data.pathLen)};Reporter.prototype.enterKey=function enterKey(key){return this._reporterState.path.push(key)};Reporter.prototype.exitKey=function exitKey(index){var state=this._reporterState;state.path=state.path.slice(0,index-1)};Reporter.prototype.leaveKey=function leaveKey(index,key,value){var state=this._reporterState;this.exitKey(index);if(state.obj!==null)state.obj[key]=value};Reporter.prototype.path=function path(){return this._reporterState.path.join("/")};Reporter.prototype.enterObject=function enterObject(){var state=this._reporterState;var prev=state.obj;state.obj={};return prev};Reporter.prototype.leaveObject=function leaveObject(prev){var state=this._reporterState;var now=state.obj;state.obj=prev;return now};Reporter.prototype.error=function error(msg){var err;var state=this._reporterState;var inherited=msg instanceof ReporterError;if(inherited){err=msg}else{err=new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack)}if(!state.options.partial)throw err;if(!inherited)state.errors.push(err);return err};Reporter.prototype.wrapResult=function wrapResult(result){var state=this._reporterState;if(!state.options.partial)return result;return{result:this.isError(result)?null:result,errors:state.errors}};function ReporterError(path,msg){this.path=path;this.rethrow(msg)}inherits(ReporterError,Error);ReporterError.prototype.rethrow=function rethrow(msg){this.message=msg+" at: "+(this.path||"(shallow)");if(Error.captureStackTrace)Error.captureStackTrace(this,ReporterError);if(!this.stack){try{throw new Error(this.message)}catch(e){this.stack=e.stack}}return this}},{inherits:200}],75:[function(require,module,exports){var constants=require("../constants");exports.tagClass={0:"universal",1:"application",2:"context",3:"private"};exports.tagClassByName=constants._reverse(exports.tagClass);exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};exports.tagByName=constants._reverse(exports.tag)},{"../constants":76}],76:[function(require,module,exports){var constants=exports;constants._reverse=function reverse(map){var res={};Object.keys(map).forEach(function(key){if((key|0)==key)key=key|0;var value=map[key];res[value]=key});return res};constants.der=require("./der")},{"./der":75}],77:[function(require,module,exports){var inherits=require("inherits");var asn1=require("../../asn1");var base=asn1.base;var bignum=asn1.bignum;var der=asn1.constants.der;function DERDecoder(entity){this.enc="der";this.name=entity.name;this.entity=entity;this.tree=new DERNode;this.tree._init(entity.body)}module.exports=DERDecoder;DERDecoder.prototype.decode=function decode(data,options){if(!(data instanceof base.DecoderBuffer))data=new base.DecoderBuffer(data,options);return this.tree._decode(data,options)};function DERNode(parent){base.Node.call(this,"der",parent)}inherits(DERNode,base.Node);DERNode.prototype._peekTag=function peekTag(buffer,tag,any){if(buffer.isEmpty())return false;var state=buffer.save();var decodedTag=derDecodeTag(buffer,'Failed to peek tag: "'+tag+'"');if(buffer.isError(decodedTag))return decodedTag;buffer.restore(state);return decodedTag.tag===tag||decodedTag.tagStr===tag||decodedTag.tagStr+"of"===tag||any};DERNode.prototype._decodeTag=function decodeTag(buffer,tag,any){var decodedTag=derDecodeTag(buffer,'Failed to decode tag of "'+tag+'"');if(buffer.isError(decodedTag))return decodedTag;var len=derDecodeLen(buffer,decodedTag.primitive,'Failed to get length of "'+tag+'"');if(buffer.isError(len))return len;if(!any&&decodedTag.tag!==tag&&decodedTag.tagStr!==tag&&decodedTag.tagStr+"of"!==tag){return buffer.error('Failed to match tag: "'+tag+'"')}if(decodedTag.primitive||len!==null)return buffer.skip(len,'Failed to match body of: "'+tag+'"');var state=buffer.save();var res=this._skipUntilEnd(buffer,'Failed to skip indefinite length body: "'+this.tag+'"');if(buffer.isError(res))return res;len=buffer.offset-state.offset;buffer.restore(state);return buffer.skip(len,'Failed to match body of: "'+tag+'"')};DERNode.prototype._skipUntilEnd=function skipUntilEnd(buffer,fail){while(true){var tag=derDecodeTag(buffer,fail);if(buffer.isError(tag))return tag;var len=derDecodeLen(buffer,tag.primitive,fail);if(buffer.isError(len))return len;var res;if(tag.primitive||len!==null)res=buffer.skip(len);else res=this._skipUntilEnd(buffer,fail);if(buffer.isError(res))return res;if(tag.tagStr==="end")break}};DERNode.prototype._decodeList=function decodeList(buffer,tag,decoder,options){var result=[];while(!buffer.isEmpty()){var possibleEnd=this._peekTag(buffer,"end");if(buffer.isError(possibleEnd))return possibleEnd;var res=decoder.decode(buffer,"der",options);if(buffer.isError(res)&&possibleEnd)break;result.push(res)}return result};DERNode.prototype._decodeStr=function decodeStr(buffer,tag){if(tag==="bitstr"){var unused=buffer.readUInt8();if(buffer.isError(unused))return unused;return{unused:unused,data:buffer.raw()}}else if(tag==="bmpstr"){var raw=buffer.raw();if(raw.length%2===1)return buffer.error("Decoding of string type: bmpstr length mismatch");var str="";for(var i=0;i>6];var primitive=(tag&32)===0;if((tag&31)===31){var oct=tag;tag=0;while((oct&128)===128){oct=buf.readUInt8(fail);if(buf.isError(oct))return oct;tag<<=7;tag|=oct&127}}else{tag&=31}var tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){var len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&len===128)return null;if((len&128)===0){return len}var num=len&127;if(num>=4)return buf.error("length octect is too long");len=0;for(var i=0;i=256;i>>=8)lenOctets++;var header=new Buffer(1+1+lenOctets);header[0]=encodedTag;header[1]=128|lenOctets;for(var i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=j&255;return this._createEncoderBuffer([header,content])};DERNode.prototype._encodeStr=function encodeStr(str,tag){if(tag==="bitstr"){return this._createEncoderBuffer([str.unused|0,str.data])}else if(tag==="bmpstr"){var buf=new Buffer(str.length*2);for(var i=0;i=40)return this.reporter.error("Second objid identifier OOB");id.splice(0,2,id[0]*40+id[1])}var size=0;for(var i=0;i=128;ident>>=7)size++}var objid=new Buffer(size);var offset=objid.length-1;for(var i=id.length-1;i>=0;i--){var ident=id[i];objid[offset--]=ident&127;while((ident>>=7)>0)objid[offset--]=128|ident&127}return this._createEncoderBuffer(objid)};function two(num){if(num<10)return"0"+num;else return num}DERNode.prototype._encodeTime=function encodeTime(time,tag){var str;var date=new Date(time);if(tag==="gentime"){str=[two(date.getFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join("")}else if(tag==="utctime"){str=[two(date.getFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join("")}else{this.reporter.error("Encoding "+tag+" time is not supported yet")}return this._encodeStr(str,"octstr")};DERNode.prototype._encodeNull=function encodeNull(){return this._createEncoderBuffer("")};DERNode.prototype._encodeInt=function encodeInt(num,values){if(typeof num==="string"){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num)){return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num))}num=values[num]}if(typeof num!=="number"&&!Buffer.isBuffer(num)){var numArray=num.toArray();if(!num.sign&&numArray[0]&128){numArray.unshift(0)}num=new Buffer(numArray)}if(Buffer.isBuffer(num)){var size=num.length;if(num.length===0)size++;var out=new Buffer(size);num.copy(out);if(num.length===0)out[0]=0;return this._createEncoderBuffer(out)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);var size=1;for(var i=num;i>=256;i>>=8)size++;var out=new Array(size);for(var i=out.length-1;i>=0;i--){out[i]=num&255;num>>=8}if(out[0]&128){out.unshift(0)}return this._createEncoderBuffer(new Buffer(out))};DERNode.prototype._encodeBool=function encodeBool(value){return this._createEncoderBuffer(value?255:0)};DERNode.prototype._use=function use(entity,obj){if(typeof entity==="function")entity=entity(obj);return entity._getEncoder("der").tree};DERNode.prototype._skipDefault=function skipDefault(dataBuffer,reporter,parent){var state=this._baseState;var i;if(state["default"]===null)return false;var data=dataBuffer.join();if(state.defaultBuffer===undefined)state.defaultBuffer=this._encodeValue(state["default"],reporter,parent).join();if(data.length!==state.defaultBuffer.length)return false;for(i=0;i=31)return reporter.error("Multi-octet tag encoding unsupported");if(!primitive)res|=32;res|=der.tagClassByName[cls||"universal"]<<6;return res}},{"../../asn1":69,buffer:2,inherits:200}],81:[function(require,module,exports){var encoders=exports;encoders.der=require("./der");encoders.pem=require("./pem")},{"./der":80,"./pem":82}],82:[function(require,module,exports){var inherits=require("inherits");var DEREncoder=require("./der");function PEMEncoder(entity){DEREncoder.call(this,entity);this.enc="pem"}inherits(PEMEncoder,DEREncoder);module.exports=PEMEncoder;PEMEncoder.prototype.encode=function encode(data,options){var buf=DEREncoder.prototype.encode.call(this,data);var p=buf.toString("base64");var out=["-----BEGIN "+options.label+"-----"];for(var i=0;i0){bits.ishrn(shift)}return bits}function bits2octets(bits,q){bits=bits2int(bits,q);bits=bits.mod(q);var out=new Buffer(bits.toArray());if(out.length=q){throw new Error("invalid sig")}}module.exports=verify}).call(this,require("buffer").Buffer)},{"./curves":38,"bn.js":39,buffer:2,elliptic:41,"parse-asn1":68}],104:[function(require,module,exports){(function(Buffer){var elliptic=require("elliptic");var BN=require("bn.js");module.exports=function createECDH(curve){return new ECDH(curve)};var aliases={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};aliases.p224=aliases.secp224r1;aliases.p256=aliases.secp256r1=aliases.prime256v1;aliases.p192=aliases.secp192r1=aliases.prime192v1;aliases.p384=aliases.secp384r1;aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve];if(!this.curveType){this.curveType={name:curve}}this.curve=new elliptic.ec(this.curveType.name);this.keys=void 0}ECDH.prototype.generateKeys=function(enc,format){this.keys=this.curve.genKeyPair();return this.getPublicKey(enc,format)};ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||"utf8";if(!Buffer.isBuffer(other)){other=new Buffer(other,inenc)}var otherPub=this.curve.keyFromPublic(other).getPublic();var out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)};ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format==="compressed",true);if(format==="hybrid"){if(key[key.length-1]%2){key[0]=7}else{key[0]=6}}return formatReturnValue(key,enc)};ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)};ECDH.prototype.setPublicKey=function(pub,enc){enc=enc||"utf8";if(!Buffer.isBuffer(pub)){pub=new Buffer(pub,enc)}this.keys._importPublic(pub);return this};ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||"utf8";if(!Buffer.isBuffer(priv)){priv=new Buffer(priv,enc)}var _priv=new BN(priv);_priv=_priv.toString(16);this.keys._importPrivate(_priv);return this};function formatReturnValue(bn,enc,len){if(!Array.isArray(bn)){bn=bn.toArray()}var buf=new Buffer(bn);if(len&&buf.length=6.0.0 <7.0.0",_npmVersion:"3.10.3",_nodeVersion:"6.3.0",_npmUser:{name:"indutny",email:"fedor@indutny.com"},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},maintainers:[{name:"indutny",email:"fedor@indutny.com"}],_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},directories:{},_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"}},{}],130:[function(require,module,exports){(function(Buffer){"use strict";var inherits=require("inherits");var md5=require("./md5");var rmd160=require("ripemd160");var sha=require("sha.js");var Base=require("cipher-base");function HashNoConstructor(hash){Base.call(this,"digest");this._hash=hash;this.buffers=[]}inherits(HashNoConstructor,Base);HashNoConstructor.prototype._update=function(data){this.buffers.push(data)};HashNoConstructor.prototype._final=function(){var buf=Buffer.concat(this.buffers);var r=this._hash(buf);this.buffers=null;return r};function Hash(hash){Base.call(this,"digest");this._hash=hash}inherits(Hash,Base);Hash.prototype._update=function(data){this._hash.update(data)};Hash.prototype._final=function(){return this._hash.digest()};module.exports=function createHash(alg){alg=alg.toLowerCase();if("md5"===alg)return new HashNoConstructor(md5);if("rmd160"===alg||"ripemd160"===alg)return new HashNoConstructor(rmd160);return new Hash(sha(alg))}}).call(this,require("buffer").Buffer)},{"./md5":132,buffer:2,"cipher-base":133,inherits:200,ripemd160:134,"sha.js":136}],131:[function(require,module,exports){(function(Buffer){"use strict";var intSize=4;var zeroBuffer=new Buffer(intSize);zeroBuffer.fill(0);var chrsz=8;function toArray(buf,bigEndian){if(buf.length%intSize!==0){var len=buf.length+(intSize-buf.length%intSize);buf=Buffer.concat([buf,zeroBuffer],len)}var arr=[];var fn=bigEndian?buf.readInt32BE:buf.readInt32LE;for(var i=0;i>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":131}],133:[function(require,module,exports){arguments[4][23][0].apply(exports,arguments)},{buffer:2,dup:23,inherits:200,stream:219,string_decoder:220}],134:[function(require,module,exports){(function(Buffer){var zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13];var zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11];var sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6];var sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];var hl=[0,1518500249,1859775393,2400959708,2840853838];var hr=[1352829926,1548603684,1836072691,2053994217,0];function bytesToWords(bytes){var words=[];for(var i=0,b=0;i>>5]|=bytes[i]<<24-b%32}return words}function wordsToBytes(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes}function processBlock(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t}function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message==="string"){message=new Buffer(message,"utf8")}var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}module.exports=ripemd160}).call(this,require("buffer").Buffer)},{buffer:2}],135:[function(require,module,exports){(function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.update=function(data,enc){if(typeof data==="string"){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};module.exports=Hash}).call(this,require("buffer").Buffer)},{buffer:2}],136:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha");exports.sha1=require("./sha1");exports.sha224=require("./sha224");exports.sha256=require("./sha256");exports.sha384=require("./sha384");exports.sha512=require("./sha512")},{"./sha":137,"./sha1":138,"./sha224":139,"./sha256":140,"./sha384":141,"./sha512":142}],137:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha,Hash);Sha.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],138:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha1(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha1.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha1.prototype._hash=function(){var H=new Buffer(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha1}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],139:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Sha256=require("./sha256");var Hash=require("./hash");var W=new Array(64);function Sha224(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha224,Sha256);Sha224.prototype.init=function(){this._a=3238371032;this._b=914150663;this._c=812702999;this._d=4144912697;this._e=4290775857;this._f=1750603025;this._g=1694076839;this._h=3204075428;return this};Sha224.prototype._hash=function(){var H=new Buffer(28);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);return H};module.exports=Sha224}).call(this,require("buffer").Buffer)},{"./hash":135,"./sha256":140,buffer:2,inherits:200}],140:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703;this._b=3144134277;this._c=1013904242;this._d=2773480762;this._e=1359893119;this._f=2600822924;this._g=528734635;this._h=1541459225;return this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;var f=this._f|0;var g=this._g|0;var h=this._h|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<64;++i)W[i]=gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W[j]|0;var T2=sigma0(a)+maj(a,b,c)|0;h=g;g=f;f=e;e=d+T1|0;d=c;c=b;b=a;a=T1+T2|0}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=new Buffer(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};module.exports=Sha256}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],141:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var SHA512=require("./sha512");var Hash=require("./hash");var W=new Array(160);function Sha384(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha384,SHA512);Sha384.prototype.init=function(){this._ah=3418070365;this._bh=1654270250;this._ch=2438529370;this._dh=355462360;this._eh=1731405415;this._fh=2394180231;this._gh=3675008525;this._hh=1203062813;this._al=3238371032;this._bl=914150663;this._cl=812702999;this._dl=4144912697;this._el=4290775857;this._fl=1750603025;this._gl=1694076839;this._hl=3204075428;return this};Sha384.prototype._hash=function(){var H=new Buffer(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);return H};module.exports=Sha384}).call(this,require("buffer").Buffer)},{"./hash":135, -"./sha512":142,buffer:2,inherits:200}],142:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._ah=1779033703;this._bh=3144134277;this._ch=1013904242;this._dh=2773480762;this._eh=1359893119;this._fh=2600822924;this._gh=528734635;this._hh=1541459225;this._al=4089235720;this._bl=2227873595;this._cl=4271175723;this._dl=1595750129;this._el=2917565137;this._fl=725511199;this._gl=4215389547;this._hl=327033209;return this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}Sha512.prototype._update=function(M){var W=this._w;var ah=this._ah|0;var bh=this._bh|0;var ch=this._ch|0;var dh=this._dh|0;var eh=this._eh|0;var fh=this._fh|0;var gh=this._gh|0;var hh=this._hh|0;var al=this._al|0;var bl=this._bl|0;var cl=this._cl|0;var dl=this._dl|0;var el=this._el|0;var fl=this._fl|0;var gl=this._gl|0;var hl=this._hl|0;for(var i=0;i<32;i+=2){W[i]=M.readInt32BE(i*4);W[i+1]=M.readInt32BE(i*4+4)}for(;i<160;i+=2){var xh=W[i-15*2];var xl=W[i-15*2+1];var gamma0=Gamma0(xh,xl);var gamma0l=Gamma0l(xl,xh);xh=W[i-2*2];xl=W[i-2*2+1];var gamma1=Gamma1(xh,xl);var gamma1l=Gamma1l(xl,xh);var Wi7h=W[i-7*2];var Wi7l=W[i-7*2+1];var Wi16h=W[i-16*2];var Wi16l=W[i-16*2+1];var Wil=gamma0l+Wi7l|0;var Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0;Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0;Wil=Wil+Wi16l|0;Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0;W[i]=Wih;W[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W[j];Wil=W[j+1];var majh=maj(ah,bh,ch);var majl=maj(al,bl,cl);var sigma0h=sigma0(ah,al);var sigma0l=sigma0(al,ah);var sigma1h=sigma1(eh,el);var sigma1l=sigma1(el,eh);var Kih=K[j];var Kil=K[j+1];var chh=Ch(eh,fh,gh);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l|0;var t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0;t1h=t1h+chh+getCarry(t1l,chl)|0;t1l=t1l+Kil|0;t1h=t1h+Kih+getCarry(t1l,Kil)|0;t1l=t1l+Wil|0;t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0;var t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh;hl=gl;gh=fh;gl=fl;fh=eh;fl=el;el=dl+t1l|0;eh=dh+t1h+getCarry(el,dl)|0;dh=ch;dl=cl;ch=bh;cl=bl;bh=ah;bl=al;al=t1l+t2l|0;ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._ah=this._ah+ah+getCarry(this._al,al)|0;this._bh=this._bh+bh+getCarry(this._bl,bl)|0;this._ch=this._ch+ch+getCarry(this._cl,cl)|0;this._dh=this._dh+dh+getCarry(this._dl,dl)|0;this._eh=this._eh+eh+getCarry(this._el,el)|0;this._fh=this._fh+fh+getCarry(this._fl,fl)|0;this._gh=this._gh+gh+getCarry(this._gl,gl)|0;this._hh=this._hh+hh+getCarry(this._hl,hl)|0};Sha512.prototype._hash=function(){var H=new Buffer(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);writeInt64BE(this._gh,this._gl,48);writeInt64BE(this._hh,this._hl,56);return H};module.exports=Sha512}).call(this,require("buffer").Buffer)},{"./hash":135,buffer:2,inherits:200}],143:[function(require,module,exports){(function(Buffer){"use strict";var createHash=require("create-hash/browser");var inherits=require("inherits");var Transform=require("stream").Transform;var ZEROS=new Buffer(128);ZEROS.fill(0);function Hmac(alg,key){Transform.call(this);alg=alg.toLowerCase();if(typeof key==="string"){key=new Buffer(key)}var blocksize=alg==="sha512"||alg==="sha384"?128:64;this._alg=alg;this._key=key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.lengthbits){num.ishrn(1)}if(num.isEven()){num.iadd(ONE)}if(!num.testn(1)){num.iadd(TWO)}if(!gen.cmp(TWO)){while(num.mod(TWENTYFOUR).cmp(ELEVEN)){num.iadd(FOUR)}}else if(!gen.cmp(FIVE)){while(num.mod(TEN).cmp(THREE)){num.iadd(FOUR)}}n2=num.shrn(1);if(simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num)){return num}}}},{"bn.js":148,"miller-rabin":149,randombytes:198}],147:[function(require,module,exports){module.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],148:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39}],149:[function(require,module,exports){var bn=require("bn.js");var brorand=require("brorand");function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin;MillerRabin.create=function create(rand){return new MillerRabin(rand)};MillerRabin.prototype._rand=function _rand(n){var len=n.bitLength();var buf=this.rand.generate(Math.ceil(len/8));buf[0]|=3;var mask=len&7;if(mask!==0)buf[buf.length-1]>>=7-mask;return new bn(buf)};MillerRabin.prototype.test=function test(n,k,cb){var len=n.bitLength();var red=bn.mont(n);var rone=new bn(1).toRed(red);if(!k)k=Math.max(1,len/48|0);var n1=n.subn(1);var n2=n1.subn(1);for(var s=0;!n1.testn(s);s++){}var d=n.shrn(s);var rn1=n1.toRed(red);var prime=true;for(;k>0;k--){var a=this._rand(n2);if(cb)cb(a);var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i0;k--){var a=this._rand(n2);var g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i=6?"utf-8":"binary"}exports.pbkdf2Sync=function(password,salt,iterations,keylen,digest){if(!Buffer.isBuffer(password))password=new Buffer(password,defaultEncoding);if(!Buffer.isBuffer(salt))salt=new Buffer(salt,defaultEncoding);checkParameters(iterations,keylen);digest=digest||"sha1";var hLen;var l=1;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);var r;var T;for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen}U.copy(T,0,0,hLen);for(var j=1;jMAX_ALLOC||keylen!==keylen){throw new TypeError("Bad key length")}}},{}],153:[function(require,module,exports){exports.publicEncrypt=require("./publicEncrypt");exports.privateDecrypt=require("./privateDecrypt");exports.privateEncrypt=function privateEncrypt(key,buf){return exports.publicEncrypt(key,buf,true)};exports.publicDecrypt=function publicDecrypt(key,buf){return exports.privateDecrypt(key,buf,true)}},{"./privateDecrypt":194,"./publicEncrypt":195}],154:[function(require,module,exports){(function(Buffer){var createHash=require("create-hash");module.exports=function(seed,len){var t=new Buffer("");var i=0,c;while(t.lengthk||new bn(enc).cmp(key.modulus)>=0){throw new Error("decryption error")}var msg;if(reverse){msg=withPublic(new bn(enc),key)}else{msg=crt(enc,key)}var zBuffer=new Buffer(k-msg.length);zBuffer.fill(0);msg=Buffer.concat([zBuffer,msg],k);if(padding===4){return oaep(key,msg)}else if(padding===1){return pkcs1(key,msg,reverse)}else if(padding===3){return msg}else{throw new Error("unknown padding")}};function oaep(key,msg){var n=key.modulus;var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(msg[0]!==0){throw new Error("decryption error")}var maskedSeed=msg.slice(1,hLen+1);var maskedDb=msg.slice(hLen+1);var seed=xor(maskedSeed,mgf(maskedDb,hLen));var db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen))){throw new Error("decryption error")}var i=hLen;while(db[i]===0){i++}if(db[i++]!==1){throw new Error("decryption error")}return db.slice(i)}function pkcs1(key,msg,reverse){var p1=msg.slice(0,2);var i=2;var status=0;while(msg[i++]!==0){if(i>=msg.length){status++;break}}var ps=msg.slice(2,i-1);var p2=msg.slice(i-1,i);if(p1.toString("hex")!=="0002"&&!reverse||p1.toString("hex")!=="0001"&&reverse){status++}if(ps.length<8){status++}if(status){throw new Error("decryption error")}return msg.slice(i)}function compare(a,b){a=new Buffer(a);b=new Buffer(b);var dif=0;var len=a.length;if(a.length!==b.length){dif++;len=Math.min(a.length,b.length)}var i=-1;while(++i=0){throw new Error("data too long for modulus")}}else{throw new Error("unknown padding")}if(reverse){return crt(paddedMsg,key)}else{return withPublic(paddedMsg,key)}};function oaep(key,msg){var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(mLen>k-hLen2-2){throw new Error("message too long")}var ps=new Buffer(k-mLen-hLen2-2);ps.fill(0);var dblen=k-hLen-1;var seed=randomBytes(hLen);var maskedDb=xor(Buffer.concat([iHash,ps,new Buffer([1]),msg],dblen),mgf(seed,dblen));var maskedSeed=xor(seed,mgf(maskedDb,hLen));return new bn(Buffer.concat([new Buffer([0]),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length;var k=key.modulus.byteLength();if(mLen>k-11){throw new Error("message too long")}var ps;if(reverse){ps=new Buffer(k-mLen-3);ps.fill(255)}else{ps=nonZero(k-mLen-3)}return new bn(Buffer.concat([new Buffer([0,reverse?1:2]),ps,new Buffer([0]),msg],k))}function nonZero(len,crypto){var out=new Buffer(len);var i=0;var cache=randomBytes(len*2);var cur=0;var num;while(i65536)throw new Error("requested too many random bytes");var rawBytes=new global.Uint8Array(size);if(size>0){crypto.getRandomValues(rawBytes)}var bytes=new Buffer(rawBytes.buffer);if(typeof cb==="function"){return process.nextTick(function(){cb(null,bytes)})}return bytes}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{_process:202,buffer:2}],199:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],200:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],201:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],202:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var _i=0;_i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}var Duplex;function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode; -if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function writableStateGetBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var Duplex;function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:2,"buffer-shims":210}],210:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:2}],211:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":201}],212:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],213:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:2}],221:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(obj){if(Object.keys)return Object.keys(obj);else{var res=[];for(var key in obj)res.push(key);return res}};var forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);else for(var i=0;i2&&arguments[2]!==undefined?arguments[2]:{length:12,counter:1};var salt=site+passwordOptions.counter.toString();var derivedHash=_crypto2.default.createHmac("sha256",encryptedLogin).update(salt).digest("hex");return derivedHash.substring(0,passwordOptions.length)}function _getPasswordTemplate(passwordTypes){var templates={lowercase:"vc",uppercase:"VC",numbers:"n",symbols:"s"};var template="";for(var templateKey in templates){if(passwordTypes.hasOwnProperty(templateKey)&&passwordTypes[templateKey]){template+=templates[templateKey]}}return template}function _prettyPrint(hash,template){var _this=this;var password="";this._string2charCodes(hash).forEach(function(charCode,index){var charType=_this._getCharType(template,index);password+=_this._getPasswordChar(charType,charCode)});return password}function _string2charCodes(text){var charCodes=[];for(var i=0;i { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + const iterations = 8192; + const keylen = 32; + crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) +} + +function _renderPassword(encryptedLogin, site, passwordOptions) { + const derivedEncryptedLogin = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); + const template = this._getPasswordTemplate(passwordOptions); + return this._prettyPrint(derivedEncryptedLogin, template); +} + +function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { + const salt = site + passwordOptions.counter.toString(); + const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); + return derivedHash.substring(0, passwordOptions.length); +} + +function _getPasswordTemplate(passwordTypes) { + const templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + let template = ''; + for (let templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] + } + } + return template; +} + +function _prettyPrint(hash, template) { + let password = ''; + + this._string2charCodes(hash).forEach((charCode, index) => { + const charType = this._getCharType(template, index); + password += this._getPasswordChar(charType, charCode); + }); + return password; +} + +function _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} diff --git a/package.json b/package.json index 8c5dcb7..8011fba 100644 --- a/package.json +++ b/package.json @@ -2,63 +2,41 @@ "name": "lesspass", "version": "4.0.0", "author": "Guillaume Vincent ", - "description": "lesspass javascript module to generate idempotent passwords", - "main": "lib/lesspass.js", + "description": "LessPass javascript module to generate idempotent passwords", + "main": "index", + "repository": "lesspass/core", + "homepage": "https://github.com/lesspass/core#readme", + "bugs": "https://github.com/lesspass/core/issues", "scripts": { + "test-node": "cd tests && babel-node --presets es2015 node.js && cd ..", "test": "ava --require babel-core/register", - "browserify": "browserify src/lesspass.js --standalone lesspass | uglifyjs > dist/lesspass.min.js", - "babelify": "babel src/lesspass.js -o lib/lesspass.js", - "build": "rm -rf dist lib && mkdir dist lib && npm run browserify && npm run babelify", - "prepublish": "npm test && npm run build" + "prepublish": "npm test" }, + "files": [ + "*.md", + "lib" + ], "keywords": [ "password", "crypto", "lesspass" ], - "repository": { - "type": "git", - "url": "git+ssh://git@github.com:lesspass/core.git" - }, - "engines": { - "node": ">=4.2.6" - }, "license": "MIT", - "bugs": { - "url": "https://github.com/lesspass/core/issues" - }, - "homepage": "https://github.com/lesspass/core#readme", "devDependencies": { - "ava": "^0.15.2", - "babel-cli": "^6.10.1", - "babel-core": "^6.10.4", - "babel-preset-es2015": "^6.9.0", - "babelify": "^7.3.0", - "browserify": "^13.0.1", - "karma": "^1.1.0", - "karma-ava": "0.0.1", - "karma-chrome-launcher": "^1.0.1", - "karma-firefox-launcher": "^1.0.0", - "uglify-js": "^2.6.4" + "ava": "^0.16.0", + "babel-cli": "^6.16.0", + "babel-core": "^6.17.0", + "babel-preset-es2015": "^6.16.0" }, "babel": { "presets": [ "es2015" ] }, - "browserify": { - "transform": [ - "babelify" - ] - }, "ava": { "files": [ "tests/*.js", - "!tests/karma.conf.js", "!tests/node.js" - ], - "source": [ - "src/*.js" ] } } diff --git a/readme.md b/readme.md index 2def304..60df20c 100644 --- a/readme.md +++ b/readme.md @@ -4,26 +4,22 @@ core library for LessPass password manager in javascript used to generate unique password. -It works with the browser and NodeJs - ## Requirements - - node 4.x.x + - node v4.6.x ## Install npm install lesspass ## Usage - -### Node - - var lesspass = require('lesspass'); - - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var site = 'lesspass.com'; - var options = { + + import LessPass from 'lesspass'; + + const site = 'lesspass.com'; + const login = 'contact@lesspass.com'; + const masterPassword = 'password'; + const options = { counter: 1, length: 12, lowercase: true, @@ -31,42 +27,11 @@ It works with the browser and NodeJs numbers: true, symbols: true }; - lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { - var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); - console.log(generatedPassword); //azYS7,olOL2] - }); - - - -### Browser - - - - - - - - - - - see [tests/api.tests.js](tests/api.tests.js) for more examples diff --git a/src/lesspass.js b/src/lesspass.js deleted file mode 100644 index da82a42..0000000 --- a/src/lesspass.js +++ /dev/null @@ -1,95 +0,0 @@ -import crypto from 'crypto'; - -module.exports = { - encryptLogin: _encryptLogin, - renderPassword: _renderPassword, - _deriveEncryptedLogin, - _getPasswordTemplate, - _prettyPrint, - _string2charCodes, - _getCharType, - _getPasswordChar, -}; - -function _encryptLogin(login, masterPassword) { - return new Promise((resolve, reject) => { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); - } - const iterations = 8192; - const keylen = 32; - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }) -} - -function _renderPassword(encryptedLogin, site, passwordOptions) { - const derivedEncryptedLogin = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); - const template = this._getPasswordTemplate(passwordOptions); - return this._prettyPrint(derivedEncryptedLogin, template); -} - -function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { - const salt = site + passwordOptions.counter.toString(); - const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); - return derivedHash.substring(0, passwordOptions.length); -} - -function _getPasswordTemplate(passwordTypes) { - const templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - let template = ''; - for (let templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] - } - } - return template; -} - -function _prettyPrint(hash, template) { - let password = ''; - - this._string2charCodes(hash).forEach((charCode, index) => { - const charType = this._getCharType(template, index); - password += this._getPasswordChar(charType, charCode); - }); - return password; -} - -function _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} - -function _getCharType(template, index) { - return template[index % template.length]; -} - -function _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; -} diff --git a/tests/api.tests.js b/tests/api.tests.js index 9e712ff..654724d 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass'; +import lesspass from '../index'; test('encrypt login with pbkdf2 8192 iterations and sha256', t => { return lesspass.encryptLogin('test@example.org', 'password').then(encryptedLogin => { diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js index b851206..79ad944 100644 --- a/tests/deriveEncryptedLogin.tests.js +++ b/tests/deriveEncryptedLogin.tests.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass'; +import lesspass from '../index'; test('should derive encrypted login with default length', t => { const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; diff --git a/tests/getPasswordTemplate.tests.js b/tests/getPasswordTemplate.tests.js index 2946429..5efca0a 100644 --- a/tests/getPasswordTemplate.tests.js +++ b/tests/getPasswordTemplate.tests.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass'; +import lesspass from '../index'; test('should get default template', t => { t.is('vcVCns', lesspass._getPasswordTemplate({ diff --git a/tests/index.html b/tests/index.html deleted file mode 100644 index 8ef6471..0000000 --- a/tests/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - diff --git a/tests/node.js b/tests/node.js index 59c0803..5263f7a 100644 --- a/tests/node.js +++ b/tests/node.js @@ -1,10 +1,10 @@ -var lesspass = require('../lib/lesspass'); -var assert = require('assert'); +import lesspass from '../index'; +import assert from 'assert'; -var site = 'lesspass.com'; -var login = 'contact@lesspass.com'; -var masterPassword = 'password'; -var options = { +const site = 'lesspass.com'; +const login = 'contact@lesspass.com'; +const masterPassword = 'password'; +const options = { counter: 1, length: 12, lowercase: true, @@ -12,9 +12,12 @@ var options = { numbers: true, symbols: true }; -lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { - var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); - assert.equal(generatedPassword, 'azYS7,olOL2]'); -}).catch(function (err) { - console.log(err); -}); +lesspass.encryptLogin(login, masterPassword) + .then(encryptedLogin => { + var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); + assert.equal(generatedPassword, 'azYS7,olOL2]'); + console.log('test node ES6 ok'); + }) + .catch(err => { + console.log(err); + }); diff --git a/tests/prettyPrint.js b/tests/prettyPrint.js index 94e56cf..7a6c073 100644 --- a/tests/prettyPrint.js +++ b/tests/prettyPrint.js @@ -1,5 +1,5 @@ import test from 'ava'; -import lesspass from '../src/lesspass'; +import lesspass from '../index'; test('should print different password if templates different', t => { const encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; From 830b50e423ae0c0ead09607ef9221ae7034822c3 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 15:43:26 +0200 Subject: [PATCH 039/124] 4.0.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8011fba..f446c18 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "4.0.0", + "version": "4.0.1", "author": "Guillaume Vincent ", "description": "LessPass javascript module to generate idempotent passwords", "main": "index", From 32a3dee1cbae4feaddb13ea11b4df9e2a778c323 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 18:45:08 +0200 Subject: [PATCH 040/124] fix missing files --- package.json | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/package.json b/package.json index f446c18..836d9d4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "4.0.1", + "version": "4.0.2", "author": "Guillaume Vincent ", "description": "LessPass javascript module to generate idempotent passwords", "main": "index", @@ -12,10 +12,6 @@ "test": "ava --require babel-core/register", "prepublish": "npm test" }, - "files": [ - "*.md", - "lib" - ], "keywords": [ "password", "crypto", From 1adf7cb942c6c055a0ebb6261c18147933031ce5 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 18:56:11 +0200 Subject: [PATCH 041/124] fix import error --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index 9848ac1..da82a42 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,6 @@ import crypto from 'crypto'; -export default { +module.exports = { encryptLogin: _encryptLogin, renderPassword: _renderPassword, _deriveEncryptedLogin, From 91b81292cb4c3a2b850da2b14ce70d29e4d9549e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 18:56:18 +0200 Subject: [PATCH 042/124] 4.0.3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 836d9d4..8a7a177 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "4.0.2", + "version": "4.0.3", "author": "Guillaume Vincent ", "description": "LessPass javascript module to generate idempotent passwords", "main": "index", From 345b6f58a560f0f1342499e882d6528002822159 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 19:05:17 +0200 Subject: [PATCH 043/124] babel ES6 code --- package.json | 9 ++++++--- tests/node.js | 26 +++++++++++--------------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index 8a7a177..e9cd42e 100644 --- a/package.json +++ b/package.json @@ -3,14 +3,16 @@ "version": "4.0.3", "author": "Guillaume Vincent ", "description": "LessPass javascript module to generate idempotent passwords", - "main": "index", + "main": "lib/index.js", + "jsnext:main": "index.js", "repository": "lesspass/core", "homepage": "https://github.com/lesspass/core#readme", "bugs": "https://github.com/lesspass/core/issues", "scripts": { "test-node": "cd tests && babel-node --presets es2015 node.js && cd ..", "test": "ava --require babel-core/register", - "prepublish": "npm test" + "build": "rimraf lib && babel index.js -d lib", + "prepublish": "npm test && npm run build" }, "keywords": [ "password", @@ -22,7 +24,8 @@ "ava": "^0.16.0", "babel-cli": "^6.16.0", "babel-core": "^6.17.0", - "babel-preset-es2015": "^6.16.0" + "babel-preset-es2015": "^6.16.0", + "rimraf": "^2.5.4" }, "babel": { "presets": [ diff --git a/tests/node.js b/tests/node.js index 5263f7a..73504e0 100644 --- a/tests/node.js +++ b/tests/node.js @@ -1,10 +1,10 @@ -import lesspass from '../index'; -import assert from 'assert'; +var lesspass = require('../lib/index'); +var assert = require('assert'); -const site = 'lesspass.com'; -const login = 'contact@lesspass.com'; -const masterPassword = 'password'; -const options = { +var site = 'lesspass.com'; +var login = 'contact@lesspass.com'; +var masterPassword = 'password'; +var options = { counter: 1, length: 12, lowercase: true, @@ -12,12 +12,8 @@ const options = { numbers: true, symbols: true }; -lesspass.encryptLogin(login, masterPassword) - .then(encryptedLogin => { - var generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); - assert.equal(generatedPassword, 'azYS7,olOL2]'); - console.log('test node ES6 ok'); - }) - .catch(err => { - console.log(err); - }); + +lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { + var generatedPassword = lesspass.deriveEncryptedLogin(encryptedLogin, site, options); + assert(generatedPassword, 'azYS7,olOL2]'); +}); From f6ecb66b2306e19ee19af3696370749363abc52f Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 7 Oct 2016 19:06:47 +0200 Subject: [PATCH 044/124] 4.0.4 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e9cd42e..bc17313 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "4.0.3", + "version": "4.0.4", "author": "Guillaume Vincent ", "description": "LessPass javascript module to generate idempotent passwords", "main": "lib/index.js", From 8f4a6855d1b408b4bee3bbb77097c193802f54c1 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 20 Oct 2016 11:20:36 +0200 Subject: [PATCH 045/124] add license in readme --- readme.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 60df20c..d0a5b74 100644 --- a/readme.md +++ b/readme.md @@ -41,4 +41,9 @@ see [tests/api.tests.js](tests/api.tests.js) for more examples npm test -see [LessPass](https://github.com/lesspass/lesspass) project +## License + +MIT © [Guillaume Vincent](http://guillaumevincent.com) + + +## [LessPass project](https://github.com/lesspass/lesspass) From 619ee9292785e6d9821cae07ebdea70cee1554f0 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 20 Oct 2016 14:00:22 +0200 Subject: [PATCH 046/124] update ISSUE_TEMPLATE file --- ISSUE_TEMPLATE | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ISSUE_TEMPLATE b/ISSUE_TEMPLATE index 6b2ed8e..f6acdd8 100644 --- a/ISSUE_TEMPLATE +++ b/ISSUE_TEMPLATE @@ -1,3 +1,5 @@ + + **Thank you for taking your time to fill out an issue.** To make it easier to manage, can you put this issue in LessPass super project ? From f6668eb45dc0256da559b5c21311ec0da713cf9a Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 20 Oct 2016 14:01:34 +0200 Subject: [PATCH 047/124] fix error in node test --- tests/node.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/node.js b/tests/node.js index 73504e0..e5b15a1 100644 --- a/tests/node.js +++ b/tests/node.js @@ -13,7 +13,13 @@ var options = { symbols: true }; -lesspass.encryptLogin(login, masterPassword).then(function (encryptedLogin) { - var generatedPassword = lesspass.deriveEncryptedLogin(encryptedLogin, site, options); - assert(generatedPassword, 'azYS7,olOL2]'); -}); +var generatedPassword; +lesspass.encryptLogin(login, masterPassword) + .then(function (encryptedLogin) { + generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); + assert.equal(generatedPassword, 'azYS7,olOL2]'); + console.log('generated password ok'); + }) + .catch(e => { + console.log(e); + }); From 902f158366127b6be0f3edf697c2fde973ce5244 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 20 Oct 2016 16:23:39 +0200 Subject: [PATCH 048/124] update readme --- readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/readme.md b/readme.md index d0a5b74..93c270a 100644 --- a/readme.md +++ b/readme.md @@ -1,8 +1,6 @@ [![Build Status](https://travis-ci.org/lesspass/core.svg?branch=master)](https://travis-ci.org/lesspass/core) -# LessPass Core - -core library for LessPass password manager in javascript used to generate unique password. +> core library for LessPass password manager in javascript used to generate unique password. ## Requirements From f7548f4974487ea672eb22383cd651ff53e81d25 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 25 Oct 2016 17:43:08 +0200 Subject: [PATCH 049/124] upgrade to node 6 LTS --- .gitignore | 4 +- .npmignore | 2 - .travis.yml | 2 +- index.js | 25 +++++++---- package.json | 12 +++--- readme.md | 23 +++++----- tests/api.tests.js | 86 +++++++++++++++++++------------------ tests/deriveEncryptedLogin.tests.js | 54 ++++++++++++----------- tests/node.js | 16 +++---- 9 files changed, 121 insertions(+), 103 deletions(-) delete mode 100644 .npmignore diff --git a/.gitignore b/.gitignore index a9f4ed5..1ca9571 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -lib -node_modules \ No newline at end of file +node_modules/ +npm-debug.log diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 6bd575e..0000000 --- a/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -.travis.yml -tests \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 92a1e92..10d8531 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,3 @@ language: node_js node_js: - - 4 \ No newline at end of file + - 6 \ No newline at end of file diff --git a/index.js b/index.js index da82a42..bdfe301 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ module.exports = { _string2charCodes, _getCharType, _getPasswordChar, + _createHmac }; function _encryptLogin(login, masterPassword) { @@ -29,15 +30,23 @@ function _encryptLogin(login, masterPassword) { } function _renderPassword(encryptedLogin, site, passwordOptions) { - const derivedEncryptedLogin = this._deriveEncryptedLogin(encryptedLogin, site, passwordOptions); - const template = this._getPasswordTemplate(passwordOptions); - return this._prettyPrint(derivedEncryptedLogin, template); + return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + const template = _getPasswordTemplate(passwordOptions); + return _prettyPrint(derivedEncryptedLogin, template); + }); +} + +function _createHmac(encryptedLogin, salt) { + return new Promise(resolve => { + resolve(crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex')); + }); } function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { const salt = site + passwordOptions.counter.toString(); - const derivedHash = crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex'); - return derivedHash.substring(0, passwordOptions.length); + return _createHmac(encryptedLogin, salt).then(derivedHash => { + return derivedHash.substring(0, passwordOptions.length); + }); } function _getPasswordTemplate(passwordTypes) { @@ -59,9 +68,9 @@ function _getPasswordTemplate(passwordTypes) { function _prettyPrint(hash, template) { let password = ''; - this._string2charCodes(hash).forEach((charCode, index) => { - const charType = this._getCharType(template, index); - password += this._getPasswordChar(charType, charCode); + _string2charCodes(hash).forEach((charCode, index) => { + const charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); }); return password; } diff --git a/package.json b/package.json index bc17313..aba9245 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,21 @@ { "name": "lesspass", - "version": "4.0.4", + "version": "5.0.0", "author": "Guillaume Vincent ", - "description": "LessPass javascript module to generate idempotent passwords", + "description": "LessPass node module used to generate LessPass passwords", "main": "lib/index.js", "jsnext:main": "index.js", "repository": "lesspass/core", - "homepage": "https://github.com/lesspass/core#readme", - "bugs": "https://github.com/lesspass/core/issues", "scripts": { - "test-node": "cd tests && babel-node --presets es2015 node.js && cd ..", + "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd ..", "test": "ava --require babel-core/register", "build": "rimraf lib && babel index.js -d lib", "prepublish": "npm test && npm run build" }, + "files": [ + "lib/", + "index.js" + ], "keywords": [ "password", "crypto", diff --git a/readme.md b/readme.md index 93c270a..aab81fd 100644 --- a/readme.md +++ b/readme.md @@ -4,7 +4,7 @@ ## Requirements - - node v4.6.x + - node LTS v6 ## Install @@ -12,12 +12,12 @@ ## Usage - import LessPass from 'lesspass'; - - const site = 'lesspass.com'; - const login = 'contact@lesspass.com'; - const masterPassword = 'password'; - const options = { + var LessPass = require('lesspass'); + + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var options = { counter: 1, length: 12, lowercase: true, @@ -25,11 +25,12 @@ numbers: true, symbols: true }; - LessPass.encryptLogin(login, masterPassword) - .then(encryptedLogin => { - var generatedPassword = LessPass.renderPassword(encryptedLogin, site, options); - console.log(generatedPassword); //azYS7,olOL2] + + LessPass.encryptLogin(login, masterPassword).then(encryptedLogin => { + LessPass.renderPassword(encryptedLogin, site, options).then(generatedPassword => { + console.log(generatedPassword); //azYS7,olOL2] }); + }); see [tests/api.tests.js](tests/api.tests.js) for more examples diff --git a/tests/api.tests.js b/tests/api.tests.js index 654724d..d753b81 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -1,36 +1,20 @@ import test from 'ava'; import lesspass from '../index'; -test('encrypt login with pbkdf2 8192 iterations and sha256', t => { - return lesspass.encryptLogin('test@example.org', 'password').then(encryptedLogin => { +test('should use pbkdf2 with 8192 iterations and sha256', t=> { + lesspass.encryptLogin('test@example.org', 'password').then(function (encryptedLogin) { t.is('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); - }) -}); - -test('encrypt login with utf8 parameter', t => { - return lesspass.encryptLogin('test@example.org', '♥ LessPass ♥').then(encryptedLogin => { - t.is('063092c809334979f505df88ed37845d298c01f7e8a03cbd661edbc084c650ca', encryptedLogin); - }) + }); }); -test('render password', t => { - const site = 'lesspass.com'; - const encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - const passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - t.is('azYS7,olOL2]', lesspass.renderPassword(encryptedLogin, site, passwordOptions)); +test('should allow utf8 parameter', t=> { + lesspass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { + t.is('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); + }); }); - - test('auto generated encrypt login tests', t => { - const promises = []; - const passwords = [ + var promises = []; + var passwords = [ { login: 'contact@lesspass.com', masterPassword: 'password', @@ -88,20 +72,34 @@ test('auto generated encrypt login tests', t => { } ]; - for (const entry of passwords) { + for (var entry of passwords) { promises.push(lesspass.encryptLogin(entry.login, entry.masterPassword)); } - t.plan(passwords.length); return Promise.all(promises).then(values => { for (let i = 0; i < values.length; i++) { t.is(passwords[i].encryptedLogin, values[i]); } }); }); - -test('auto generated derive encrypted login tests', t => { - const passwords = [ +test('render password', t => { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + lesspass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + t.is('azYS7,olOL2]', generatedPassword); + }) +}); +test('auto generated render password tests', t => { + var promises = []; + var passwords = [ { encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', site: 'lesspass.com', @@ -225,18 +223,22 @@ test('auto generated derive encrypted login tests', t => { } ]; - - t.plan(passwords.length); - for (let i = 0; i < passwords.length; i++) { - let password = passwords[i]; - let passwordOption = { - counter: password.counter, - length: password.length, - lowercase: password.lowercase, - uppercase: password.uppercase, - numbers: password.numbers, - symbols: password.symbols, + for (var entry of passwords) { + var passwordOption = { + counter: entry.counter, + length: entry.length, + lowercase: entry.lowercase, + uppercase: entry.uppercase, + numbers: entry.numbers, + symbols: entry.symbols, }; - t.is(password.generatedPassword, lesspass.renderPassword(password.encryptedLogin, password.site, passwordOption)); + promises.push(lesspass.renderPassword(entry.encryptedLogin, entry.site, passwordOption)); } + + return Promise.all(promises).then(values => { + for (let i = 0; i < values.length; i++) { + t.is(passwords[i].generatedPassword, values[i]); + } + }); }); + diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js index 79ad944..002954c 100644 --- a/tests/deriveEncryptedLogin.tests.js +++ b/tests/deriveEncryptedLogin.tests.js @@ -1,12 +1,13 @@ import test from 'ava'; import lesspass from '../index'; -test('should derive encrypted login with default length', t => { - const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - t.is(12, lesspass._deriveEncryptedLogin(encryptedLogin, site).length); +test('should createHmac', t => { + var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + var salt = 'lesspass.com1'; + return lesspass._createHmac(encryptedLogin, salt).then(hmac => { + t.is('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); + }); }); - test('should derive encrypted login with default options', t => { const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; const site = 'lesspass.com'; @@ -18,30 +19,32 @@ test('should derive encrypted login with default options', t => { numbers: true, symbols: true, }; - t.is( - lesspass._deriveEncryptedLogin(encryptedLogin, site), - lesspass._deriveEncryptedLogin(encryptedLogin, site, option) - ); + var p1 = lesspass._deriveEncryptedLogin(encryptedLogin, site); + var p2 = lesspass._deriveEncryptedLogin(encryptedLogin, site, option); + Promise.all([p1, p2]).then(generatedPasswords => { + t.is(generatedPasswords[0], generatedPasswords[1]) + }); }); - test('should derive encrypted login with defined length', t => { - const encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - const site = 'lesspass.com'; - const option = { + var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; + var site = 'lesspass.com'; + var option = { counter: 1, length: 10, }; - t.is(10, lesspass._deriveEncryptedLogin(encryptedLogin, site, option).length); + return lesspass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { + t.is(10, generatedPassword.length); + }) }); - test('should return two different passwords if site different', t => { const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; const site = 'google.com'; const site2 = 'facebook.com'; - t.not( - lesspass._deriveEncryptedLogin(encryptedLogin, site), - lesspass._deriveEncryptedLogin(encryptedLogin, site2) - ); + var p1 = lesspass._deriveEncryptedLogin(encryptedLogin, site); + var p2 = lesspass._deriveEncryptedLogin(encryptedLogin, site2); + Promise.all([p1, p2]).then(derivedEncryptedLogins => { + t.not(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) + }); }); test('should return two different passwords if counter different', t => { @@ -49,14 +52,17 @@ test('should return two different passwords if counter different', t => { const site = 'lesspass.com'; const option = {counter: 1}; const option2 = {counter: 2}; - t.not( - lesspass._deriveEncryptedLogin(encryptedLogin, site, option), - lesspass._deriveEncryptedLogin(encryptedLogin, site, option2) - ); + var p1 = lesspass._deriveEncryptedLogin(encryptedLogin, site, option); + var p2 = lesspass._deriveEncryptedLogin(encryptedLogin, site, option2); + Promise.all([p1, p2]).then(derivedEncryptedLogins => { + t.not(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) + }); }); test('should derive encrypted login with sha 256', t => { const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; const site = 'lesspass.com'; - t.is('be00f942fc8a', lesspass._deriveEncryptedLogin(encryptedLogin, site)); + return lesspass._deriveEncryptedLogin(encryptedLogin, site).then(function (encryptedLogin) { + t.is('be00f942fc8a', encryptedLogin); + }); }); diff --git a/tests/node.js b/tests/node.js index e5b15a1..a148b28 100644 --- a/tests/node.js +++ b/tests/node.js @@ -1,4 +1,4 @@ -var lesspass = require('../lib/index'); +var LessPass = require('../lib/index'); var assert = require('assert'); var site = 'lesspass.com'; @@ -13,13 +13,13 @@ var options = { symbols: true }; -var generatedPassword; -lesspass.encryptLogin(login, masterPassword) - .then(function (encryptedLogin) { - generatedPassword = lesspass.renderPassword(encryptedLogin, site, options); - assert.equal(generatedPassword, 'azYS7,olOL2]'); - console.log('generated password ok'); +LessPass.encryptLogin(login, masterPassword) + .then(encryptedLogin => { + LessPass.renderPassword(encryptedLogin, site, options).then(generatedPassword => { + assert.equal(generatedPassword, 'azYS7,olOL2]'); + console.log('generated password ok'); + }); }) .catch(e => { console.log(e); - }); + }); \ No newline at end of file From c56ee5f12db09eb274754f1b3dbab5adf36d7e47 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 25 Oct 2016 17:44:58 +0200 Subject: [PATCH 050/124] add lib --- lib/index.js | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 lib/index.js diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..3091b0b --- /dev/null +++ b/lib/index.js @@ -0,0 +1,112 @@ +'use strict'; + +var _crypto = require('crypto'); + +var _crypto2 = _interopRequireDefault(_crypto); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = { + encryptLogin: _encryptLogin, + renderPassword: _renderPassword, + _deriveEncryptedLogin: _deriveEncryptedLogin, + _getPasswordTemplate: _getPasswordTemplate, + _prettyPrint: _prettyPrint, + _string2charCodes: _string2charCodes, + _getCharType: _getCharType, + _getPasswordChar: _getPasswordChar, + _createHmac: _createHmac +}; + +function _encryptLogin(login, masterPassword) { + return new Promise(function (resolve, reject) { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + var iterations = 8192; + var keylen = 32; + _crypto2.default.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); +} + +function _renderPassword(encryptedLogin, site, passwordOptions) { + return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = _getPasswordTemplate(passwordOptions); + return _prettyPrint(derivedEncryptedLogin, template); + }); +} + +function _createHmac(encryptedLogin, salt) { + return new Promise(function (resolve) { + resolve(_crypto2.default.createHmac('sha256', encryptedLogin).update(salt).digest('hex')); + }); +} + +function _deriveEncryptedLogin(encryptedLogin, site) { + var passwordOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { length: 12, counter: 1 }; + + var salt = site + passwordOptions.counter.toString(); + return _createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, passwordOptions.length); + }); +} + +function _getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's' + }; + var template = ''; + for (var templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey]; + } + } + return template; +} + +function _prettyPrint(hash, template) { + var password = ''; + + _string2charCodes(hash).forEach(function (charCode, index) { + var charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; +} + +function _string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} \ No newline at end of file From 6a849f2e5f6f420e1d27b11fd9c8468b2a2aa2e5 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 25 Oct 2016 17:45:04 +0200 Subject: [PATCH 051/124] 5.0.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index aba9245..e73bd59 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.0.0", + "version": "5.0.1", "author": "Guillaume Vincent ", "description": "LessPass node module used to generate LessPass passwords", "main": "lib/index.js", From c5145fd9ba0f7a6c4f020529bfb3bf51de46cbbc Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 25 Oct 2016 17:53:04 +0200 Subject: [PATCH 052/124] update readme --- readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index aab81fd..87dba3a 100644 --- a/readme.md +++ b/readme.md @@ -45,4 +45,6 @@ see [tests/api.tests.js](tests/api.tests.js) for more examples MIT © [Guillaume Vincent](http://guillaumevincent.com) -## [LessPass project](https://github.com/lesspass/lesspass) +## Issues + +report issues on [LessPass project](https://github.com/lesspass/lesspass/issues) From fbeed733fe1b0a86249ea2af25337a5b6e00b431 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 27 Oct 2016 08:54:10 +0200 Subject: [PATCH 053/124] add createFingerprint interface --- index.js | 7 +++++++ tests/api.tests.js | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/index.js b/index.js index bdfe301..98533ca 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ import crypto from 'crypto'; module.exports = { encryptLogin: _encryptLogin, renderPassword: _renderPassword, + createFingerprint: createFingerprint, _deriveEncryptedLogin, _getPasswordTemplate, _prettyPrint, @@ -102,3 +103,9 @@ function _getPasswordChar(charType, index) { const passwordChar = passwordsChars[charType]; return passwordChar[index % passwordChar.length]; } + +function createFingerprint(str) { + return new Promise(resolve => { + resolve(crypto.createHmac('sha256', str).digest('hex')) + }); +} \ No newline at end of file diff --git a/tests/api.tests.js b/tests/api.tests.js index d753b81..435558d 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -242,3 +242,10 @@ test('auto generated render password tests', t => { }); }); + +test('createFingerprint', t => { + return lesspass.createFingerprint('password').then(fingerprint => { + t.is('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); + }); +}); + From 70be70097454c15712cc9d36c3d84e65094d2ae1 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 27 Oct 2016 08:54:27 +0200 Subject: [PATCH 054/124] 5.1.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e73bd59..0ce9845 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.0.1", + "version": "5.1.0", "author": "Guillaume Vincent ", "description": "LessPass node module used to generate LessPass passwords", "main": "lib/index.js", From 04909008254fb775e03a3ed10499756d25504886 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 27 Oct 2016 18:15:13 +0200 Subject: [PATCH 055/124] update build --- lib/index.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/index.js b/lib/index.js index 3091b0b..cfdaec2 100644 --- a/lib/index.js +++ b/lib/index.js @@ -9,6 +9,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de module.exports = { encryptLogin: _encryptLogin, renderPassword: _renderPassword, + createFingerprint: createFingerprint, _deriveEncryptedLogin: _deriveEncryptedLogin, _getPasswordTemplate: _getPasswordTemplate, _prettyPrint: _prettyPrint, @@ -109,4 +110,10 @@ function _getPasswordChar(charType, index) { }; var passwordChar = passwordsChars[charType]; return passwordChar[index % passwordChar.length]; +} + +function createFingerprint(str) { + return new Promise(function (resolve) { + resolve(_crypto2.default.createHmac('sha256', str).digest('hex')); + }); } \ No newline at end of file From 449813d5424b9910ee549a62cc085cb206e38d16 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 27 Oct 2016 18:15:30 +0200 Subject: [PATCH 056/124] 5.1.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0ce9845..123f9b3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.1.0", + "version": "5.1.1", "author": "Guillaume Vincent ", "description": "LessPass node module used to generate LessPass passwords", "main": "lib/index.js", From 582322ecebf12bfd1887b39232cc0b6a67f925d8 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sat, 29 Oct 2016 19:00:31 +0200 Subject: [PATCH 057/124] change license from MIT to GNU GPLv3 --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ license | 21 -- readme.md | 2 +- 3 files changed, 675 insertions(+), 22 deletions(-) create mode 100644 LICENSE delete mode 100644 license diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/license b/license deleted file mode 100644 index 6a8501b..0000000 --- a/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Guillaume Vincent (guillaumevincent.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/readme.md b/readme.md index 87dba3a..0329418 100644 --- a/readme.md +++ b/readme.md @@ -42,7 +42,7 @@ see [tests/api.tests.js](tests/api.tests.js) for more examples ## License -MIT © [Guillaume Vincent](http://guillaumevincent.com) +This project is licensed under the terms of the GNU GPLv3. ## Issues From 4dd321fdcba14e1bb8086405aed429cffb8325c3 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 4 Nov 2016 17:10:40 +0100 Subject: [PATCH 058/124] remove ava to use same test suite with webcrypto --- package.json | 13 +- tests/api.tests.js | 488 +++++++++++++++++++----------------- tests/deriveEncryptedLogin.tests.js | 132 +++++----- tests/getPasswordTemplate.tests.js | 112 +++++---- tests/helper.js | 3 + tests/prettyPrint.js | 68 +++-- 6 files changed, 419 insertions(+), 397 deletions(-) create mode 100644 tests/helper.js diff --git a/package.json b/package.json index 123f9b3..0d47823 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,9 @@ "repository": "lesspass/core", "scripts": { "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd ..", - "test": "ava --require babel-core/register", + "test": "mocha --compilers js:babel-register --require ./tests/helper.js tests", "build": "rimraf lib && babel index.js -d lib", - "prepublish": "npm test && npm run build" + "prepublish": "npm test && npm run build && npm run test:node" }, "files": [ "lib/", @@ -23,21 +23,16 @@ ], "license": "MIT", "devDependencies": { - "ava": "^0.16.0", "babel-cli": "^6.16.0", "babel-core": "^6.17.0", "babel-preset-es2015": "^6.16.0", + "chai": "^3.5.0", + "mocha": "^3.1.2", "rimraf": "^2.5.4" }, "babel": { "presets": [ "es2015" ] - }, - "ava": { - "files": [ - "tests/*.js", - "!tests/node.js" - ] } } diff --git a/tests/api.tests.js b/tests/api.tests.js index 435558d..361cf70 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -1,251 +1,265 @@ -import test from 'ava'; -import lesspass from '../index'; +var assert = chai.assert; -test('should use pbkdf2 with 8192 iterations and sha256', t=> { - lesspass.encryptLogin('test@example.org', 'password').then(function (encryptedLogin) { - t.is('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); - }); -}); +describe('LessPass', function () { + describe('encryptLogin', function () { + it('should use pbkdf2 with 8192 iterations and sha256', function (done) { + LessPass.encryptLogin('test@example.org', 'password').then(function (encryptedLogin) { + assert.equal('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); + done(); + }); + }); -test('should allow utf8 parameter', t=> { - lesspass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { - t.is('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); - }); -}); -test('auto generated encrypt login tests', t => { - var promises = []; - var passwords = [ - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'lesspass', - masterPassword: 'password', - encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password2', - encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', - } - ]; + it('should allow utf8 parameter', function (done) { + LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { + assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); + done(); + }); + }); + it('auto generated encrypt login tests', function () { + var promises = []; + var passwords = [ + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'lesspass', + masterPassword: 'password', + encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password2', + encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', + } + ]; - for (var entry of passwords) { - promises.push(lesspass.encryptLogin(entry.login, entry.masterPassword)); - } + for (var entry of passwords) { + promises.push(LessPass.encryptLogin(entry.login, entry.masterPassword)); + } - return Promise.all(promises).then(values => { - for (let i = 0; i < values.length; i++) { - t.is(passwords[i].encryptedLogin, values[i]); - } + return Promise.all(promises).then(values => { + for (let i = 0; i < values.length; i++) { + assert.equal(passwords[i].encryptedLogin, values[i]); + } + }); + }); }); }); -test('render password', t => { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - lesspass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - t.is('azYS7,olOL2]', generatedPassword); - }) -}); -test('auto generated render password tests', t => { - var promises = []; - var passwords = [ - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'azYS7,olOL2]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 14, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'azYS7,olOL2]iz' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: false, - numbers: false, - symbols: false, - generatedPassword: 'azyseqololat' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: false, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'AZ3[EQ7@OL2]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: true, - symbols: true, - generatedPassword: '4?3[7,7@7@2]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: false, - symbols: true, - generatedPassword: '[?=[&,:@:@[]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: false, - generatedPassword: 'azYS7uwAW8at' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: false, - symbols: false, - generatedPassword: 'azYSeqOLolAT' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 2, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'obYT2=olOV9=' - }, - { - encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'erOC1%imIW3,' - }, - { - encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'uvUM5_ucUP5=' - } - ]; - for (var entry of passwords) { - var passwordOption = { - counter: entry.counter, - length: entry.length, - lowercase: entry.lowercase, - uppercase: entry.uppercase, - numbers: entry.numbers, - symbols: entry.symbols, - }; - promises.push(lesspass.renderPassword(entry.encryptedLogin, entry.site, passwordOption)); - } +describe('LessPass', function () { + describe('renderPassword', function () { + it('render password', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + assert.equal('azYS7,olOL2]', generatedPassword); + }) + }); + it('auto generated render password tests', function () { + var promises = []; + var passwords = [ + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'azYS7,olOL2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 14, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'azYS7,olOL2]iz' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: false, + numbers: false, + symbols: false, + generatedPassword: 'azyseqololat' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'AZ3[EQ7@OL2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: true, + symbols: true, + generatedPassword: '4?3[7,7@7@2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: false, + symbols: true, + generatedPassword: '[?=[&,:@:@[]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + generatedPassword: 'azYS7uwAW8at' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: false, + symbols: false, + generatedPassword: 'azYSeqOLolAT' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 2, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'obYT2=olOV9=' + }, + { + encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'erOC1%imIW3,' + }, + { + encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'uvUM5_ucUP5=' + } + ]; + + for (var entry of passwords) { + var passwordOption = { + counter: entry.counter, + length: entry.length, + lowercase: entry.lowercase, + uppercase: entry.uppercase, + numbers: entry.numbers, + symbols: entry.symbols, + }; + promises.push(LessPass.renderPassword(entry.encryptedLogin, entry.site, passwordOption)); + } - return Promise.all(promises).then(values => { - for (let i = 0; i < values.length; i++) { - t.is(passwords[i].generatedPassword, values[i]); - } + return Promise.all(promises).then(values => { + for (let i = 0; i < values.length; i++) { + assert.equal(passwords[i].generatedPassword, values[i]); + } + }); + }); }); }); - -test('createFingerprint', t => { - return lesspass.createFingerprint('password').then(fingerprint => { - t.is('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); +describe('LessPass', function () { + describe('fingerprint', function () { + it('createFingerprint', function (done) { + LessPass.createFingerprint('password').then(function (fingerprint) { + assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); + done(); + }) + }); }); }); diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js index 002954c..24c8793 100644 --- a/tests/deriveEncryptedLogin.tests.js +++ b/tests/deriveEncryptedLogin.tests.js @@ -1,68 +1,72 @@ -import test from 'ava'; -import lesspass from '../index'; +var assert = chai.assert; -test('should createHmac', t => { - var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - var salt = 'lesspass.com1'; - return lesspass._createHmac(encryptedLogin, salt).then(hmac => { - t.is('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); - }); -}); -test('should derive encrypted login with default options', t => { - const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - const option = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - }; - var p1 = lesspass._deriveEncryptedLogin(encryptedLogin, site); - var p2 = lesspass._deriveEncryptedLogin(encryptedLogin, site, option); - Promise.all([p1, p2]).then(generatedPasswords => { - t.is(generatedPasswords[0], generatedPasswords[1]) - }); -}); -test('should derive encrypted login with defined length', t => { - var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - var site = 'lesspass.com'; - var option = { - counter: 1, - length: 10, - }; - return lesspass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { - t.is(10, generatedPassword.length); - }) -}); -test('should return two different passwords if site different', t => { - const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'google.com'; - const site2 = 'facebook.com'; - var p1 = lesspass._deriveEncryptedLogin(encryptedLogin, site); - var p2 = lesspass._deriveEncryptedLogin(encryptedLogin, site2); - Promise.all([p1, p2]).then(derivedEncryptedLogins => { - t.not(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) +describe('LessPass', function () { + describe('deriveEncryptedLogin', function () { + it('should createHmac', function (done) { + var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + var salt = 'lesspass.com1'; + LessPass._createHmac(encryptedLogin, salt).then(function (hmac) { + assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); + done(); + }); + }); + it('should derive encrypted login with default options', function () { + const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + const site = 'lesspass.com'; + const option = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + }; + var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); + var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); + Promise.all([p1, p2]).then(generatedPasswords => { + assert.equal(generatedPasswords[0], generatedPasswords[1]) + }); + }); + it('should derive encrypted login with defined length', function (done) { + var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; + var site = 'lesspass.com'; + var option = { + counter: 1, + length: 10, + }; + LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { + assert.equal(10, generatedPassword.length); + done(); + }) + }); + it('should return two different passwords if site different', function () { + const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'google.com'; + const site2 = 'facebook.com'; + var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); + var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site2); + Promise.all([p1, p2]).then(derivedEncryptedLogins => { + assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) + }); + }); + it('should return two different passwords if counter different', function () { + const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option = {counter: 1}; + const option2 = {counter: 2}; + var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); + var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option2); + Promise.all([p1, p2]).then(derivedEncryptedLogins => { + assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) + }); + }); + it('should derive encrypted login with sha 256', function () { + const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (encryptedLogin) { + assert.equal('be00f942fc8a', encryptedLogin); + }); + }); }); }); -test('should return two different passwords if counter different', t => { - const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option = {counter: 1}; - const option2 = {counter: 2}; - var p1 = lesspass._deriveEncryptedLogin(encryptedLogin, site, option); - var p2 = lesspass._deriveEncryptedLogin(encryptedLogin, site, option2); - Promise.all([p1, p2]).then(derivedEncryptedLogins => { - t.not(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) - }); -}); - -test('should derive encrypted login with sha 256', t => { - const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - return lesspass._deriveEncryptedLogin(encryptedLogin, site).then(function (encryptedLogin) { - t.is('be00f942fc8a', encryptedLogin); - }); -}); diff --git a/tests/getPasswordTemplate.tests.js b/tests/getPasswordTemplate.tests.js index 5efca0a..a8718d4 100644 --- a/tests/getPasswordTemplate.tests.js +++ b/tests/getPasswordTemplate.tests.js @@ -1,55 +1,63 @@ -import test from 'ava'; -import lesspass from '../index'; +var assert = chai.assert; -test('should get default template', t => { - t.is('vcVCns', lesspass._getPasswordTemplate({ - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - })); +describe('LessPass', function () { + describe('getPasswordTemplate', function () { + it('should get default template', function () { + assert.equal('vcVCns', LessPass._getPasswordTemplate({ + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + })); + }); + it('should get lowercase template', function () { + assert.equal('vc', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: false, + symbols: false + })); + }); + it('should get uppercase template', function () { + assert.equal('VC', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: true, + numbers: false, + symbols: false + })); + }); + it('should get numbers template', function () { + assert.equal('n', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: true, + symbols: false + })); + }); + it('should get symbols template', function () { + assert.equal('s', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + })); + }); + it('should concatenate template if two password settings', function () { + assert.equal('vcVC', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + })); + assert.equal('vcns', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: true, + symbols: true + })); + }); + }); }); -test('should get template from password setting', t => { - t.is('vc', lesspass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: false, - symbols: false - })); - t.is('VC', lesspass._getPasswordTemplate({ - lowercase: false, - uppercase: true, - numbers: false, - symbols: false - })); - t.is('n', lesspass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: true, - symbols: false - })); - t.is('s', lesspass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: false, - symbols: true - })); -}); - -test('should concatenate template if two password settings', t => { - t.is('vcVC', lesspass._getPasswordTemplate({ - lowercase: true, - uppercase: true, - numbers: false, - symbols: false - })); - t.is('vcns', lesspass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: true, - symbols: true - })); -}); diff --git a/tests/helper.js b/tests/helper.js new file mode 100644 index 0000000..30a150d --- /dev/null +++ b/tests/helper.js @@ -0,0 +1,3 @@ +// globals +global.chai = require('chai'); +global.LessPass = require('../index'); diff --git a/tests/prettyPrint.js b/tests/prettyPrint.js index 7a6c073..bb09c0c 100644 --- a/tests/prettyPrint.js +++ b/tests/prettyPrint.js @@ -1,37 +1,35 @@ -import test from 'ava'; -import lesspass from '../index'; +var assert = chai.assert; -test('should print different password if templates different', t => { - const encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; - t.not(lesspass._prettyPrint(encryptedLogin, 'cv'), lesspass._prettyPrint(encryptedLogin, 'vc')); -}); - -test('must return a string of the same length as the input', t => { - const hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; - t.is(hash.length, lesspass._prettyPrint(hash, 'cv').length); -}); - -test('should return char inside a string based on modulo of the index', t => { - const template = 'cv'; - t.is('c', lesspass._getCharType(template, 0)); - t.is('v', lesspass._getCharType(template, 1)); - t.is('c', lesspass._getCharType(template, 10)); -}); - -test('should convert a string into an array of char code', t => { - const charCodes = lesspass._string2charCodes('ab40f6ee71'); - t.is(97, charCodes[0]); - t.is(98, charCodes[1]); - t.is(10, charCodes.length); -}); - -test('should get password char based on its type and index', t => { - const typeVowel = 'V'; - t.is('A', lesspass._getPasswordChar(typeVowel, 0)); -}); - -test('should modulo if overflow', t => { - const typeVowel = 'V'; - t.is('E', lesspass._getPasswordChar(typeVowel, 1)); - t.is('E', lesspass._getPasswordChar(typeVowel, 7)); +describe('LessPass', function () { + describe('prettyPrint', function () { + it('should print different password if templates different', function () { + var encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; + assert.notEqual(LessPass._prettyPrint(encryptedLogin, 'cv'), LessPass._prettyPrint(encryptedLogin, 'vc')); + }); + it('must return a string of the same length as the input', function () { + var hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; + assert.equal(hash.length, LessPass._prettyPrint(hash, 'cv').length); + }); + it('should return char inside a string based on modulo of the index', function () { + var template = 'cv'; + assert.equal('c', LessPass._getCharType(template, 0)); + assert.equal('v', LessPass._getCharType(template, 1)); + assert.equal('c', LessPass._getCharType(template, 10)); + }); + it('should convert a string into an array of char code', function () { + var charCodes = LessPass._string2charCodes('ab40f6ee71'); + assert.equal(97, charCodes[0]); + assert.equal(98, charCodes[1]); + assert.equal(10, charCodes.length); + }); + it('should get password char based on its type and index', function () { + var typeVowel = 'V'; + assert.equal('A', LessPass._getPasswordChar(typeVowel, 0)); + }); + it('should modulo if overflow', function () { + var typeVowel = 'V'; + assert.equal('E', LessPass._getPasswordChar(typeVowel, 1)); + assert.equal('E', LessPass._getPasswordChar(typeVowel, 7)); + }); + }); }); From 70bebd5e5bcd0c9a32ac6aee05ea4586f0a8773a Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 4 Nov 2016 17:37:21 +0100 Subject: [PATCH 059/124] update encryptLogin API allow user to customize iterations and key length for encryptLogin method. encryptLogin use pbkdf2 with a default 8192 iterations and 32 key length. make pbkdf2 rounds a per-site password profile option lesspass/lesspass#38 --- index.js | 4 +--- tests/api.tests.js | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 98533ca..f8f38b3 100644 --- a/index.js +++ b/index.js @@ -13,13 +13,11 @@ module.exports = { _createHmac }; -function _encryptLogin(login, masterPassword) { +function _encryptLogin(login, masterPassword, {iterations = 8192, keylen = 32}={}) { return new Promise((resolve, reject) => { if (!login || !masterPassword) { reject('login and master password parameters could not be empty'); } - const iterations = 8192; - const keylen = 32; crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { if (error) { reject('error in pbkdf2'); diff --git a/tests/api.tests.js b/tests/api.tests.js index 361cf70..6944284 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -9,12 +9,37 @@ describe('LessPass', function () { }); }); + it('should allow to customize number of iterations', function (done) { + LessPass.encryptLogin('test@example.org', 'password', {iterations: 4096}).then(function (encryptedLogin) { + assert.equal('0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f', encryptedLogin); + done(); + }); + }); + + it('should allow to customize key length', function (done) { + LessPass.encryptLogin('test@example.org', 'password', {keylen: 16}).then(function (encryptedLogin) { + assert.equal('d8af5f918db6b65b1db3d3984e5a400e', encryptedLogin); + done(); + }); + }); + + it('should allow to customize iterations and key length', function (done) { + LessPass.encryptLogin('test@example.org', 'password', { + iterations: 4096, + keylen: 16 + }).then(function (encryptedLogin) { + assert.equal('0a91208545e3aa4935d3a22984ca097a', encryptedLogin); + done(); + }); + }); + it('should allow utf8 parameter', function (done) { LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); done(); }); }); + it('auto generated encrypt login tests', function () { var promises = []; var passwords = [ @@ -105,6 +130,8 @@ describe('LessPass', function () { assert.equal('azYS7,olOL2]', generatedPassword); }) }); + + it('auto generated render password tests', function () { var promises = []; var passwords = [ From 502bcf339f7f42dd9339faba35f6f5cdfe72e267 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 4 Nov 2016 18:16:46 +0100 Subject: [PATCH 060/124] update renderPassword API allow user to customize renderPassword method will help "Other password rules?" issue lesspass/lesspass#37 --- index.js | 2 +- tests/api.tests.js | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index f8f38b3..26a2d78 100644 --- a/index.js +++ b/index.js @@ -30,7 +30,7 @@ function _encryptLogin(login, masterPassword, {iterations = 8192, keylen = 32}={ function _renderPassword(encryptedLogin, site, passwordOptions) { return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - const template = _getPasswordTemplate(passwordOptions); + const template = passwordOptions.template || _getPasswordTemplate(passwordOptions); return _prettyPrint(derivedEncryptedLogin, template); }); } diff --git a/tests/api.tests.js b/tests/api.tests.js index 6944284..40181a5 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -115,7 +115,7 @@ describe('LessPass', function () { describe('LessPass', function () { describe('renderPassword', function () { - it('render password', function () { + it('render password', function (done) { var site = 'lesspass.com'; var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; var passwordOptions = { @@ -128,9 +128,63 @@ describe('LessPass', function () { }; LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { assert.equal('azYS7,olOL2]', generatedPassword); + done(); }) }); + it('render password with a custom template', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'n' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + var i = generatedPassword.length; + while (i--) { + assert('0123456789'.indexOf(generatedPassword[i]) !== -1) + } + }) + }); + + it('render password with a custom template too short', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'CvcnCVsn' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + assert.equal('Sor4WU:8Wad5', generatedPassword); + }) + }); + + it('render password with a custom template too long', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 6, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'CvcnCVsn' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + assert.equal('Sor4WU', generatedPassword); + }) + }); it('auto generated render password tests', function () { var promises = []; @@ -281,10 +335,9 @@ describe('LessPass', function () { describe('LessPass', function () { describe('fingerprint', function () { - it('createFingerprint', function (done) { - LessPass.createFingerprint('password').then(function (fingerprint) { + it('createFingerprint', function () { + return LessPass.createFingerprint('password').then(function (fingerprint) { assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); - done(); }) }); }); From 8bc61b8b2ea866a8bbdb1743c80cb28fb81f7320 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 4 Nov 2016 18:19:27 +0100 Subject: [PATCH 061/124] update documentation --- lib/index.js | 11 ++++++++--- readme.md | 3 ++- tests/node.js | 3 ++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/lib/index.js b/lib/index.js index cfdaec2..f67150a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -20,12 +20,17 @@ module.exports = { }; function _encryptLogin(login, masterPassword) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + var _ref$iterations = _ref.iterations; + var iterations = _ref$iterations === undefined ? 8192 : _ref$iterations; + var _ref$keylen = _ref.keylen; + var keylen = _ref$keylen === undefined ? 32 : _ref$keylen; + return new Promise(function (resolve, reject) { if (!login || !masterPassword) { reject('login and master password parameters could not be empty'); } - var iterations = 8192; - var keylen = 32; _crypto2.default.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { if (error) { reject('error in pbkdf2'); @@ -38,7 +43,7 @@ function _encryptLogin(login, masterPassword) { function _renderPassword(encryptedLogin, site, passwordOptions) { return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = _getPasswordTemplate(passwordOptions); + var template = passwordOptions.template || _getPasswordTemplate(passwordOptions); return _prettyPrint(derivedEncryptedLogin, template); }); } diff --git a/readme.md b/readme.md index 0329418..985ebf9 100644 --- a/readme.md +++ b/readme.md @@ -23,7 +23,8 @@ lowercase: true, uppercase: true, numbers: true, - symbols: true + symbols: true, + template: 'vcVCns' }; LessPass.encryptLogin(login, masterPassword).then(encryptedLogin => { diff --git a/tests/node.js b/tests/node.js index a148b28..779b2de 100644 --- a/tests/node.js +++ b/tests/node.js @@ -10,7 +10,8 @@ var options = { lowercase: true, uppercase: true, numbers: true, - symbols: true + symbols: true, + template: 'vcVCns' }; LessPass.encryptLogin(login, masterPassword) From 8356cb7aa7a94c6867224ff5eb79bdec38b0f52b Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 4 Nov 2016 18:19:43 +0100 Subject: [PATCH 062/124] 5.2.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0d47823..df5a033 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.1.1", + "version": "5.2.0", "author": "Guillaume Vincent ", "description": "LessPass node module used to generate LessPass passwords", "main": "lib/index.js", From 665ca540b4257ae9c8e82713dcab5ec9643abc7b Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 7 Nov 2016 14:58:16 +0100 Subject: [PATCH 063/124] remove useless ISSUE_TEMPLATE --- ISSUE_TEMPLATE | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 ISSUE_TEMPLATE diff --git a/ISSUE_TEMPLATE b/ISSUE_TEMPLATE deleted file mode 100644 index f6acdd8..0000000 --- a/ISSUE_TEMPLATE +++ /dev/null @@ -1,11 +0,0 @@ - - -**Thank you for taking your time to fill out an issue.** - -To make it easier to manage, can you put this issue in LessPass super project ? - -https://github.com/lesspass/lesspass/issues - -:heart: - -Thanks \ No newline at end of file From 0555a2130789fd371cf85ac284f177f2fbc79ccb Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 13 Nov 2016 12:09:14 +0100 Subject: [PATCH 064/124] clean package.json --- package.json | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/package.json b/package.json index df5a033..824b3cd 100644 --- a/package.json +++ b/package.json @@ -1,27 +1,32 @@ { "name": "lesspass", "version": "5.2.0", - "author": "Guillaume Vincent ", "description": "LessPass node module used to generate LessPass passwords", + "keywords": [ + "crypto", + "lesspass", + "password" + ], + "license": "GPLv3", + "author": "Guillaume Vincent ", + "files": [ + "lib/", + "index.js" + ], "main": "lib/index.js", "jsnext:main": "index.js", "repository": "lesspass/core", "scripts": { - "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd ..", - "test": "mocha --compilers js:babel-register --require ./tests/helper.js tests", "build": "rimraf lib && babel index.js -d lib", - "prepublish": "npm test && npm run build && npm run test:node" + "prepublish": "npm test && npm run build && npm run test:node", + "test": "mocha --compilers js:babel-register --require ./tests/helper.js tests", + "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd .." + }, + "babel": { + "presets": [ + "es2015" + ] }, - "files": [ - "lib/", - "index.js" - ], - "keywords": [ - "password", - "crypto", - "lesspass" - ], - "license": "MIT", "devDependencies": { "babel-cli": "^6.16.0", "babel-core": "^6.17.0", @@ -29,10 +34,5 @@ "chai": "^3.5.0", "mocha": "^3.1.2", "rimraf": "^2.5.4" - }, - "babel": { - "presets": [ - "es2015" - ] } } From 260dbd36155227dd5188b3b65df04097ec6ac165 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 15 Nov 2016 14:44:03 +0100 Subject: [PATCH 065/124] use the browserified version of crypto packages --- index.js | 9 +++++---- lib/index.js | 13 +++++-------- package.json | 4 ++++ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index 26a2d78..ab267fe 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,5 @@ -import crypto from 'crypto'; +var pbkdf2 = require('pbkdf2'); +var createHmac = require('create-hmac'); module.exports = { encryptLogin: _encryptLogin, @@ -18,7 +19,7 @@ function _encryptLogin(login, masterPassword, {iterations = 8192, keylen = 32}={ if (!login || !masterPassword) { reject('login and master password parameters could not be empty'); } - crypto.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { if (error) { reject('error in pbkdf2'); } else { @@ -37,7 +38,7 @@ function _renderPassword(encryptedLogin, site, passwordOptions) { function _createHmac(encryptedLogin, salt) { return new Promise(resolve => { - resolve(crypto.createHmac('sha256', encryptedLogin).update(salt).digest('hex')); + resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); }); } @@ -104,6 +105,6 @@ function _getPasswordChar(charType, index) { function createFingerprint(str) { return new Promise(resolve => { - resolve(crypto.createHmac('sha256', str).digest('hex')) + resolve(createHmac('sha256', new Buffer(str)).digest('hex')) }); } \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index f67150a..3c9bf9a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,10 +1,7 @@ 'use strict'; -var _crypto = require('crypto'); - -var _crypto2 = _interopRequireDefault(_crypto); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var pbkdf2 = require('pbkdf2'); +var createHmac = require('create-hmac'); module.exports = { encryptLogin: _encryptLogin, @@ -31,7 +28,7 @@ function _encryptLogin(login, masterPassword) { if (!login || !masterPassword) { reject('login and master password parameters could not be empty'); } - _crypto2.default.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -50,7 +47,7 @@ function _renderPassword(encryptedLogin, site, passwordOptions) { function _createHmac(encryptedLogin, salt) { return new Promise(function (resolve) { - resolve(_crypto2.default.createHmac('sha256', encryptedLogin).update(salt).digest('hex')); + resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); }); } @@ -119,6 +116,6 @@ function _getPasswordChar(charType, index) { function createFingerprint(str) { return new Promise(function (resolve) { - resolve(_crypto2.default.createHmac('sha256', str).digest('hex')); + resolve(createHmac('sha256', new Buffer(str)).digest('hex')); }); } \ No newline at end of file diff --git a/package.json b/package.json index 824b3cd..0c0aea6 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,10 @@ "es2015" ] }, + "dependencies": { + "create-hmac": "^1.1.4", + "pbkdf2": "^3.0.9" + }, "devDependencies": { "babel-cli": "^6.16.0", "babel-core": "^6.17.0", From 9790da5489b612b59cc7a835054cbd83d37c56de Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 15 Nov 2016 15:33:14 +0100 Subject: [PATCH 066/124] merge webcrypto --- example/index.html | 35 + gulpfile.js | 17 + lib/lesspass.js | 6724 +++++++++++++++++++++++++++++++++++++++ lib/lesspass.webcrypto.js | 310 ++ lib/lesspass.webcrypto.min.js | 1 + package.json | 18 +- tests/api.tests.js | 6 +- tests/karma.config.js | 24 + tests/karma.webcrypto.config.js | 26 + webcrypto.js | 158 + 10 files changed, 7313 insertions(+), 6 deletions(-) create mode 100644 example/index.html create mode 100644 gulpfile.js create mode 100644 lib/lesspass.js create mode 100644 lib/lesspass.webcrypto.js create mode 100644 lib/lesspass.webcrypto.min.js create mode 100644 tests/karma.config.js create mode 100644 tests/karma.webcrypto.config.js create mode 100644 webcrypto.js diff --git a/example/index.html b/example/index.html new file mode 100644 index 0000000..41e7165 --- /dev/null +++ b/example/index.html @@ -0,0 +1,35 @@ + + + + + + + + + + \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..b6fbfbb --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,17 @@ +var gulp = require('gulp'), + concat = require('gulp-concat'), + rename = require('gulp-rename'), + uglify = require('gulp-uglify'); + +gulp.task('js', function () { + return gulp.src(['node_modules/unibabel/index.js', 'node_modules/unibabel/unibabel.hex.js', 'webcrypto.js']) + .pipe(concat('lesspass.webcrypto.js')) + .pipe(gulp.dest('lib')) + .pipe(rename('lesspass.webcrypto.min.js')) + .pipe(uglify()) + .pipe(gulp.dest('lib')); +}); + +gulp.task('default', ['js'], function () { +}); + diff --git a/lib/lesspass.js b/lib/lesspass.js new file mode 100644 index 0000000..bfe261e --- /dev/null +++ b/lib/lesspass.js @@ -0,0 +1,6724 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LessPass = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) +} + +function _renderPassword(encryptedLogin, site, passwordOptions) { + return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + const template = passwordOptions.template || _getPasswordTemplate(passwordOptions); + return _prettyPrint(derivedEncryptedLogin, template); + }); +} + +function _createHmac(encryptedLogin, salt) { + return new Promise(resolve => { + resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + }); +} + +function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { + const salt = site + passwordOptions.counter.toString(); + return _createHmac(encryptedLogin, salt).then(derivedHash => { + return derivedHash.substring(0, passwordOptions.length); + }); +} + +function _getPasswordTemplate(passwordTypes) { + const templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + let template = ''; + for (let templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] + } + } + return template; +} + +function _prettyPrint(hash, template) { + let password = ''; + + _string2charCodes(hash).forEach((charCode, index) => { + const charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; +} + +function _string2charCodes(text) { + const charCodes = []; + for (let i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + const passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + const passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function createFingerprint(str) { + return new Promise(resolve => { + resolve(createHmac('sha256', new Buffer(str)).digest('hex')) + }); +} +}).call(this,require("buffer").Buffer) +},{"buffer":5,"create-hmac":11,"pbkdf2":17}],2:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} + +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],3:[function(require,module,exports){ + +},{}],4:[function(require,module,exports){ +(function (global){ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"buffer":5}],5:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":2,"ieee754":13,"isarray":16}],6:[function(require,module,exports){ +(function (Buffer){ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + return out +} + +}).call(this,require("buffer").Buffer) +},{"buffer":5,"inherits":14,"stream":41,"string_decoder":42}],7:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":15}],8:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var inherits = require('inherits') +var md5 = require('./md5') +var rmd160 = require('ripemd160') +var sha = require('sha.js') + +var Base = require('cipher-base') + +function HashNoConstructor(hash) { + Base.call(this, 'digest') + + this._hash = hash + this.buffers = [] +} + +inherits(HashNoConstructor, Base) + +HashNoConstructor.prototype._update = function (data) { + this.buffers.push(data) +} + +HashNoConstructor.prototype._final = function () { + var buf = Buffer.concat(this.buffers) + var r = this._hash(buf) + this.buffers = null + + return r +} + +function Hash(hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if ('md5' === alg) return new HashNoConstructor(md5) + if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160) + + return new Hash(sha(alg)) +} + +}).call(this,require("buffer").Buffer) +},{"./md5":10,"buffer":5,"cipher-base":6,"inherits":14,"ripemd160":32,"sha.js":34}],9:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} +exports.hash = hash; +}).call(this,require("buffer").Buffer) +},{"buffer":5}],10:[function(require,module,exports){ +'use strict'; +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = require('./helpers'); + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; +},{"./helpers":9}],11:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var createHash = require('create-hash/browser'); +var inherits = require('inherits') + +var Transform = require('stream').Transform + +var ZEROS = new Buffer(128) +ZEROS.fill(0) + +function Hmac(alg, key) { + Transform.call(this) + alg = alg.toLowerCase() + if (typeof key === 'string') { + key = new Buffer(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + + if (key.length > blocksize) { + key = createHash(alg).update(key).digest() + + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = new Buffer(blocksize) + var opad = this._opad = new Buffer(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = createHash(alg).update(ipad) +} + +inherits(Hmac, Transform) + +Hmac.prototype.update = function (data, enc) { + this._hash.update(data, enc) + + return this +} + +Hmac.prototype._transform = function (data, _, next) { + this._hash.update(data) + + next() +} + +Hmac.prototype._flush = function (next) { + this.push(this.digest()) + + next() +} + +Hmac.prototype.digest = function (enc) { + var h = this._hash.digest() + + return createHash(this._alg).update(this._opad).update(h).digest(enc) +} + +module.exports = function createHmac(alg, key) { + return new Hmac(alg, key) +} + +}).call(this,require("buffer").Buffer) +},{"buffer":5,"create-hash/browser":8,"inherits":14,"stream":41}],12:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],13:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],14:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],15:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],16:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],17:[function(require,module,exports){ +(function (process,Buffer){ +var createHmac = require('create-hmac') +var checkParameters = require('./precondition') + +exports.pbkdf2 = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + checkParameters(iterations, keylen) + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + + setTimeout(function () { + callback(null, exports.pbkdf2Sync(password, salt, iterations, keylen, digest)) + }) +} + +var defaultEncoding +if (process.browser) { + defaultEncoding = 'utf-8' +} else { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} + +exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { + if (!Buffer.isBuffer(password)) password = new Buffer(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, defaultEncoding) + + checkParameters(iterations, keylen) + + digest = digest || 'sha1' + + var hLen + var l = 1 + var DK = new Buffer(keylen) + var block1 = new Buffer(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var r + var T + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + var U = createHmac(digest, password).update(block1).digest() + + if (!hLen) { + hLen = U.length + T = new Buffer(hLen) + l = Math.ceil(keylen / hLen) + r = keylen - (l - 1) * hLen + } + + U.copy(T, 0, 0, hLen) + + for (var j = 1; j < iterations; j++) { + U = createHmac(digest, password).update(U).digest() + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + var destPos = (i - 1) * hLen + var len = (i === l ? r : hLen) + T.copy(DK, destPos, 0, len) + } + + return DK +} + +}).call(this,require('_process'),require("buffer").Buffer) +},{"./precondition":18,"_process":20,"buffer":5,"create-hmac":11}],18:[function(require,module,exports){ +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + +},{}],19:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + +}).call(this,require('_process')) +},{"_process":20}],20:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],21:[function(require,module,exports){ +module.exports = require("./lib/_stream_duplex.js") + +},{"./lib/_stream_duplex.js":22}],22:[function(require,module,exports){ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":24,"./_stream_writable":26,"core-util-is":7,"inherits":14,"process-nextick-args":19}],23:[function(require,module,exports){ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":25,"core-util-is":7,"inherits":14}],24:[function(require,module,exports){ +(function (process){ +'use strict'; + +module.exports = Readable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var isArray = require('isarray'); +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var StringDecoder; + +util.inherits(Readable, Stream); + +function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} + +var Duplex; +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +var Duplex; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = bufferShim.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process')) +},{"./_stream_duplex":22,"./internal/streams/BufferList":27,"_process":20,"buffer":5,"buffer-shims":4,"core-util-is":7,"events":12,"inherits":14,"isarray":16,"process-nextick-args":19,"string_decoder/":42,"util":3}],25:[function(require,module,exports){ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":22,"core-util-is":7,"inherits":14}],26:[function(require,module,exports){ +(function (process){ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +util.inherits(Writable, Stream); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +var Duplex; +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +var Duplex; +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = bufferShim.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} +}).call(this,require('_process')) +},{"./_stream_duplex":22,"_process":20,"buffer":5,"buffer-shims":4,"core-util-is":7,"events":12,"inherits":14,"process-nextick-args":19,"util-deprecate":43}],27:[function(require,module,exports){ +'use strict'; + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +module.exports = BufferList; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return bufferShim.alloc(0); + if (this.length === 1) return this.head.data; + var ret = bufferShim.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; +},{"buffer":5,"buffer-shims":4}],28:[function(require,module,exports){ +module.exports = require("./lib/_stream_passthrough.js") + +},{"./lib/_stream_passthrough.js":23}],29:[function(require,module,exports){ +(function (process){ +var Stream = (function (){ + try { + return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify + } catch(_){} +}()); +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream || exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; +} + +}).call(this,require('_process')) +},{"./lib/_stream_duplex.js":22,"./lib/_stream_passthrough.js":23,"./lib/_stream_readable.js":24,"./lib/_stream_transform.js":25,"./lib/_stream_writable.js":26,"_process":20}],30:[function(require,module,exports){ +module.exports = require("./lib/_stream_transform.js") + +},{"./lib/_stream_transform.js":25}],31:[function(require,module,exports){ +module.exports = require("./lib/_stream_writable.js") + +},{"./lib/_stream_writable.js":26}],32:[function(require,module,exports){ +(function (Buffer){ +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** @preserve +(c) 2012 by Cédric Mesnil. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// constants table +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] +var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] + +function bytesToWords (bytes) { + var words = [] + for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { + words[b >>> 5] |= bytes[i] << (24 - b % 32) + } + return words +} + +function wordsToBytes (words) { + var bytes = [] + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) + } + return bytes +} + +function processBlock (H, M, offset) { + // swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i + var M_offset_i = M[offset_i] + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ) + } + + // Working variables + var al, bl, cl, dl, el + var ar, br, cr, dr, er + + ar = al = H[0] + br = bl = H[1] + cr = cl = H[2] + dr = dl = H[3] + er = el = H[4] + + // computation + var t + for (i = 0; i < 80; i += 1) { + t = (al + M[offset + zl[i]]) | 0 + if (i < 16) { + t += f1(bl, cl, dl) + hl[0] + } else if (i < 32) { + t += f2(bl, cl, dl) + hl[1] + } else if (i < 48) { + t += f3(bl, cl, dl) + hl[2] + } else if (i < 64) { + t += f4(bl, cl, dl) + hl[3] + } else {// if (i<80) { + t += f5(bl, cl, dl) + hl[4] + } + t = t | 0 + t = rotl(t, sl[i]) + t = (t + el) | 0 + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = t + + t = (ar + M[offset + zr[i]]) | 0 + if (i < 16) { + t += f5(br, cr, dr) + hr[0] + } else if (i < 32) { + t += f4(br, cr, dr) + hr[1] + } else if (i < 48) { + t += f3(br, cr, dr) + hr[2] + } else if (i < 64) { + t += f2(br, cr, dr) + hr[3] + } else {// if (i<80) { + t += f1(br, cr, dr) + hr[4] + } + + t = t | 0 + t = rotl(t, sr[i]) + t = (t + er) | 0 + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = t + } + + // intermediate hash value + t = (H[1] + cl + dr) | 0 + H[1] = (H[2] + dl + er) | 0 + H[2] = (H[3] + el + ar) | 0 + H[3] = (H[4] + al + br) | 0 + H[4] = (H[0] + bl + cr) | 0 + H[0] = t +} + +function f1 (x, y, z) { + return ((x) ^ (y) ^ (z)) +} + +function f2 (x, y, z) { + return (((x) & (y)) | ((~x) & (z))) +} + +function f3 (x, y, z) { + return (((x) | (~(y))) ^ (z)) +} + +function f4 (x, y, z) { + return (((x) & (z)) | ((y) & (~(z)))) +} + +function f5 (x, y, z) { + return ((x) ^ ((y) | (~(z)))) +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function ripemd160 (message) { + var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] + + if (typeof message === 'string') { + message = new Buffer(message, 'utf8') + } + + var m = bytesToWords(message) + + var nBitsLeft = message.length * 8 + var nBitsTotal = message.length * 8 + + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) + m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ) + + for (var i = 0; i < m.length; i += 16) { + processBlock(H, m, i) + } + + // swap endian + for (i = 0; i < 5; i++) { + // shortcut + var H_i = H[i] + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00) + } + + var digestbytes = wordsToBytes(H) + return new Buffer(digestbytes) +} + +module.exports = ripemd160 + +}).call(this,require("buffer").Buffer) +},{"buffer":5}],33:[function(require,module,exports){ +(function (Buffer){ +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = new Buffer(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + this._s = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = new Buffer(data, enc) + } + + var l = this._len += data.length + var s = this._s || 0 + var f = 0 + var buffer = this._block + + while (s < l) { + var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) + var ch = (t - f) + + for (var i = 0; i < ch; i++) { + buffer[(s % this._blockSize) + i] = data[i + f] + } + + s += ch + f += ch + + if ((s % this._blockSize) === 0) { + this._update(buffer) + } + } + this._s = s + + return this +} + +Hash.prototype.digest = function (enc) { + // Suppose the length of the message M, in bits, is l + var l = this._len * 8 + + // Append the bit 1 to the end of the message + this._block[this._len % this._blockSize] = 0x80 + + // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize + this._block.fill(0, this._len % this._blockSize + 1) + + if (l % (this._blockSize * 8) >= this._finalSize * 8) { + this._update(this._block) + this._block.fill(0) + } + + // to this append the block which is equal to the number l written in binary + // TODO: handle case where l is > Math.pow(2, 29) + this._block.writeInt32BE(l, this._blockSize - 4) + + var hash = this._update(this._block) || this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + +}).call(this,require("buffer").Buffer) +},{"buffer":5}],34:[function(require,module,exports){ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') + +},{"./sha":35,"./sha1":36,"./sha224":37,"./sha256":38,"./sha384":39,"./sha512":40}],35:[function(require,module,exports){ +(function (Buffer){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + +}).call(this,require("buffer").Buffer) +},{"./hash":33,"buffer":5,"inherits":14}],36:[function(require,module,exports){ +(function (Buffer){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 + +}).call(this,require("buffer").Buffer) +},{"./hash":33,"buffer":5,"inherits":14}],37:[function(require,module,exports){ +(function (Buffer){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = new Buffer(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + +}).call(this,require("buffer").Buffer) +},{"./hash":33,"./sha256":38,"buffer":5,"inherits":14}],38:[function(require,module,exports){ +(function (Buffer){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = new Buffer(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + +}).call(this,require("buffer").Buffer) +},{"./hash":33,"buffer":5,"inherits":14}],39:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = new Buffer(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + +}).call(this,require("buffer").Buffer) +},{"./hash":33,"./sha512":40,"buffer":5,"inherits":14}],40:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = new Buffer(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + +}).call(this,require("buffer").Buffer) +},{"./hash":33,"buffer":5,"inherits":14}],41:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":12,"inherits":14,"readable-stream/duplex.js":21,"readable-stream/passthrough.js":28,"readable-stream/readable.js":29,"readable-stream/transform.js":30,"readable-stream/writable.js":31}],42:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +},{"buffer":5}],43:[function(require,module,exports){ +(function (global){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}]},{},[1])(1) +}); \ No newline at end of file diff --git a/lib/lesspass.webcrypto.js b/lib/lesspass.webcrypto.js new file mode 100644 index 0000000..0e52f1e --- /dev/null +++ b/lib/lesspass.webcrypto.js @@ -0,0 +1,310 @@ +(function () { +'use strict'; + +function utf8ToBinaryString(str) { + var escstr = encodeURIComponent(str); + // replaces any uri escape sequence, such as %0A, + // with binary escape, such as 0x0A + var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) { + return String.fromCharCode(parseInt(p1, 16)); + }); + + return binstr; +} + +function utf8ToBuffer(str) { + var binstr = utf8ToBinaryString(str); + var buf = binaryStringToBuffer(binstr); + return buf; +} + +function utf8ToBase64(str) { + var binstr = utf8ToBinaryString(str); + return btoa(binstr); +} + +function binaryStringToUtf8(binstr) { + var escstr = binstr.replace(/(.)/g, function (m, p) { + var code = p.charCodeAt(0).toString(16).toUpperCase(); + if (code.length < 2) { + code = '0' + code; + } + return '%' + code; + }); + + return decodeURIComponent(escstr); +} + +function bufferToUtf8(buf) { + var binstr = bufferToBinaryString(buf); + + return binaryStringToUtf8(binstr); +} + +function base64ToUtf8(b64) { + var binstr = atob(b64); + + return binaryStringToUtf8(binstr); +} + +function bufferToBinaryString(buf) { + var binstr = Array.prototype.map.call(buf, function (ch) { + return String.fromCharCode(ch); + }).join(''); + + return binstr; +} + +function bufferToBase64(arr) { + var binstr = bufferToBinaryString(arr); + return btoa(binstr); +} + +function binaryStringToBuffer(binstr) { + var buf; + + if ('undefined' !== typeof Uint8Array) { + buf = new Uint8Array(binstr.length); + } else { + buf = []; + } + + Array.prototype.forEach.call(binstr, function (ch, i) { + buf[i] = ch.charCodeAt(0); + }); + + return buf; +} + +function base64ToBuffer(base64) { + var binstr = atob(base64); + var buf = binaryStringToBuffer(binstr); + return buf; +} + +window.Unibabel = { + utf8ToBinaryString: utf8ToBinaryString +, utf8ToBuffer: utf8ToBuffer +, utf8ToBase64: utf8ToBase64 +, binaryStringToUtf8: binaryStringToUtf8 +, bufferToUtf8: bufferToUtf8 +, base64ToUtf8: base64ToUtf8 +, bufferToBinaryString: bufferToBinaryString +, bufferToBase64: bufferToBase64 +, binaryStringToBuffer: binaryStringToBuffer +, base64ToBuffer: base64ToBuffer + +// compat +, strToUtf8Arr: utf8ToBuffer +, utf8ArrToStr: bufferToUtf8 +, arrToBase64: bufferToBase64 +, base64ToArr: base64ToBuffer +}; + +}()); + +(function () { +'use strict'; + +function bufferToHex(arr) { + var i; + var len; + var hex = ''; + var c; + + for (i = 0, len = arr.length; i < len; i += 1) { + c = arr[i].toString(16); + if (c.length < 2) { + c = '0' + c; + } + hex += c; + } + + return hex; +} + +function hexToBuffer(hex) { + // TODO use Uint8Array or ArrayBuffer or DataView + var i; + var byteLen = hex.length / 2; + var arr; + var j = 0; + + if (byteLen !== parseInt(byteLen, 10)) { + throw new Error("Invalid hex length '" + hex.length + "'"); + } + + arr = new Uint8Array(byteLen); + + for (i = 0; i < byteLen; i += 1) { + arr[i] = parseInt(hex[j] + hex[j + 1], 16); + j += 2; + } + + return arr; +} + +// Hex Convenience Functions +window.Unibabel.hexToBuffer = hexToBuffer; +window.Unibabel.bufferToHex = bufferToHex; + +}()); + +(function () { + 'use strict'; + + if (window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle) { + window.crypto.subtle = window.crypto.webkitSubtle; + } + if (!window.crypto || !window.crypto.subtle) { + console.error("Your browser does not support the Web Cryptography API! LessPass will not work."); + return; + } + + function importKey(masterPassword, algo, usages) { + var format = 'raw'; + var masterPasswordArrayBuffer = Unibabel.utf8ToBuffer(masterPassword); + var extractable = false; + return window.crypto.subtle.importKey(format, masterPasswordArrayBuffer, algo, extractable, usages); + } + + function deriveKey(masterKey, salt, iterations, keylen) { + var algo = { + name: 'PBKDF2', + salt: Unibabel.utf8ToBuffer(salt), + iterations: iterations, + hash: 'SHA-256', + }; + var extractable = true; + var derivedKeyAlgo = {name: 'AES-CTR', length: keylen * 8}; + var usages = ['encrypt', 'decrypt']; + return window.crypto.subtle.deriveKey(algo, masterKey, derivedKeyAlgo, extractable, usages); + } + + + function exportKey(derivedKey) { + return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { + return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); + }); + } + + function encryptLogin(login, masterPassword, options) { + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + + return importKey(masterPassword, 'PBKDF2', ['deriveKey']) + .then(function (key) { + return deriveKey(key, login, iterations, keylen); + }) + .then(exportKey); + } + + function signKey(masterKey, salt) { + var algo = {name: 'HMAC'}; + var saltArrayBuffer = Unibabel.utf8ToBuffer(salt); + return window.crypto.subtle.sign(algo, masterKey, saltArrayBuffer); + } + + function _createHmac(encryptedLogin, salt) { + return importKey(encryptedLogin, {name: 'HMAC', hash: {name: 'SHA-256'}}, ['sign']) + .then(function (key) { + return signKey(key, salt); + }) + .then(function (derivedHmacKey) { + return Unibabel.bufferToHex(new Uint8Array(derivedHmacKey)) + }); + } + + function _deriveEncryptedLogin(encryptedLogin, site) { + var passwordOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + length: 12, + counter: 1 + }; + + var salt = site + passwordOptions.counter.toString(); + return _createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, passwordOptions.length); + }); + } + + function createFingerprint(str) { + return _createHmac(str, ''); + } + + function renderPassword(encryptedLogin, site, passwordOptions) { + return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = passwordOptions.template || LessPass._getPasswordTemplate(passwordOptions); + return LessPass._prettyPrint(derivedEncryptedLogin, template); + }); + } + + function _getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var template = ''; + for (var templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] + } + } + return template; + } + + + function _prettyPrint(hash, template) { + var password = ''; + + _string2charCodes(hash).forEach(function (charCode, index) { + var charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; + } + + function _string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; + } + + function _getCharType(template, index) { + return template[index % template.length]; + } + + function _getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; + } + + window.LessPass = { + encryptLogin: encryptLogin, + renderPassword: renderPassword, + createFingerprint: createFingerprint, + _createHmac: _createHmac, + _deriveEncryptedLogin: _deriveEncryptedLogin, + _getPasswordTemplate: _getPasswordTemplate, + _prettyPrint: _prettyPrint, + _string2charCodes: _string2charCodes, + _getCharType: _getCharType, + _getPasswordChar: _getPasswordChar, + }; +}()); + diff --git a/lib/lesspass.webcrypto.min.js b/lib/lesspass.webcrypto.min.js new file mode 100644 index 0000000..dffa619 --- /dev/null +++ b/lib/lesspass.webcrypto.min.js @@ -0,0 +1 @@ +!function(){"use strict";function r(r){var n=encodeURIComponent(r),t=n.replace(/%([0-9A-F]{2})/g,function(r,n){return String.fromCharCode(parseInt(n,16))});return t}function n(n){var t=r(n),e=f(t);return e}function t(n){var t=r(n);return btoa(t)}function e(r){var n=r.replace(/(.)/g,function(r,n){var t=n.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t});return decodeURIComponent(n)}function o(r){var n=i(r);return e(n)}function u(r){var n=atob(r);return e(n)}function i(r){var n=Array.prototype.map.call(r,function(r){return String.fromCharCode(r)}).join("");return n}function a(r){var n=i(r);return btoa(n)}function f(r){var n;return n="undefined"!=typeof Uint8Array?new Uint8Array(r.length):[],Array.prototype.forEach.call(r,function(r,t){n[t]=r.charCodeAt(0)}),n}function c(r){var n=atob(r),t=f(n);return t}window.Unibabel={utf8ToBinaryString:r,utf8ToBuffer:n,utf8ToBase64:t,binaryStringToUtf8:e,bufferToUtf8:o,base64ToUtf8:u,bufferToBinaryString:i,bufferToBase64:a,binaryStringToBuffer:f,base64ToBuffer:c,strToUtf8Arr:n,utf8ArrToStr:o,arrToBase64:a,base64ToArr:c}}(),function(){"use strict";function r(r){var n,t,e,o="";for(n=0,t=r.length;n2&&void 0!==arguments[2]?arguments[2]:{length:12,counter:1},e=n+t.counter.toString();return u(r,e).then(function(r){return r.substring(0,t.length)})}function a(r){return u(r,"")}function f(r,n,t){return i(r,n,t).then(function(r){var n=t.template||LessPass._getPasswordTemplate(t);return LessPass._prettyPrint(r,n)})}function c(r){var n={lowercase:"vc",uppercase:"VC",numbers:"n",symbols:"s"},t="";for(var e in n)r.hasOwnProperty(e)&&r[e]&&(t+=n[e]);return t}function s(r,n){var t="";return w(r).forEach(function(r,e){var o=l(n,e);t+=b(o,r)}),t}function w(r){for(var n=[],t=0;t lib/lesspass.js", + "gulp": "gulp", "prepublish": "npm test && npm run build && npm run test:node", "test": "mocha --compilers js:babel-register --require ./tests/helper.js tests", - "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd .." + "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd ..", + "test:webcrypto": "karma start tests/karma.webcrypto.config.js", + "test:browser": "npm run build && karma start tests/karma.config.js" }, "babel": { "presets": [ @@ -29,13 +32,22 @@ }, "dependencies": { "create-hmac": "^1.1.4", - "pbkdf2": "^3.0.9" + "pbkdf2": "^3.0.9", + "unibabel": "^2.1.3" }, "devDependencies": { "babel-cli": "^6.16.0", "babel-core": "^6.17.0", "babel-preset-es2015": "^6.16.0", + "browserify": "^13.1.1", "chai": "^3.5.0", + "gulp": "^3.9.1", + "gulp-concat": "^2.6.1", + "gulp-rename": "^1.2.2", + "gulp-uglify": "^2.0.0", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", "mocha": "^3.1.2", "rimraf": "^2.5.4" } diff --git a/tests/api.tests.js b/tests/api.tests.js index 40181a5..1f27baa 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -33,14 +33,14 @@ describe('LessPass', function () { }); }); - it('should allow utf8 parameter', function (done) { - LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { + it('should allow utf8 parameter', function () { + return LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); - done(); }); }); it('auto generated encrypt login tests', function () { + this.timeout(10000); var promises = []; var passwords = [ { diff --git a/tests/karma.config.js b/tests/karma.config.js new file mode 100644 index 0000000..efec162 --- /dev/null +++ b/tests/karma.config.js @@ -0,0 +1,24 @@ +module.exports = function (config) { + config.set({ + basePath: '..', + frameworks: ['mocha', 'chai'], + files: [ + 'lib/lesspass.js', + 'tests/**/*.js' + ], + exclude: [ + 'tests/node.js', + 'tests/helper.js', + 'tests/karma.webcrypto.config.js', + ], + preprocessors: {}, + reporters: ['progress'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome', 'Firefox'], + singleRun: true, + concurrency: Infinity + }) +}; diff --git a/tests/karma.webcrypto.config.js b/tests/karma.webcrypto.config.js new file mode 100644 index 0000000..ef9fad9 --- /dev/null +++ b/tests/karma.webcrypto.config.js @@ -0,0 +1,26 @@ +module.exports = function (config) { + config.set({ + basePath: '..', + frameworks: ['mocha', 'chai'], + files: [ + 'node_modules/unibabel/index.js', + 'node_modules/unibabel/unibabel.hex.js', + 'webcrypto.js', + 'tests/**/*.js' + ], + exclude: [ + 'tests/node.js', + 'tests/helper.js', + 'tests/karma.config.js', + ], + preprocessors: {}, + reporters: ['progress'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome', 'Firefox'], + singleRun: true, + concurrency: Infinity + }) +}; diff --git a/webcrypto.js b/webcrypto.js new file mode 100644 index 0000000..d606127 --- /dev/null +++ b/webcrypto.js @@ -0,0 +1,158 @@ +(function () { + 'use strict'; + + if (window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle) { + window.crypto.subtle = window.crypto.webkitSubtle; + } + if (!window.crypto || !window.crypto.subtle) { + console.error("Your browser does not support the Web Cryptography API! LessPass will not work."); + return; + } + + function importKey(masterPassword, algo, usages) { + var format = 'raw'; + var masterPasswordArrayBuffer = Unibabel.utf8ToBuffer(masterPassword); + var extractable = false; + return window.crypto.subtle.importKey(format, masterPasswordArrayBuffer, algo, extractable, usages); + } + + function deriveKey(masterKey, salt, iterations, keylen) { + var algo = { + name: 'PBKDF2', + salt: Unibabel.utf8ToBuffer(salt), + iterations: iterations, + hash: 'SHA-256', + }; + var extractable = true; + var derivedKeyAlgo = {name: 'AES-CTR', length: keylen * 8}; + var usages = ['encrypt', 'decrypt']; + return window.crypto.subtle.deriveKey(algo, masterKey, derivedKeyAlgo, extractable, usages); + } + + + function exportKey(derivedKey) { + return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { + return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); + }); + } + + function encryptLogin(login, masterPassword, options) { + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + + return importKey(masterPassword, 'PBKDF2', ['deriveKey']) + .then(function (key) { + return deriveKey(key, login, iterations, keylen); + }) + .then(exportKey); + } + + function signKey(masterKey, salt) { + var algo = {name: 'HMAC'}; + var saltArrayBuffer = Unibabel.utf8ToBuffer(salt); + return window.crypto.subtle.sign(algo, masterKey, saltArrayBuffer); + } + + function _createHmac(encryptedLogin, salt) { + return importKey(encryptedLogin, {name: 'HMAC', hash: {name: 'SHA-256'}}, ['sign']) + .then(function (key) { + return signKey(key, salt); + }) + .then(function (derivedHmacKey) { + return Unibabel.bufferToHex(new Uint8Array(derivedHmacKey)) + }); + } + + function _deriveEncryptedLogin(encryptedLogin, site) { + var passwordOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + length: 12, + counter: 1 + }; + + var salt = site + passwordOptions.counter.toString(); + return _createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, passwordOptions.length); + }); + } + + function createFingerprint(str) { + return _createHmac(str, ''); + } + + function renderPassword(encryptedLogin, site, passwordOptions) { + return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = passwordOptions.template || LessPass._getPasswordTemplate(passwordOptions); + return LessPass._prettyPrint(derivedEncryptedLogin, template); + }); + } + + function _getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var template = ''; + for (var templateKey in templates) { + if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { + template += templates[templateKey] + } + } + return template; + } + + + function _prettyPrint(hash, template) { + var password = ''; + + _string2charCodes(hash).forEach(function (charCode, index) { + var charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; + } + + function _string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; + } + + function _getCharType(template, index) { + return template[index % template.length]; + } + + function _getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; + } + + window.LessPass = { + encryptLogin: encryptLogin, + renderPassword: renderPassword, + createFingerprint: createFingerprint, + _createHmac: _createHmac, + _deriveEncryptedLogin: _deriveEncryptedLogin, + _getPasswordTemplate: _getPasswordTemplate, + _prettyPrint: _prettyPrint, + _string2charCodes: _string2charCodes, + _getCharType: _getCharType, + _getPasswordChar: _getPasswordChar, + }; +}()); + From 0b3e22fd0c6c7ebe43a7bc93407821c4dc628b7e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 15 Nov 2016 19:06:32 +0100 Subject: [PATCH 067/124] remove ES6 code --- example/index.html | 35 ------------ example/lesspass.html | 35 ++++++++++++ example/lesspass.webcrypto.html | 35 ++++++++++++ gulpfile.js | 14 ++--- index.js | 28 ++++++---- lib/index.js | 121 ---------------------------------------- lib/lesspass.js | 28 ++++++---- lib/lesspass.webcrypto.min.js | 1 - package.json | 24 +++----- tests/node.js | 2 +- 10 files changed, 119 insertions(+), 204 deletions(-) delete mode 100644 example/index.html create mode 100644 example/lesspass.html create mode 100644 example/lesspass.webcrypto.html delete mode 100644 lib/index.js delete mode 100644 lib/lesspass.webcrypto.min.js diff --git a/example/index.html b/example/index.html deleted file mode 100644 index 41e7165..0000000 --- a/example/index.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/example/lesspass.html b/example/lesspass.html new file mode 100644 index 0000000..3c46d32 --- /dev/null +++ b/example/lesspass.html @@ -0,0 +1,35 @@ + + + + + + + + + + \ No newline at end of file diff --git a/example/lesspass.webcrypto.html b/example/lesspass.webcrypto.html new file mode 100644 index 0000000..2caf890 --- /dev/null +++ b/example/lesspass.webcrypto.html @@ -0,0 +1,35 @@ + + + + + + + + + + \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index b6fbfbb..562f4db 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,17 +1,13 @@ -var gulp = require('gulp'), - concat = require('gulp-concat'), - rename = require('gulp-rename'), - uglify = require('gulp-uglify'); +var gulp = require('gulp'); +var concat = require('gulp-concat'); +var rename = require('gulp-rename'); -gulp.task('js', function () { +gulp.task('webcrypto', function () { return gulp.src(['node_modules/unibabel/index.js', 'node_modules/unibabel/unibabel.hex.js', 'webcrypto.js']) .pipe(concat('lesspass.webcrypto.js')) - .pipe(gulp.dest('lib')) - .pipe(rename('lesspass.webcrypto.min.js')) - .pipe(uglify()) .pipe(gulp.dest('lib')); }); -gulp.task('default', ['js'], function () { +gulp.task('default', ['webcrypto'], function () { }); diff --git a/index.js b/index.js index ab267fe..9aba1ac 100644 --- a/index.js +++ b/index.js @@ -14,12 +14,16 @@ module.exports = { _createHmac }; -function _encryptLogin(login, masterPassword, {iterations = 8192, keylen = 32}={}) { - return new Promise((resolve, reject) => { +function _encryptLogin(login, masterPassword, options) { + const _options = options !== undefined ? options : {}; + const iterations = _options.iterations || 8192; + const keylen = _options.keylen || 32; + + return new Promise(function (resolve, reject) { if (!login || !masterPassword) { reject('login and master password parameters could not be empty'); } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -37,15 +41,19 @@ function _renderPassword(encryptedLogin, site, passwordOptions) { } function _createHmac(encryptedLogin, salt) { - return new Promise(resolve => { + return new Promise(function (resolve) { resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); }); } -function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { - const salt = site + passwordOptions.counter.toString(); - return _createHmac(encryptedLogin, salt).then(derivedHash => { - return derivedHash.substring(0, passwordOptions.length); +function _deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; + + const salt = site + counter.toString(); + return _createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, length); }); } @@ -68,7 +76,7 @@ function _getPasswordTemplate(passwordTypes) { function _prettyPrint(hash, template) { let password = ''; - _string2charCodes(hash).forEach((charCode, index) => { + _string2charCodes(hash).forEach(function (charCode, index) { const charType = _getCharType(template, index); password += _getPasswordChar(charType, charCode); }); @@ -104,7 +112,7 @@ function _getPasswordChar(charType, index) { } function createFingerprint(str) { - return new Promise(resolve => { + return new Promise(function (resolve) { resolve(createHmac('sha256', new Buffer(str)).digest('hex')) }); } \ No newline at end of file diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index 3c9bf9a..0000000 --- a/lib/index.js +++ /dev/null @@ -1,121 +0,0 @@ -'use strict'; - -var pbkdf2 = require('pbkdf2'); -var createHmac = require('create-hmac'); - -module.exports = { - encryptLogin: _encryptLogin, - renderPassword: _renderPassword, - createFingerprint: createFingerprint, - _deriveEncryptedLogin: _deriveEncryptedLogin, - _getPasswordTemplate: _getPasswordTemplate, - _prettyPrint: _prettyPrint, - _string2charCodes: _string2charCodes, - _getCharType: _getCharType, - _getPasswordChar: _getPasswordChar, - _createHmac: _createHmac -}; - -function _encryptLogin(login, masterPassword) { - var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - var _ref$iterations = _ref.iterations; - var iterations = _ref$iterations === undefined ? 8192 : _ref$iterations; - var _ref$keylen = _ref.keylen; - var keylen = _ref$keylen === undefined ? 32 : _ref$keylen; - - return new Promise(function (resolve, reject) { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); - } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }); -} - -function _renderPassword(encryptedLogin, site, passwordOptions) { - return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = passwordOptions.template || _getPasswordTemplate(passwordOptions); - return _prettyPrint(derivedEncryptedLogin, template); - }); -} - -function _createHmac(encryptedLogin, salt) { - return new Promise(function (resolve) { - resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); - }); -} - -function _deriveEncryptedLogin(encryptedLogin, site) { - var passwordOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { length: 12, counter: 1 }; - - var salt = site + passwordOptions.counter.toString(); - return _createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, passwordOptions.length); - }); -} - -function _getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's' - }; - var template = ''; - for (var templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey]; - } - } - return template; -} - -function _prettyPrint(hash, template) { - var password = ''; - - _string2charCodes(hash).forEach(function (charCode, index) { - var charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; -} - -function _string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} - -function _getCharType(template, index) { - return template[index % template.length]; -} - -function _getPasswordChar(charType, index) { - var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; -} - -function createFingerprint(str) { - return new Promise(function (resolve) { - resolve(createHmac('sha256', new Buffer(str)).digest('hex')); - }); -} \ No newline at end of file diff --git a/lib/lesspass.js b/lib/lesspass.js index bfe261e..712d9bd 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -16,12 +16,16 @@ module.exports = { _createHmac }; -function _encryptLogin(login, masterPassword, {iterations = 8192, keylen = 32}={}) { - return new Promise((resolve, reject) => { +function _encryptLogin(login, masterPassword, options) { + const _options = options !== undefined ? options : {}; + const iterations = _options.iterations || 8192; + const keylen = _options.keylen || 32; + + return new Promise(function (resolve, reject) { if (!login || !masterPassword) { reject('login and master password parameters could not be empty'); } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', (error, key) => { + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -39,15 +43,19 @@ function _renderPassword(encryptedLogin, site, passwordOptions) { } function _createHmac(encryptedLogin, salt) { - return new Promise(resolve => { + return new Promise(function (resolve) { resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); }); } -function _deriveEncryptedLogin(encryptedLogin, site, passwordOptions = {length: 12, counter: 1}) { - const salt = site + passwordOptions.counter.toString(); - return _createHmac(encryptedLogin, salt).then(derivedHash => { - return derivedHash.substring(0, passwordOptions.length); +function _deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; + + const salt = site + counter.toString(); + return _createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, length); }); } @@ -70,7 +78,7 @@ function _getPasswordTemplate(passwordTypes) { function _prettyPrint(hash, template) { let password = ''; - _string2charCodes(hash).forEach((charCode, index) => { + _string2charCodes(hash).forEach(function (charCode, index) { const charType = _getCharType(template, index); password += _getPasswordChar(charType, charCode); }); @@ -106,7 +114,7 @@ function _getPasswordChar(charType, index) { } function createFingerprint(str) { - return new Promise(resolve => { + return new Promise(function (resolve) { resolve(createHmac('sha256', new Buffer(str)).digest('hex')) }); } diff --git a/lib/lesspass.webcrypto.min.js b/lib/lesspass.webcrypto.min.js deleted file mode 100644 index dffa619..0000000 --- a/lib/lesspass.webcrypto.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(){"use strict";function r(r){var n=encodeURIComponent(r),t=n.replace(/%([0-9A-F]{2})/g,function(r,n){return String.fromCharCode(parseInt(n,16))});return t}function n(n){var t=r(n),e=f(t);return e}function t(n){var t=r(n);return btoa(t)}function e(r){var n=r.replace(/(.)/g,function(r,n){var t=n.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t});return decodeURIComponent(n)}function o(r){var n=i(r);return e(n)}function u(r){var n=atob(r);return e(n)}function i(r){var n=Array.prototype.map.call(r,function(r){return String.fromCharCode(r)}).join("");return n}function a(r){var n=i(r);return btoa(n)}function f(r){var n;return n="undefined"!=typeof Uint8Array?new Uint8Array(r.length):[],Array.prototype.forEach.call(r,function(r,t){n[t]=r.charCodeAt(0)}),n}function c(r){var n=atob(r),t=f(n);return t}window.Unibabel={utf8ToBinaryString:r,utf8ToBuffer:n,utf8ToBase64:t,binaryStringToUtf8:e,bufferToUtf8:o,base64ToUtf8:u,bufferToBinaryString:i,bufferToBase64:a,binaryStringToBuffer:f,base64ToBuffer:c,strToUtf8Arr:n,utf8ArrToStr:o,arrToBase64:a,base64ToArr:c}}(),function(){"use strict";function r(r){var n,t,e,o="";for(n=0,t=r.length;n2&&void 0!==arguments[2]?arguments[2]:{length:12,counter:1},e=n+t.counter.toString();return u(r,e).then(function(r){return r.substring(0,t.length)})}function a(r){return u(r,"")}function f(r,n,t){return i(r,n,t).then(function(r){var n=t.template||LessPass._getPasswordTemplate(t);return LessPass._prettyPrint(r,n)})}function c(r){var n={lowercase:"vc",uppercase:"VC",numbers:"n",symbols:"s"},t="";for(var e in n)r.hasOwnProperty(e)&&r[e]&&(t+=n[e]);return t}function s(r,n){var t="";return w(r).forEach(function(r,e){var o=l(n,e);t+=b(o,r)}),t}function w(r){for(var n=[],t=0;t", "files": [ - "lib/", "index.js" ], - "main": "lib/index.js", - "jsnext:main": "index.js", + "main": "index.js", "repository": "lesspass/core", "scripts": { - "build": "rimraf lib && babel index.js -d lib && browserify --standalone LessPass index.js > lib/lesspass.js", - "gulp": "gulp", - "prepublish": "npm test && npm run build && npm run test:node", - "test": "mocha --compilers js:babel-register --require ./tests/helper.js tests", - "test:node": "npm run build && cd tests && babel-node --presets es2015 node.js && cd ..", + "build": "rimraf lib && mkdir lib && browserify --standalone LessPass index.js > lib/lesspass.js && gulp", + "prepublish": "npm test && npm run build && npm run test:node && npm run test:browser", + "test": "mocha --require ./tests/helper.js tests", + "test:node": "npm run build && cd tests && node node.js && cd ..", "test:webcrypto": "karma start tests/karma.webcrypto.config.js", "test:browser": "npm run build && karma start tests/karma.config.js" }, - "babel": { - "presets": [ - "es2015" - ] - }, "dependencies": { "create-hmac": "^1.1.4", "pbkdf2": "^3.0.9", "unibabel": "^2.1.3" }, "devDependencies": { - "babel-cli": "^6.16.0", - "babel-core": "^6.17.0", - "babel-preset-es2015": "^6.16.0", "browserify": "^13.1.1", "chai": "^3.5.0", "gulp": "^3.9.1", "gulp-concat": "^2.6.1", "gulp-rename": "^1.2.2", - "gulp-uglify": "^2.0.0", "karma": "^1.3.0", "karma-chai": "^0.1.0", + "karma-chrome-launcher": "^2.0.0", + "karma-firefox-launcher": "^1.0.0", "karma-mocha": "^1.3.0", "mocha": "^3.1.2", "rimraf": "^2.5.4" diff --git a/tests/node.js b/tests/node.js index 779b2de..6a510e0 100644 --- a/tests/node.js +++ b/tests/node.js @@ -1,4 +1,4 @@ -var LessPass = require('../lib/index'); +var LessPass = require('../index'); var assert = require('assert'); var site = 'lesspass.com'; From 6d0e1b792d02880d20367e5333b04a34b595f72e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 15 Nov 2016 19:06:55 +0100 Subject: [PATCH 068/124] 5.2.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2600361..addd2cf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.2.0", + "version": "5.2.1", "description": "LessPass node module used to generate LessPass passwords", "keywords": [ "crypto", From ce916e68b8fe7210736235b196fd39b7ef0fe308 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 15 Nov 2016 19:53:24 +0100 Subject: [PATCH 069/124] add phantomjs to fix error on travis --- index.js | 51 +- lib/lesspass.js | 6026 +++++++++++++++++++++++++++++++++-- package.json | 3 + tests/api.tests.js | 16 +- tests/deriveEncryptedLogin.tests.js | 6 +- tests/karma.config.js | 9 +- tests/karma.webcrypto.config.js | 8 +- tests/node.js | 6 +- 8 files changed, 5870 insertions(+), 255 deletions(-) diff --git a/index.js b/index.js index 9aba1ac..f742f94 100644 --- a/index.js +++ b/index.js @@ -1,23 +1,24 @@ var pbkdf2 = require('pbkdf2'); var createHmac = require('create-hmac'); +var Promise = require("bluebird"); module.exports = { encryptLogin: _encryptLogin, renderPassword: _renderPassword, createFingerprint: createFingerprint, - _deriveEncryptedLogin, - _getPasswordTemplate, - _prettyPrint, - _string2charCodes, - _getCharType, - _getPasswordChar, - _createHmac + _deriveEncryptedLogin: _deriveEncryptedLogin, + _getPasswordTemplate: _getPasswordTemplate, + _prettyPrint: _prettyPrint, + _string2charCodes: _string2charCodes, + _getCharType: _getCharType, + _getPasswordChar: _getPasswordChar, + _createHmac: _createHmac }; function _encryptLogin(login, masterPassword, options) { - const _options = options !== undefined ? options : {}; - const iterations = _options.iterations || 8192; - const keylen = _options.keylen || 32; + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; return new Promise(function (resolve, reject) { if (!login || !masterPassword) { @@ -35,7 +36,7 @@ function _encryptLogin(login, masterPassword, options) { function _renderPassword(encryptedLogin, site, passwordOptions) { return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - const template = passwordOptions.template || _getPasswordTemplate(passwordOptions); + var template = passwordOptions.template || _getPasswordTemplate(passwordOptions); return _prettyPrint(derivedEncryptedLogin, template); }); } @@ -51,41 +52,41 @@ function _deriveEncryptedLogin(encryptedLogin, site, options) { var length = _options.length || 12; var counter = _options.counter || 1; - const salt = site + counter.toString(); + var salt = site + counter.toString(); return _createHmac(encryptedLogin, salt).then(function (derivedHash) { return derivedHash.substring(0, length); }); } function _getPasswordTemplate(passwordTypes) { - const templates = { + var templates = { lowercase: 'vc', uppercase: 'VC', numbers: 'n', symbols: 's', }; - let template = ''; - for (let templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] + var returnedTemplate = ''; + Object.keys(templates).forEach(function (template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template] } - } - return template; + }); + return returnedTemplate; } function _prettyPrint(hash, template) { - let password = ''; + var password = ''; _string2charCodes(hash).forEach(function (charCode, index) { - const charType = _getCharType(template, index); + var charType = _getCharType(template, index); password += _getPasswordChar(charType, charCode); }); return password; } function _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { charCodes.push(text.charCodeAt(i)); } return charCodes; @@ -96,7 +97,7 @@ function _getCharType(template, index) { } function _getPasswordChar(charType, index) { - const passwordsChars = { + var passwordsChars = { V: 'AEIOUY', C: 'BCDFGHJKLMNPQRSTVWXZ', v: 'aeiouy', @@ -107,7 +108,7 @@ function _getPasswordChar(charType, index) { s: '@&%?,=[]_:-+*$#!\'^~;()/.', x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' }; - const passwordChar = passwordsChars[charType]; + var passwordChar = passwordsChars[charType]; return passwordChar[index % passwordChar.length]; } diff --git a/lib/lesspass.js b/lib/lesspass.js index 712d9bd..714c2a3 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -2,242 +2,5844 @@ (function (Buffer){ var pbkdf2 = require('pbkdf2'); var createHmac = require('create-hmac'); +var Promise = require("bluebird"); module.exports = { encryptLogin: _encryptLogin, renderPassword: _renderPassword, createFingerprint: createFingerprint, - _deriveEncryptedLogin, - _getPasswordTemplate, - _prettyPrint, - _string2charCodes, - _getCharType, - _getPasswordChar, - _createHmac + _deriveEncryptedLogin: _deriveEncryptedLogin, + _getPasswordTemplate: _getPasswordTemplate, + _prettyPrint: _prettyPrint, + _string2charCodes: _string2charCodes, + _getCharType: _getCharType, + _getPasswordChar: _getPasswordChar, + _createHmac: _createHmac }; function _encryptLogin(login, masterPassword, options) { - const _options = options !== undefined ? options : {}; - const iterations = _options.iterations || 8192; - const keylen = _options.keylen || 32; + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + + return new Promise(function (resolve, reject) { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) +} + +function _renderPassword(encryptedLogin, site, passwordOptions) { + return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = passwordOptions.template || _getPasswordTemplate(passwordOptions); + return _prettyPrint(derivedEncryptedLogin, template); + }); +} + +function _createHmac(encryptedLogin, salt) { + return new Promise(function (resolve) { + resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + }); +} + +function _deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; + + var salt = site + counter.toString(); + return _createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, length); + }); +} + +function _getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var returnedTemplate = ''; + Object.keys(templates).forEach(function (template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template] + } + }); + return returnedTemplate; +} + +function _prettyPrint(hash, template) { + var password = ''; + + _string2charCodes(hash).forEach(function (charCode, index) { + var charType = _getCharType(template, index); + password += _getPasswordChar(charType, charCode); + }); + return password; +} + +function _string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function _getCharType(template, index) { + return template[index % template.length]; +} + +function _getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function createFingerprint(str) { + return new Promise(function (resolve) { + resolve(createHmac('sha256', new Buffer(str)).digest('hex')) + }); +} +}).call(this,require("buffer").Buffer) +},{"bluebird":3,"buffer":6,"create-hmac":12,"pbkdf2":18}],2:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} + +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],3:[function(require,module,exports){ +(function (process,global){ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 3.4.6 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (((this._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise":22}],5:[function(_dereq_,module,exports){ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = _dereq_("./util"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var args = [].slice.call(arguments, 1);; + if (!true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + +},{"./util":36}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise._isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent._isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + promise._setWillBeCancelled(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this._isCancellable()) return; + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this._isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; + +},{"./util":36}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util"); +var getKeys = _dereq_("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; + +},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; + +},{}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (true || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); + +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); + +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +var fireDomEvent = (function() { + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new CustomEvent(name.toLowerCase(), { + detail: event, + cancelable: true + }); + return !util.global.dispatchEvent(domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new Event(name.toLowerCase(), { + cancelable: true + }); + domEvent.detail = event; + return !util.global.dispatchEvent(domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name.toLowerCase(), false, true, + event); + return !util.global.dispatchEvent(domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); + +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); + +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; +} + +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; + +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } + + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } + + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; + + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } + + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { + + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } + + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", true); + } +} + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = " (No stack trace)" === line || + stackFramePattern.test(line); + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); + } + } else { + activeFireEvent(name, promise); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +function longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit -= 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit -= 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; + +},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; + +},{}],11:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; +var PromiseAll = Promise.all; + +function promiseAllThis() { + return PromiseAll(this); +} + +function PromiseMapSeries(promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, INTERNAL); +} + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, INTERNAL, 0) + ._then(promiseAllThis, undefined, undefined, this, undefined); +}; + +Promise.prototype.mapSeries = function (fn) { + return PromiseReduce(this, fn, INTERNAL, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, 0) + ._then(promiseAllThis, undefined, undefined, promises, undefined); +}; + +Promise.mapSeries = PromiseMapSeries; +}; + + +},{}],12:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],14:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; + +},{}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, tryConvertToPromise) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; + +function PassThroughHandlerContext(promise, type, handler) { + this.promise = promise; + this.type = type; + this.handler = handler; + this.called = false; + this.cancelPromise = null; +} + +PassThroughHandlerContext.prototype.isFinallyHandler = function() { + return this.type === 0; +}; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.isFinallyHandler() + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret !== undefined) { + promise._setReturnedNonUndefined(); + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise._isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, + fail, + undefined, + new PassThroughHandlerContext(this, type, handler), + undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +return PassThroughHandlerContext; +}; + +},{"./util":36}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise, + Proxyable, + debug) { +var errors = _dereq_("./errors"); +var TypeError = errors.TypeError; +var util = _dereq_("./util"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + if (debug.cancellation()) { + var internal = new Promise(INTERNAL); + var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); + this._promise = internal.lastly(function() { + return _finallyPromise; + }); + internal._captureStackTrace(); + internal._setOnCancel(this); + } else { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + } + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; + this._yieldedPromise = null; + this._cancellationPhase = false; +} +util.inherits(PromiseSpawn, Proxyable); + +PromiseSpawn.prototype._isResolved = function() { + return this._promise === null; +}; + +PromiseSpawn.prototype._cleanup = function() { + this._promise = this._generator = null; + if (debug.cancellation() && this._finallyPromise !== null) { + this._finallyPromise._fulfill(); + this._finallyPromise = null; + } +}; + +PromiseSpawn.prototype._promiseCancelled = function() { + if (this._isResolved()) return; + var implementsReturn = typeof this._generator["return"] !== "undefined"; + + var result; + if (!implementsReturn) { + var reason = new Promise.CancellationError( + "generator .return() sentinel"); + Promise.coroutine.returnSentinel = reason; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + result = tryCatch(this._generator["throw"]).call(this._generator, + reason); + this._promise._popContext(); + } else { + this._promise._pushContext(); + result = tryCatch(this._generator["return"]).call(this._generator, + undefined); + this._promise._popContext(); + } + this._cancellationPhase = true; + this._yieldedPromise = null; + this._continue(result); +}; + +PromiseSpawn.prototype._promiseFulfilled = function(value) { + this._yieldedPromise = null; + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._promiseRejected = function(reason) { + this._yieldedPromise = null; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._resultCancelled = function() { + if (this._yieldedPromise instanceof Promise) { + var promise = this._yieldedPromise; + this._yieldedPromise = null; + promise.cancel(); + } +}; + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._promiseFulfilled(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + var promise = this._promise; + if (result === errorObj) { + this._cleanup(); + if (this._cancellationPhase) { + return promise.cancel(); + } else { + return promise._rejectCallback(result.e, false); + } + } + + var value = result.value; + if (result.done === true) { + this._cleanup(); + if (this._cancellationPhase) { + return promise.cancel(); + } else { + return promise._resolveCallback(value); + } + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._promiseRejected( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + this._yieldedPromise = maybePromise; + maybePromise._proxy(this, null); + } else if (((bitField & 33554432) !== 0)) { + Promise._async.invoke( + this._promiseFulfilled, this, maybePromise._value() + ); + } else if (((bitField & 16777216) !== 0)) { + Promise._async.invoke( + this._promiseRejected, this, maybePromise._reason() + ); + } else { + this._promiseCancelled(); + } + } +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + var ret = spawn.promise(); + spawn._generator = generator; + spawn._promiseFulfilled(undefined); + return ret; + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + debug.deprecated("Promise.spawn()", "Promise.coroutine()"); + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; + +},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, + getDomain) { +var util = _dereq_("./util"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise, async) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.asyncNeeded = true; \n\ + this.now = 0; \n\ + } \n\ + \n\ + [TheName].prototype._callFunction = function(promise) { \n\ + promise._pushContext(); \n\ + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + if (this.asyncNeeded) { \n\ + async.invoke(this._callFunction, this, promise); \n\ + } else { \n\ + this._callFunction(promise); \n\ + } \n\ + \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise, async); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", "async", code) + (tryCatch, errorObj, Promise, async); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + reject = function (reason) { + this._reject(reason); + }; +}} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + holder.asyncNeeded = false; + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + + if (!ret._isFateSealed()) { + if (holder.asyncNeeded) { + var domain = getDomain(); + if (domain !== null) { + holder.fn = util.domainBind(domain, holder.fn); + } + } + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } + return ret; + } + } + } + var args = [].slice.call(arguments);; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util":36}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + var domain = getDomain(); + this._callback = domain === null ? fn : util.domainBind(domain, fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = []; + async.invoke(this._asyncInit, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); + +MappingPromiseArray.prototype._asyncInit = function() { + this._init$(undefined, -2); +}; + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + + if (index < 0) { + index = (index * -1) - 1; + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return true; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return false; + } + if (preservedValues !== null) preservedValues[index] = value; + + var promise = this._promise; + var callback = this._callback; + var receiver = promise._boundValue(); + promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + preservedValues !== null ? "Promise.filter" : "Promise.map", + promise + ); + if (ret === errorObj) { + this._reject(ret.e); + return true; + } + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + if (limit >= 1) this._inFlight++; + values[index] = maybePromise; + maybePromise._proxy(this, (index + 1) * -1); + return false; + } else if (((bitField & 33554432) !== 0)) { + ret = maybePromise._value(); + } else if (((bitField & 16777216) !== 0)) { + this._reject(maybePromise._reason()); + return true; + } else { + this._cancel(); + return true; + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + return true; + } + return false; +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + + var limit = 0; + if (options !== undefined) { + if (typeof options === "object" && options !== null) { + if (typeof options.concurrency !== "number") { + return Promise.reject( + new TypeError("'concurrency' must be a number but it is " + + util.classString(options.concurrency))); + } + limit = options.concurrency; + } else { + return Promise.reject(new TypeError( + "options argument must be an object but it is " + + util.classString(options))); + } + } + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter).promise(); +} + +Promise.prototype.map = function (fn, options) { + return map(this, fn, options, null); +}; + +Promise.map = function (promises, fn, options, _filter) { + return map(promises, fn, options, _filter); +}; + + +}; + +},{"./util":36}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util":36}],20:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors"); +var OperationalError = errors.OperationalError; +var es5 = _dereq_("./es5"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + var args = [].slice.call(arguments, 1);; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; + +},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util"); +var async = Promise._async; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundValue(); + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var newReason = new Error(reason + ""); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, + options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./util":36}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = _dereq_("./util"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var es5 = _dereq_("./es5"); +var Async = _dereq_("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = _dereq_("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {}; +var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = _dereq_("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; +var debug = _dereq_("./debuggability")(Promise, Context); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + _dereq_("./finally")(Promise, tryConvertToPromise); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + if (self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } +} + +function Promise(executor) { + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + if (executor !== INTERNAL) { + check(this, executor); + this._resolveFromExecutor(executor); + } + this._promiseCreated(); + this._fireEvent("promiseCreated", this); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("expecting an object but got " + + "A catch statement predicate " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.getNewLibraryCopy = module.exports; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + return async.setScheduler(fn); +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + this._fireEvent("promiseChained", this, promise); + } + + var domain = getDomain(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: domain === null ? handler + : (typeof handler === "function" && + util.domainBind(domain, handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; + this._fireEvent("promiseFulfilled", this); +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; + this._fireEvent("promiseRejected", this); +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; + this._fireEvent("promiseResolved", this); +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; + this._fireEvent("promiseCancelled", this); +}; + +Promise.prototype._setWillBeCancelled = function() { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + if (async.hasCustomScheduler()) return; + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : util.domainBind(domain, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : util.domainBind(domain, reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + var promise = maybePromise._target(); + + if (promise === this) { + this._reject(makeSelfResolutionError()); + return; + } + + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj) { + promise._rejectCallback(x.e, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise, this); + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (receiver instanceof PassThroughHandlerContext && + receiver.isFinallyHandler()) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + async.settlePromises(this); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); +_dereq_("./direct_resolve")(Promise); +_dereq_("./synchronous_inspection")(Promise); +_dereq_("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); +Promise.Promise = Promise; +Promise.version = "3.4.6"; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./call_get.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +_dereq_('./timers.js')(Promise, INTERNAL, debug); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +_dereq_('./nodeify.js')(Promise); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./settle.js')(Promise, PromiseArray, debug); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./filter.js')(Promise, INTERNAL); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = _dereq_("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util":36}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util"); +var nodebackForPromise = _dereq_("./nodeback"); +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + name !== "constructor"; +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn, _, multiArgs) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + var body = "'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ + return promise; \n\ + }; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ + return ret; \n\ + ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode); + body = body.replace("Parameters", parameterDeclaration(newParameterCount)); + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL", + body)( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise, multiArgs); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); + return promise; + } + util.notEnumerableProp(promisified, "__isPromisified__", true); + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, + fn, suffix, multiArgs); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver, multiArgs) { + return makeNodePromisified(callback, receiver, undefined, + callback, null, multiArgs); +} + +Promise.promisify = function (fn, options) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + if (isPromisified(fn)) { + return fn; + } + options = Object(options); + var receiver = options.context === undefined ? THIS : options.context; + var multiArgs = !!options.multiArgs; + var ret = promisify(fn, receiver, multiArgs); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + options = Object(options); + var multiArgs = !!options.multiArgs; + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier, + multiArgs); + promisifyAll(value, suffix, filter, promisifier, multiArgs); + } + } + + return promisifyAll(target, suffix, filter, promisifier, multiArgs); +}; +}; + + +},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util"); +var isObject = util.isObject; +var es5 = _dereq_("./es5"); +var Es6Map; +if (typeof Map === "function") Es6Map = Map; + +var mapToEntries = (function() { + var index = 0; + var size = 0; + + function extractEntry(value, key) { + this[index] = value; + this[index + size] = key; + index++; + } + + return function mapToEntries(map) { + size = map.size; + index = 0; + var ret = new Array(map.size * 2); + map.forEach(extractEntry, ret); + return ret; + }; +})(); + +var entriesToMap = function(entries) { + var ret = new Es6Map(); + var length = entries.length / 2 | 0; + for (var i = 0; i < length; ++i) { + var key = entries[length + i]; + var value = entries[i]; + ret.set(key, value); + } + return ret; +}; + +function PropertiesPromiseArray(obj) { + var isMap = false; + var entries; + if (Es6Map !== undefined && obj instanceof Es6Map) { + entries = mapToEntries(obj); + isMap = true; + } else { + var keys = es5.keys(obj); + var len = keys.length; + entries = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + entries[i] = obj[key]; + entries[i + len] = key; + } + } + this.constructor$(entries); + this._isMap = isMap; + this._init$(undefined, -3); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () {}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val; + if (this._isMap) { + val = entriesToMap(this._values); + } else { + val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + } + this._resolve(val); + return true; + } + return false; +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 2); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + +},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util"); + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else { + promises = util.asArray(promises); + if (promises === null) + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 3); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; + +},{"./util":36}],28:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +function ReductionPromiseArray(promises, fn, initialValue, _each) { + this.constructor$(promises); + var domain = getDomain(); + this._fn = domain === null ? fn : util.domainBind(domain, fn); + if (initialValue !== undefined) { + initialValue = Promise.resolve(initialValue); + initialValue._attachCancellationCallback(this); + } + this._initialValue = initialValue; + this._currentCancellable = null; + if(_each === INTERNAL) { + this._eachValues = Array(this._length); + } else if (_each === 0) { + this._eachValues = null; + } else { + this._eachValues = undefined; + } + this._promise._captureStackTrace(); + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._gotAccum = function(accum) { + if (this._eachValues !== undefined && + this._eachValues !== null && + accum !== INTERNAL) { + this._eachValues.push(accum); + } +}; + +ReductionPromiseArray.prototype._eachComplete = function(value) { + if (this._eachValues !== null) { + this._eachValues.push(value); + } + return this._eachValues; +}; + +ReductionPromiseArray.prototype._init = function() {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function() { + this._resolve(this._eachValues !== undefined ? this._eachValues + : this._initialValue); +}; + +ReductionPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +ReductionPromiseArray.prototype._resolve = function(value) { + this._promise._resolveCallback(value); + this._values = null; +}; + +ReductionPromiseArray.prototype._resultCancelled = function(sender) { + if (sender === this._initialValue) return this._cancel(); + if (this._isResolved()) return; + this._resultCancelled$(); + if (this._currentCancellable instanceof Promise) { + this._currentCancellable.cancel(); + } + if (this._initialValue instanceof Promise) { + this._initialValue.cancel(); + } +}; + +ReductionPromiseArray.prototype._iterate = function (values) { + this._values = values; + var value; + var i; + var length = values.length; + if (this._initialValue !== undefined) { + value = this._initialValue; + i = 0; + } else { + value = Promise.resolve(values[0]); + i = 1; + } + + this._currentCancellable = value; + + if (!value.isRejected()) { + for (; i < length; ++i) { + var ctx = { + accum: null, + value: values[i], + index: i, + length: length, + array: this + }; + value = value._then(gotAccum, undefined, undefined, ctx, undefined); + } + } + + if (this._eachValues !== undefined) { + value = value + ._then(this._eachComplete, undefined, undefined, this, undefined); + } + value._then(completed, completed, undefined, value, this); +}; + +Promise.prototype.reduce = function (fn, initialValue) { + return reduce(this, fn, initialValue, null); +}; + +Promise.reduce = function (promises, fn, initialValue, _each) { + return reduce(promises, fn, initialValue, _each); +}; + +function completed(valueOrReason, array) { + if (this.isFulfilled()) { + array._resolve(valueOrReason); + } else { + array._reject(valueOrReason); + } +} + +function reduce(promises, fn, initialValue, _each) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var array = new ReductionPromiseArray(promises, fn, initialValue, _each); + return array.promise(); +} + +function gotAccum(accum) { + this.accum = accum; + this.array._gotAccum(accum); + var value = tryConvertToPromise(this.value, this.array._promise); + if (value instanceof Promise) { + this.array._currentCancellable = value; + return value._then(gotValue, undefined, undefined, this, undefined); + } else { + return gotValue.call(this, value); + } +} + +function gotValue(value) { + var array = this.array; + var promise = array._promise; + var fn = tryCatch(array._fn); + promise._pushContext(); + var ret; + if (array._eachValues !== undefined) { + ret = fn.call(promise._boundValue(), value, this.index, this.length); + } else { + ret = fn.call(promise._boundValue(), + this.accum, value, this.index, this.length); + } + if (ret instanceof Promise) { + array._currentCancellable = ret; + } + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", + promise + ); + return ret; +} +}; + +},{"./util":36}],29:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var NativePromise = util.getNativePromise(); +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if (typeof NativePromise === "function" && + typeof NativePromise.resolve === "function") { + var nativePromise = NativePromise.resolve(); + schedule = function(fn) { + nativePromise.then(fn); + }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + (window.navigator.standalone || window.cordova))) { + schedule = (function() { + var div = document.createElement("div"); + var opts = {attributes: true}; + var toggleScheduled = false; + var div2 = document.createElement("div"); + var o2 = new MutationObserver(function() { + div.classList.toggle("foo"); + toggleScheduled = false; + }); + o2.observe(div2, opts); + + var scheduleToggle = function() { + if (toggleScheduled) return; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; + + return function schedule(fn) { + var o = new MutationObserver(function() { + o.disconnect(); + fn(); + }); + o.observe(div, opts); + scheduleToggle(); + }; + })(); +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util":36}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = + function(Promise, PromiseArray, debug) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 33554432; + ret._settledValueField = value; + return this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 16777216; + ret._settledValueField = reason; + return this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + debug.deprecated(".settle()", ".reflect()"); + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return Promise.settle(this); +}; +}; + +},{"./util":36}],31:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util"); +var RangeError = _dereq_("./errors").RangeError; +var AggregateError = _dereq_("./errors").AggregateError; +var isArray = util.isArray; +var CANCELLATION = {}; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + return true; + } + return false; + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._promiseCancelled = function () { + if (this._values instanceof Promise || this._values == null) { + return this._cancel(); + } + this._addRejected(CANCELLATION); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._checkOutcome = function() { + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + if (this._values[i] !== CANCELLATION) { + e.push(this._values[i]); + } + } + if (e.length > 0) { + this._reject(e); + } else { + this._cancel(); + } + return true; + } + return false; +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; + +},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = function() { + return (this._bitField & 8454144) !== 0; +}; + +Promise.prototype.__isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype._isCancelled = function() { + return this._target().__isCancelled(); +}; + +Promise.prototype.isCancelled = function() { + return (this._target()._bitField & 8454144) !== 0; +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = getThen(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util":36}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, debug) { +var util = _dereq_("./util"); +var TimeoutError = Promise.TimeoutError; + +function HandleWrapper(handle) { + this.handle = handle; +} + +HandleWrapper.prototype._resultCancelled = function() { + clearTimeout(this.handle); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (ms, value) { + var ret; + var handle; + if (value !== undefined) { + ret = Promise.resolve(value) + ._then(afterValue, null, null, ms, undefined); + if (debug.cancellation() && value instanceof Promise) { + ret._setOnCancel(value); + } + } else { + ret = new Promise(INTERNAL); + handle = setTimeout(function() { ret._fulfill(); }, +ms); + if (debug.cancellation()) { + ret._setOnCancel(new HandleWrapper(handle)); + } + ret._captureStackTrace(); + } + ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.prototype.delay = function (ms) { + return delay(ms, this); +}; + +var afterTimeout = function (promise, message, parent) { + var err; + if (typeof message !== "string") { + if (message instanceof Error) { + err = message; + } else { + err = new TimeoutError("operation timed out"); + } + } else { + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._reject(err); + + if (parent != null) { + parent.cancel(); + } +}; + +function successClear(value) { + clearTimeout(this.handle); + return value; +} + +function failureClear(reason) { + clearTimeout(this.handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret, parent; + + var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { + if (ret.isPending()) { + afterTimeout(ret, message, parent); + } + }, ms)); + + if (debug.cancellation()) { + parent = this.then(); + ret = parent._then(successClear, failureClear, + undefined, handleWrapper, undefined); + ret._setOnCancel(handleWrapper); + } else { + ret = this._then(successClear, failureClear, + undefined, handleWrapper, undefined); + } + + return ret; +}; + +}; + +},{"./util":36}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext, INTERNAL, debug) { + var util = _dereq_("./util"); + var TypeError = _dereq_("./errors").TypeError; + var inherits = _dereq_("./util").inherits; + var errorObj = util.errorObj; + var tryCatch = util.tryCatch; + var NULL = {}; + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = new Promise(INTERNAL); + function iterator() { + if (i >= len) return ret._fulfill(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret; + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return NULL; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== NULL + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); - return new Promise(function (resolve, reject) { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { - if (error) { - reject('error in pbkdf2'); + return value; + } + + function ResourceList(length) { + this.length = length; + this.promise = null; + this[length-1] = null; + } + + ResourceList.prototype._resultCancelled = function() { + var len = this.length; + for (var i = 0; i < len; ++i) { + var item = this[i]; + if (item instanceof Promise) { + item.cancel(); + } + } + }; + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } + var resources = new ResourceList(len); + for (var i = 0; i < len; ++i) { + var resource = input[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); } else { - resolve(key.toString('hex')); + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } } + resources[i] = resource; + } + + var reflectedResources = new Array(resources.length); + for (var i = 0; i < reflectedResources.length; ++i) { + reflectedResources[i] = Promise.resolve(resources[i]).reflect(); + } + + var resultPromise = Promise.all(reflectedResources) + .then(function(inspections) { + for (var i = 0; i < inspections.length; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + errorObj.e = inspection.error(); + return errorObj; + } else if (!inspection.isFulfilled()) { + resultPromise.cancel(); + return; + } + inspections[i] = inspection.value(); + } + promise._pushContext(); + + fn = tryCatch(fn); + var ret = spreadArgs + ? fn.apply(undefined, inspections) : fn(inspections); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promiseCreated, "Promise.using", promise); + return ret; + }); + + var promise = resultPromise.lastly(function() { + var inspection = new Promise.PromiseInspection(resultPromise); + return dispose(resources, inspection); }); - }) -} + resources.promise = promise; + promise._setOnCancel(resources); + return promise; + }; -function _renderPassword(encryptedLogin, site, passwordOptions) { - return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - const template = passwordOptions.template || _getPasswordTemplate(passwordOptions); - return _prettyPrint(derivedEncryptedLogin, template); - }); -} + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 131072; + this._disposer = disposer; + }; -function _createHmac(encryptedLogin, salt) { - return new Promise(function (resolve) { - resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); - }); -} + Promise.prototype._isDisposable = function () { + return (this._bitField & 131072) > 0; + }; -function _deriveEncryptedLogin(encryptedLogin, site, options) { - var _options = options !== undefined ? options : {}; - var length = _options.length || 12; - var counter = _options.counter || 1; + Promise.prototype._getDisposer = function () { + return this._disposer; + }; - const salt = site + counter.toString(); - return _createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, length); - }); -} + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~131072); + this._disposer = undefined; + }; -function _getPasswordTemplate(passwordTypes) { - const templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); }; - let template = ''; - for (let templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] + +}; + +},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; + +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } } } - return template; + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + } -function _prettyPrint(hash, template) { - let password = ''; +function isObject(value) { + return typeof value === "function" || + typeof value === "object" && value !== null; +} - _string2charCodes(hash).forEach(function (charCode, index) { - const charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); } -function _string2charCodes(text) { - const charCodes = []; - for (let i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; } - return charCodes; + ret[i] = appendee; + return ret; } -function _getCharType(template, index) { - return template[index % template.length]; +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } } -function _getPasswordChar(charType, index) { - const passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true }; - const passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; + es5.defineProperty(obj, name, descriptor); + return obj; } -function createFingerprint(str) { - return new Promise(function (resolve) { - resolve(createHmac('sha256', new Buffer(str)).digest('hex')) - }); +function thrower(r) { + throw r; } -}).call(this,require("buffer").Buffer) -},{"buffer":5,"create-hmac":11,"pbkdf2":17}],2:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +})(); - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } } -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function FakeConstructor() {} + FakeConstructor.prototype = obj; + var l = 8; + while (l--) new FakeConstructor(); + return obj; + eval(obj); } -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} - arr = new Arr(len * 3 / 4 - placeHolders) +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} - var L = 0 +function isError(obj) { + return obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"; +} - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} - return arr +function canAttachTrace(obj) { + return isError(obj) && es5.propertyIsWritable(obj, "stack"); } -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); } -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } } -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 +var asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} - parts.push(output) +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; - return parts.join('') +function env(key, def) { + return isNode ? process.env[key] : def; } -},{}],3:[function(require,module,exports){ +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if ({}.toString.call(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +function domainBind(self, cb) { + return self.bind(cb); +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + domainBind: domainBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":13}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":21}],4:[function(require,module,exports){ -},{}],4:[function(require,module,exports){ +},{}],5:[function(require,module,exports){ (function (global){ 'use strict'; @@ -349,7 +5951,7 @@ exports.allocUnsafeSlow = function allocUnsafeSlow(size) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"buffer":5}],5:[function(require,module,exports){ +},{"buffer":6}],6:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -2142,7 +7744,7 @@ function isnan (val) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":2,"ieee754":13,"isarray":16}],6:[function(require,module,exports){ +},{"base64-js":2,"ieee754":14,"isarray":17}],7:[function(require,module,exports){ (function (Buffer){ var Transform = require('stream').Transform var inherits = require('inherits') @@ -2236,7 +7838,7 @@ CipherBase.prototype._toString = function (value, enc, fin) { } }).call(this,require("buffer").Buffer) -},{"buffer":5,"inherits":14,"stream":41,"string_decoder":42}],7:[function(require,module,exports){ +},{"buffer":6,"inherits":15,"stream":42,"string_decoder":43}],8:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -2347,7 +7949,7 @@ function objectToString(o) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":15}],8:[function(require,module,exports){ +},{"../../is-buffer/index.js":16}],9:[function(require,module,exports){ (function (Buffer){ 'use strict'; var inherits = require('inherits') @@ -2403,7 +8005,7 @@ module.exports = function createHash (alg) { } }).call(this,require("buffer").Buffer) -},{"./md5":10,"buffer":5,"cipher-base":6,"inherits":14,"ripemd160":32,"sha.js":34}],9:[function(require,module,exports){ +},{"./md5":11,"buffer":6,"cipher-base":7,"inherits":15,"ripemd160":33,"sha.js":35}],10:[function(require,module,exports){ (function (Buffer){ 'use strict'; var intSize = 4; @@ -2440,7 +8042,7 @@ function hash(buf, fn, hashSize, bigEndian) { } exports.hash = hash; }).call(this,require("buffer").Buffer) -},{"buffer":5}],10:[function(require,module,exports){ +},{"buffer":6}],11:[function(require,module,exports){ 'use strict'; /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message @@ -2597,7 +8199,7 @@ function bit_rol(num, cnt) module.exports = function md5(buf) { return helpers.hash(buf, core_md5, 16); }; -},{"./helpers":9}],11:[function(require,module,exports){ +},{"./helpers":10}],12:[function(require,module,exports){ (function (Buffer){ 'use strict'; var createHash = require('create-hash/browser'); @@ -2669,7 +8271,7 @@ module.exports = function createHmac(alg, key) { } }).call(this,require("buffer").Buffer) -},{"buffer":5,"create-hash/browser":8,"inherits":14,"stream":41}],12:[function(require,module,exports){ +},{"buffer":6,"create-hash/browser":9,"inherits":15,"stream":42}],13:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -2973,7 +8575,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],13:[function(require,module,exports){ +},{}],14:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -3059,7 +8661,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],14:[function(require,module,exports){ +},{}],15:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -3084,7 +8686,7 @@ if (typeof Object.create === 'function') { } } -},{}],15:[function(require,module,exports){ +},{}],16:[function(require,module,exports){ /*! * Determine if an object is a Buffer * @@ -3107,14 +8709,14 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -},{}],16:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],17:[function(require,module,exports){ +},{}],18:[function(require,module,exports){ (function (process,Buffer){ var createHmac = require('create-hmac') var checkParameters = require('./precondition') @@ -3186,7 +8788,7 @@ exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { } }).call(this,require('_process'),require("buffer").Buffer) -},{"./precondition":18,"_process":20,"buffer":5,"create-hmac":11}],18:[function(require,module,exports){ +},{"./precondition":19,"_process":21,"buffer":6,"create-hmac":12}],19:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { @@ -3206,7 +8808,7 @@ module.exports = function (iterations, keylen) { } } -},{}],19:[function(require,module,exports){ +},{}],20:[function(require,module,exports){ (function (process){ 'use strict'; @@ -3253,7 +8855,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":20}],20:[function(require,module,exports){ +},{"_process":21}],21:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -3435,10 +9037,10 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],21:[function(require,module,exports){ +},{}],22:[function(require,module,exports){ module.exports = require("./lib/_stream_duplex.js") -},{"./lib/_stream_duplex.js":22}],22:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":23}],23:[function(require,module,exports){ // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from @@ -3514,7 +9116,7 @@ function forEach(xs, f) { f(xs[i], i); } } -},{"./_stream_readable":24,"./_stream_writable":26,"core-util-is":7,"inherits":14,"process-nextick-args":19}],23:[function(require,module,exports){ +},{"./_stream_readable":25,"./_stream_writable":27,"core-util-is":8,"inherits":15,"process-nextick-args":20}],24:[function(require,module,exports){ // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. @@ -3541,7 +9143,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":25,"core-util-is":7,"inherits":14}],24:[function(require,module,exports){ +},{"./_stream_transform":26,"core-util-is":8,"inherits":15}],25:[function(require,module,exports){ (function (process){ 'use strict'; @@ -4481,7 +10083,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process')) -},{"./_stream_duplex":22,"./internal/streams/BufferList":27,"_process":20,"buffer":5,"buffer-shims":4,"core-util-is":7,"events":12,"inherits":14,"isarray":16,"process-nextick-args":19,"string_decoder/":42,"util":3}],25:[function(require,module,exports){ +},{"./_stream_duplex":23,"./internal/streams/BufferList":28,"_process":21,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"isarray":17,"process-nextick-args":20,"string_decoder/":43,"util":4}],26:[function(require,module,exports){ // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -4662,7 +10264,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":22,"core-util-is":7,"inherits":14}],26:[function(require,module,exports){ +},{"./_stream_duplex":23,"core-util-is":8,"inherits":15}],27:[function(require,module,exports){ (function (process){ // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all @@ -5191,7 +10793,7 @@ function CorkedRequest(state) { }; } }).call(this,require('_process')) -},{"./_stream_duplex":22,"_process":20,"buffer":5,"buffer-shims":4,"core-util-is":7,"events":12,"inherits":14,"process-nextick-args":19,"util-deprecate":43}],27:[function(require,module,exports){ +},{"./_stream_duplex":23,"_process":21,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"process-nextick-args":20,"util-deprecate":44}],28:[function(require,module,exports){ 'use strict'; var Buffer = require('buffer').Buffer; @@ -5256,10 +10858,10 @@ BufferList.prototype.concat = function (n) { } return ret; }; -},{"buffer":5,"buffer-shims":4}],28:[function(require,module,exports){ +},{"buffer":6,"buffer-shims":5}],29:[function(require,module,exports){ module.exports = require("./lib/_stream_passthrough.js") -},{"./lib/_stream_passthrough.js":23}],29:[function(require,module,exports){ +},{"./lib/_stream_passthrough.js":24}],30:[function(require,module,exports){ (function (process){ var Stream = (function (){ try { @@ -5279,13 +10881,13 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { } }).call(this,require('_process')) -},{"./lib/_stream_duplex.js":22,"./lib/_stream_passthrough.js":23,"./lib/_stream_readable.js":24,"./lib/_stream_transform.js":25,"./lib/_stream_writable.js":26,"_process":20}],30:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":23,"./lib/_stream_passthrough.js":24,"./lib/_stream_readable.js":25,"./lib/_stream_transform.js":26,"./lib/_stream_writable.js":27,"_process":21}],31:[function(require,module,exports){ module.exports = require("./lib/_stream_transform.js") -},{"./lib/_stream_transform.js":25}],31:[function(require,module,exports){ +},{"./lib/_stream_transform.js":26}],32:[function(require,module,exports){ module.exports = require("./lib/_stream_writable.js") -},{"./lib/_stream_writable.js":26}],32:[function(require,module,exports){ +},{"./lib/_stream_writable.js":27}],33:[function(require,module,exports){ (function (Buffer){ /* CryptoJS v3.1.2 @@ -5499,7 +11101,7 @@ function ripemd160 (message) { module.exports = ripemd160 }).call(this,require("buffer").Buffer) -},{"buffer":5}],33:[function(require,module,exports){ +},{"buffer":6}],34:[function(require,module,exports){ (function (Buffer){ // prototype class for hash functions function Hash (blockSize, finalSize) { @@ -5572,7 +11174,7 @@ Hash.prototype._update = function () { module.exports = Hash }).call(this,require("buffer").Buffer) -},{"buffer":5}],34:[function(require,module,exports){ +},{"buffer":6}],35:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() @@ -5589,7 +11191,7 @@ exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') -},{"./sha":35,"./sha1":36,"./sha224":37,"./sha256":38,"./sha384":39,"./sha512":40}],35:[function(require,module,exports){ +},{"./sha":36,"./sha1":37,"./sha224":38,"./sha256":39,"./sha384":40,"./sha512":41}],36:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined @@ -5686,7 +11288,7 @@ Sha.prototype._hash = function () { module.exports = Sha }).call(this,require("buffer").Buffer) -},{"./hash":33,"buffer":5,"inherits":14}],36:[function(require,module,exports){ +},{"./hash":34,"buffer":6,"inherits":15}],37:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined @@ -5788,7 +11390,7 @@ Sha1.prototype._hash = function () { module.exports = Sha1 }).call(this,require("buffer").Buffer) -},{"./hash":33,"buffer":5,"inherits":14}],37:[function(require,module,exports){ +},{"./hash":34,"buffer":6,"inherits":15}],38:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -5844,7 +11446,7 @@ Sha224.prototype._hash = function () { module.exports = Sha224 }).call(this,require("buffer").Buffer) -},{"./hash":33,"./sha256":38,"buffer":5,"inherits":14}],38:[function(require,module,exports){ +},{"./hash":34,"./sha256":39,"buffer":6,"inherits":15}],39:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -5982,7 +11584,7 @@ Sha256.prototype._hash = function () { module.exports = Sha256 }).call(this,require("buffer").Buffer) -},{"./hash":33,"buffer":5,"inherits":14}],39:[function(require,module,exports){ +},{"./hash":34,"buffer":6,"inherits":15}],40:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var SHA512 = require('./sha512') @@ -6042,7 +11644,7 @@ Sha384.prototype._hash = function () { module.exports = Sha384 }).call(this,require("buffer").Buffer) -},{"./hash":33,"./sha512":40,"buffer":5,"inherits":14}],40:[function(require,module,exports){ +},{"./hash":34,"./sha512":41,"buffer":6,"inherits":15}],41:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var Hash = require('./hash') @@ -6305,7 +11907,7 @@ Sha512.prototype._hash = function () { module.exports = Sha512 }).call(this,require("buffer").Buffer) -},{"./hash":33,"buffer":5,"inherits":14}],41:[function(require,module,exports){ +},{"./hash":34,"buffer":6,"inherits":15}],42:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -6434,7 +12036,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":12,"inherits":14,"readable-stream/duplex.js":21,"readable-stream/passthrough.js":28,"readable-stream/readable.js":29,"readable-stream/transform.js":30,"readable-stream/writable.js":31}],42:[function(require,module,exports){ +},{"events":13,"inherits":15,"readable-stream/duplex.js":22,"readable-stream/passthrough.js":29,"readable-stream/readable.js":30,"readable-stream/transform.js":31,"readable-stream/writable.js":32}],43:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -6657,7 +12259,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":5}],43:[function(require,module,exports){ +},{"buffer":6}],44:[function(require,module,exports){ (function (global){ /** diff --git a/package.json b/package.json index addd2cf..274a6cb 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "test:browser": "npm run build && karma start tests/karma.config.js" }, "dependencies": { + "bluebird": "^3.4.6", "create-hmac": "^1.1.4", "pbkdf2": "^3.0.9", "unibabel": "^2.1.3" @@ -38,7 +39,9 @@ "karma-chrome-launcher": "^2.0.0", "karma-firefox-launcher": "^1.0.0", "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", "mocha": "^3.1.2", + "phantomjs": "^2.1.7", "rimraf": "^2.5.4" } } diff --git a/tests/api.tests.js b/tests/api.tests.js index 1f27baa..18b345c 100644 --- a/tests/api.tests.js +++ b/tests/api.tests.js @@ -100,12 +100,12 @@ describe('LessPass', function () { } ]; - for (var entry of passwords) { + passwords.forEach(function (entry) { promises.push(LessPass.encryptLogin(entry.login, entry.masterPassword)); - } + }); - return Promise.all(promises).then(values => { - for (let i = 0; i < values.length; i++) { + return Promise.all(promises).then(function (values) { + for (var i = 0; i < values.length; i++) { assert.equal(passwords[i].encryptedLogin, values[i]); } }); @@ -312,7 +312,7 @@ describe('LessPass', function () { } ]; - for (var entry of passwords) { + passwords.forEach(function (entry) { var passwordOption = { counter: entry.counter, length: entry.length, @@ -322,10 +322,10 @@ describe('LessPass', function () { symbols: entry.symbols, }; promises.push(LessPass.renderPassword(entry.encryptedLogin, entry.site, passwordOption)); - } + }); - return Promise.all(promises).then(values => { - for (let i = 0; i < values.length; i++) { + return Promise.all(promises).then(function(values) { + for (var i = 0; i < values.length; i++) { assert.equal(passwords[i].generatedPassword, values[i]); } }); diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js index 24c8793..d7fea59 100644 --- a/tests/deriveEncryptedLogin.tests.js +++ b/tests/deriveEncryptedLogin.tests.js @@ -23,7 +23,7 @@ describe('LessPass', function () { }; var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); - Promise.all([p1, p2]).then(generatedPasswords => { + Promise.all([p1, p2]).then(function(generatedPasswords) { assert.equal(generatedPasswords[0], generatedPasswords[1]) }); }); @@ -45,7 +45,7 @@ describe('LessPass', function () { const site2 = 'facebook.com'; var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site2); - Promise.all([p1, p2]).then(derivedEncryptedLogins => { + Promise.all([p1, p2]).then(function(derivedEncryptedLogins) { assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) }); }); @@ -56,7 +56,7 @@ describe('LessPass', function () { const option2 = {counter: 2}; var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option2); - Promise.all([p1, p2]).then(derivedEncryptedLogins => { + Promise.all([p1, p2]).then(function(derivedEncryptedLogins) { assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) }); }); diff --git a/tests/karma.config.js b/tests/karma.config.js index efec162..8cb1241 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -1,8 +1,9 @@ module.exports = function (config) { - config.set({ + var configuration = { basePath: '..', frameworks: ['mocha', 'chai'], files: [ + 'node_modules/bluebird/js/browser/bluebird.core.min.js', 'lib/lesspass.js', 'tests/**/*.js' ], @@ -20,5 +21,9 @@ module.exports = function (config) { browsers: ['Chrome', 'Firefox'], singleRun: true, concurrency: Infinity - }) + }; + if (process.env.TRAVIS) { + configuration.browsers = ['PhantomJS']; + } + config.set(configuration) }; diff --git a/tests/karma.webcrypto.config.js b/tests/karma.webcrypto.config.js index ef9fad9..d7be84c 100644 --- a/tests/karma.webcrypto.config.js +++ b/tests/karma.webcrypto.config.js @@ -1,5 +1,5 @@ module.exports = function (config) { - config.set({ + var configuration = { basePath: '..', frameworks: ['mocha', 'chai'], files: [ @@ -22,5 +22,9 @@ module.exports = function (config) { browsers: ['Chrome', 'Firefox'], singleRun: true, concurrency: Infinity - }) + }; + if (process.env.TRAVIS) { + configuration.browsers = ['PhantomJS']; + } + config.set(configuration) }; diff --git a/tests/node.js b/tests/node.js index 6a510e0..40a8e28 100644 --- a/tests/node.js +++ b/tests/node.js @@ -15,12 +15,12 @@ var options = { }; LessPass.encryptLogin(login, masterPassword) - .then(encryptedLogin => { - LessPass.renderPassword(encryptedLogin, site, options).then(generatedPassword => { + .then(function(encryptedLogin) { + LessPass.renderPassword(encryptedLogin, site, options).then(function(generatedPassword) { assert.equal(generatedPassword, 'azYS7,olOL2]'); console.log('generated password ok'); }); }) - .catch(e => { + .catch(function(e) { console.log(e); }); \ No newline at end of file From d9a657c76c2d6a4f02b97b60e93bce56b8935916 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 15 Nov 2016 19:53:42 +0100 Subject: [PATCH 070/124] 5.2.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 274a6cb..46763ea 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.2.1", + "version": "5.2.2", "description": "LessPass node module used to generate LessPass passwords", "keywords": [ "crypto", From 1351820a5979bb48662d7ceaf859234bff46407b Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 11:30:26 +0100 Subject: [PATCH 071/124] clean tests remove done() functions --- tests/deriveEncryptedLogin.tests.js | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js index d7fea59..5c888f6 100644 --- a/tests/deriveEncryptedLogin.tests.js +++ b/tests/deriveEncryptedLogin.tests.js @@ -2,12 +2,11 @@ var assert = chai.assert; describe('LessPass', function () { describe('deriveEncryptedLogin', function () { - it('should createHmac', function (done) { + it('should createHmac', function () { var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; var salt = 'lesspass.com1'; - LessPass._createHmac(encryptedLogin, salt).then(function (hmac) { + return LessPass._createHmac(encryptedLogin, salt).then(function (hmac) { assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); - done(); }); }); it('should derive encrypted login with default options', function () { @@ -23,21 +22,20 @@ describe('LessPass', function () { }; var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); - Promise.all([p1, p2]).then(function(generatedPasswords) { + Promise.all([p1, p2]).then(function (generatedPasswords) { assert.equal(generatedPasswords[0], generatedPasswords[1]) }); }); - it('should derive encrypted login with defined length', function (done) { + it('should derive encrypted login with defined length', function () { var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; var site = 'lesspass.com'; var option = { counter: 1, length: 10, }; - LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { + return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { assert.equal(10, generatedPassword.length); - done(); - }) + }); }); it('should return two different passwords if site different', function () { const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; @@ -45,7 +43,7 @@ describe('LessPass', function () { const site2 = 'facebook.com'; var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site2); - Promise.all([p1, p2]).then(function(derivedEncryptedLogins) { + return Promise.all([p1, p2]).then(function (derivedEncryptedLogins) { assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) }); }); @@ -56,7 +54,7 @@ describe('LessPass', function () { const option2 = {counter: 2}; var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option2); - Promise.all([p1, p2]).then(function(derivedEncryptedLogins) { + return Promise.all([p1, p2]).then(function (derivedEncryptedLogins) { assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) }); }); From 1392e4889f08b737e1ac1238d17b9aa62327fb8f Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 11:30:54 +0100 Subject: [PATCH 072/124] add calcEntropy v2 method --- index.js | 4 +++- package.json | 2 +- src/v2.js | 18 ++++++++++++++++ tests/v2/entropy.tests.js | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 src/v2.js create mode 100644 tests/v2/entropy.tests.js diff --git a/index.js b/index.js index f742f94..82d1537 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,7 @@ var pbkdf2 = require('pbkdf2'); var createHmac = require('create-hmac'); var Promise = require("bluebird"); +var v2 = require('./src/v2'); module.exports = { encryptLogin: _encryptLogin, @@ -12,7 +13,8 @@ module.exports = { _string2charCodes: _string2charCodes, _getCharType: _getCharType, _getPasswordChar: _getPasswordChar, - _createHmac: _createHmac + _createHmac: _createHmac, + _calcEntropy: v2.calcEntropy }; function _encryptLogin(login, masterPassword, options) { diff --git a/package.json b/package.json index 46763ea..1cc8b70 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "scripts": { "build": "rimraf lib && mkdir lib && browserify --standalone LessPass index.js > lib/lesspass.js && gulp", "prepublish": "npm test && npm run build && npm run test:node && npm run test:browser", - "test": "mocha --require ./tests/helper.js tests", + "test": "mocha --require ./tests/helper.js tests/*", "test:node": "npm run build && cd tests && node node.js && cd ..", "test:webcrypto": "karma start tests/karma.webcrypto.config.js", "test:browser": "npm run build && karma start tests/karma.config.js" diff --git a/src/v2.js b/src/v2.js new file mode 100644 index 0000000..13c59cc --- /dev/null +++ b/src/v2.js @@ -0,0 +1,18 @@ +var Promise = require("bluebird"); +var pbkdf2 = require('pbkdf2'); + +exports.calcEntropy = function (site, login, masterPassword, passwordProfile) { + return new Promise(function (resolve, reject) { + var salt = site + login + passwordProfile.counter.toString(16); + var iterations = passwordProfile.iterations || 100000; + var keylen = passwordProfile.keylen || 32; + var digest = passwordProfile.digest || 'sha256'; + pbkdf2.pbkdf2(masterPassword, salt, iterations, keylen, digest, function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) +}; \ No newline at end of file diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js new file mode 100644 index 0000000..80897f0 --- /dev/null +++ b/tests/v2/entropy.tests.js @@ -0,0 +1,53 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('entropy', function () { + it('calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)', function () { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + counter: 1 + }; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); + }) + }); + + it('calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)', function () { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 8192, + keylen: 16, + digest: 'sha512', + counter: 1 + }; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); + }) + }); + + it('calc entropy different if counter different', function () { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile1 = { + iterations: 1, + counter: 1 + }; + var passwordProfile2 = { + iterations: 1, + counter: 2 + }; + var p1 = LessPass._calcEntropy(site, login, masterPassword, passwordProfile1); + var p2 = LessPass._calcEntropy(site, login, masterPassword, passwordProfile2); + return Promise.all([p1, p2]).then(function (entropies) { + assert.notEqual(entropies[0], entropies[1]) + }); + }); + + }); +}); \ No newline at end of file From 076d74f7d8da49695d71b77887e38459c76e06e9 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 12:01:09 +0100 Subject: [PATCH 073/124] add getSetOfCharacters v2 method --- index.js | 3 ++- src/v2.js | 21 ++++++++++++++++ tests/v2/setOfCharacters.tests.js | 52 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 tests/v2/setOfCharacters.tests.js diff --git a/index.js b/index.js index 82d1537..0065932 100644 --- a/index.js +++ b/index.js @@ -14,7 +14,8 @@ module.exports = { _getCharType: _getCharType, _getPasswordChar: _getPasswordChar, _createHmac: _createHmac, - _calcEntropy: v2.calcEntropy + _calcEntropy: v2.calcEntropy, + _getSetOfCharacters: v2.getSetOfCharacters, }; function _encryptLogin(login, masterPassword, options) { diff --git a/src/v2.js b/src/v2.js index 13c59cc..ca099d7 100644 --- a/src/v2.js +++ b/src/v2.js @@ -15,4 +15,25 @@ exports.calcEntropy = function (site, login, masterPassword, passwordProfile) { } }); }) +}; + +exports.getSetOfCharacters = function (passwordProfile) { + var subsetOfCharacters = { + lowercase: 'abcdefghijklmnopqrstuvwxyz', + uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + digits: '0123456789', + symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' + }; + + if (typeof passwordProfile === 'undefined') { + return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits; + } + + var setOfCharacters = ''; + ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { + if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { + setOfCharacters += subsetOfCharacters[subset] + } + }); + return setOfCharacters; }; \ No newline at end of file diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js new file mode 100644 index 0000000..cb4b933 --- /dev/null +++ b/tests/v2/setOfCharacters.tests.js @@ -0,0 +1,52 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('set of characters', function () { + it('get default set of characters', function () { + var setOfCharacters = LessPass._getSetOfCharacters(); + assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); + assert.equal(26 * 2 + 10, setOfCharacters.length); + }); + it('get default set of characters with object', function () { + var setOfCharacters = LessPass._getSetOfCharacters({ + lowercase: true, + uppercase: true, + digits: true, + symbols: false + }); + assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); + assert.equal(26 * 2 + 10, setOfCharacters.length); + }); + it('get set of characters only lowercase', function () { + var setOfCharacters = LessPass._getSetOfCharacters({lowercase: true}); + assert.equal('abcdefghijklmnopqrstuvwxyz', setOfCharacters); + assert.equal(26, setOfCharacters.length); + }); + it('get set of characters only uppercase', function () { + var setOfCharacters = LessPass._getSetOfCharacters({uppercase: true}); + assert.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); + assert.equal(26, setOfCharacters.length); + }); + it('get set of characters only digits', function () { + var setOfCharacters = LessPass._getSetOfCharacters({digits: true}); + assert.equal('0123456789', setOfCharacters); + assert.equal(10, setOfCharacters.length); + }); + it('get set of characters only symbols', function () { + var setOfCharacters = LessPass._getSetOfCharacters({symbols: true}); + assert.equal('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', setOfCharacters); + assert.equal(32, setOfCharacters.length); + }); + it('get set of characters concat two subsets', function () { + var setOfCharacters = LessPass._getSetOfCharacters({lowercase: true, uppercase: true}); + assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); + assert.equal(26 * 2, setOfCharacters.length); + }); + it('get set of characters doesn\'t care of key order in options', function () { + assert.equal( + LessPass._getSetOfCharacters({digits: true, symbols: true}), + LessPass._getSetOfCharacters({symbols: true, digits: true}) + ); + }); + }); +}); \ No newline at end of file From 6965c0dd41fa386fd58e45475d6eef9d3005376f Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 14:09:41 +0100 Subject: [PATCH 074/124] add render Password tests --- index.js | 1 + package.json | 1 + src/v2.js | 16 ++++++++++++++++ tests/v2/renderPassword.tests.js | 28 ++++++++++++++++++++++++++++ tests/v2/renderPassword.tests.py | 10 ++++++++++ 5 files changed, 56 insertions(+) create mode 100644 tests/v2/renderPassword.tests.js create mode 100644 tests/v2/renderPassword.tests.py diff --git a/index.js b/index.js index 0065932..2ef1268 100644 --- a/index.js +++ b/index.js @@ -16,6 +16,7 @@ module.exports = { _createHmac: _createHmac, _calcEntropy: v2.calcEntropy, _getSetOfCharacters: v2.getSetOfCharacters, + _renderPassword: v2.renderPassword, }; function _encryptLogin(login, masterPassword, options) { diff --git a/package.json b/package.json index 1cc8b70..5fec02c 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "test:browser": "npm run build && karma start tests/karma.config.js" }, "dependencies": { + "big-integer": "^1.6.17", "bluebird": "^3.4.6", "create-hmac": "^1.1.4", "pbkdf2": "^3.0.9", diff --git a/src/v2.js b/src/v2.js index ca099d7..d283bfb 100644 --- a/src/v2.js +++ b/src/v2.js @@ -1,5 +1,6 @@ var Promise = require("bluebird"); var pbkdf2 = require('pbkdf2'); +var bigInt = require("big-integer"); exports.calcEntropy = function (site, login, masterPassword, passwordProfile) { return new Promise(function (resolve, reject) { @@ -36,4 +37,19 @@ exports.getSetOfCharacters = function (passwordProfile) { } }); return setOfCharacters; +}; + +function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { + if (generatedPassword.length >= maxLength) { + return generatedPassword + } + var longDivision = quotient.divmod(setOfCharacters.length); + generatedPassword += setOfCharacters[longDivision.remainder]; + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) +} + +exports.renderPassword = function (entropy, setOfCharacters, passwordProfile) { + var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {}; + var length = _passwordProfile.length || 14; + return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); }; \ No newline at end of file diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js new file mode 100644 index 0000000..cbcde8e --- /dev/null +++ b/tests/v2/renderPassword.tests.js @@ -0,0 +1,28 @@ +var assert = chai.assert; + +describe('LessPass', function () { + it('render password use remainder of long division beetween entropy and set of chars length as an index ', function () { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + assert.equal('y', LessPass._renderPassword(entropy, setOfCharacters)[0]); + }); + it('render password use quotient as second entropy recursively', function () { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + assert.equal('5', LessPass._renderPassword(entropy, setOfCharacters)[1]); + }); + it('render password has default length of 14', function () { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + assert.equal(14, LessPass._renderPassword(entropy, setOfCharacters).length); + }); + it('render password can specify length', function () { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + var passwordProfile = { + length: 20 + }; + assert.equal(20, LessPass._renderPassword(entropy, setOfCharacters, passwordProfile).length); + }); + +}); \ No newline at end of file diff --git a/tests/v2/renderPassword.tests.py b/tests/v2/renderPassword.tests.py new file mode 100644 index 0000000..a8f7708 --- /dev/null +++ b/tests/v2/renderPassword.tests.py @@ -0,0 +1,10 @@ +def renderPassword(mdp, quotient, alphabet): + if len(mdp) > 14: + return mdp + quotient, remainder = divmod(quotient, len(alphabet)) + mdp += alphabet[remainder] + return renderPassword(mdp, quotient, alphabet) + + +alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' +print(renderPassword('', int('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', 16), alphabet)) From ceced2911390afbf94992874d7b0d478790bddb8 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 15:22:42 +0100 Subject: [PATCH 075/124] add generatePassword v2 method --- index.js | 7 +++-- src/v2.js | 34 ++++++++++++++++------- tests/v2/api.tests.js | 58 +++++++++++++++++++++++++++++++++++++++ tests/v2/entropy.tests.js | 4 +-- tests/v2/renderPassword.tests.js | 2 +- tests/v2/setOfCharacters.tests.js | 2 +- 6 files changed, 90 insertions(+), 17 deletions(-) create mode 100644 tests/v2/api.tests.js diff --git a/index.js b/index.js index 2ef1268..9d05e75 100644 --- a/index.js +++ b/index.js @@ -14,9 +14,10 @@ module.exports = { _getCharType: _getCharType, _getPasswordChar: _getPasswordChar, _createHmac: _createHmac, - _calcEntropy: v2.calcEntropy, - _getSetOfCharacters: v2.getSetOfCharacters, - _renderPassword: v2.renderPassword, + generatePassword: v2.generatePassword, + _calcEntropy: v2._calcEntropy, + _getSetOfCharacters: v2._getSetOfCharacters, + _renderPassword: v2._renderPassword, }; function _encryptLogin(login, masterPassword, options) { diff --git a/src/v2.js b/src/v2.js index d283bfb..6c096ad 100644 --- a/src/v2.js +++ b/src/v2.js @@ -2,7 +2,21 @@ var Promise = require("bluebird"); var pbkdf2 = require('pbkdf2'); var bigInt = require("big-integer"); -exports.calcEntropy = function (site, login, masterPassword, passwordProfile) { +exports.generatePassword = generatePassword; + +function generatePassword(site, login, masterPassword, passwordProfile) { + return _calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + var setOfCharacters = _getSetOfCharacters(passwordProfile); + return _renderPassword(entropy, setOfCharacters, passwordProfile) + }); +} + +exports._calcEntropy = _calcEntropy; +exports._getSetOfCharacters = _getSetOfCharacters; +exports._renderPassword = _renderPassword; + + +function _calcEntropy(site, login, masterPassword, passwordProfile) { return new Promise(function (resolve, reject) { var salt = site + login + passwordProfile.counter.toString(16); var iterations = passwordProfile.iterations || 100000; @@ -15,10 +29,10 @@ exports.calcEntropy = function (site, login, masterPassword, passwordProfile) { resolve(key.toString('hex')); } }); - }) -}; + }); +} -exports.getSetOfCharacters = function (passwordProfile) { +function _getSetOfCharacters(passwordProfile) { var subsetOfCharacters = { lowercase: 'abcdefghijklmnopqrstuvwxyz', uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', @@ -37,19 +51,19 @@ exports.getSetOfCharacters = function (passwordProfile) { } }); return setOfCharacters; -}; +} -function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { +function _consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { if (generatedPassword.length >= maxLength) { return generatedPassword } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) + return _consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) } -exports.renderPassword = function (entropy, setOfCharacters, passwordProfile) { +function _renderPassword(entropy, setOfCharacters, passwordProfile) { var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {}; var length = _passwordProfile.length || 14; - return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); -}; \ No newline at end of file + return _consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); +} diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js new file mode 100644 index 0000000..e8a59f1 --- /dev/null +++ b/tests/v2/api.tests.js @@ -0,0 +1,58 @@ +var assert = chai.assert; + +describe('LessPass v2', function () { + describe('API', function () { + it('render password', function () { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 100000, + lowercase: true, + uppercase: true, + digits: true, + symbols: false, + length: 14, + counter: 1 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { + assert.equal('y5m7Ctw2695ksh', generatedPassword); + }); + }); + it('render password only digit', function () { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 100000, + lowercase: false, + uppercase: false, + digits: true, + symbols: false, + length: 6, + counter: 1 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { + assert.equal('874236', generatedPassword); + }); + }); + it('render password no number', function () { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 100000, + lowercase: true, + uppercase: true, + digits: false, + symbols: true, + length: 14, + counter: 1 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { + assert.equal("s>{F}wN/-fmMX?", generatedPassword); + }); + }); + }); +}); + diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index 80897f0..5554af8 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -1,6 +1,6 @@ var assert = chai.assert; -describe('LessPass', function () { +describe('LessPass v2', function () { describe('entropy', function () { it('calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)', function () { this.timeout(10000); @@ -12,7 +12,7 @@ describe('LessPass', function () { }; return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); - }) + }); }); it('calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)', function () { diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js index cbcde8e..1a5a400 100644 --- a/tests/v2/renderPassword.tests.js +++ b/tests/v2/renderPassword.tests.js @@ -1,6 +1,6 @@ var assert = chai.assert; -describe('LessPass', function () { +describe('LessPass v2', function () { it('render password use remainder of long division beetween entropy and set of chars length as an index ', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js index cb4b933..f2ca649 100644 --- a/tests/v2/setOfCharacters.tests.js +++ b/tests/v2/setOfCharacters.tests.js @@ -1,6 +1,6 @@ var assert = chai.assert; -describe('LessPass', function () { +describe('LessPass v2', function () { describe('set of characters', function () { it('get default set of characters', function () { var setOfCharacters = LessPass._getSetOfCharacters(); From 997b8a5d811304ed33465697c235c5f14b895a2a Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 15:28:00 +0100 Subject: [PATCH 076/124] rename file that is not a test --- tests/v2/debug.py | 10 ++++++++++ tests/v2/renderPassword.tests.py | 10 ---------- 2 files changed, 10 insertions(+), 10 deletions(-) create mode 100644 tests/v2/debug.py delete mode 100644 tests/v2/renderPassword.tests.py diff --git a/tests/v2/debug.py b/tests/v2/debug.py new file mode 100644 index 0000000..a8f7708 --- /dev/null +++ b/tests/v2/debug.py @@ -0,0 +1,10 @@ +def renderPassword(mdp, quotient, alphabet): + if len(mdp) > 14: + return mdp + quotient, remainder = divmod(quotient, len(alphabet)) + mdp += alphabet[remainder] + return renderPassword(mdp, quotient, alphabet) + + +alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' +print(renderPassword('', int('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', 16), alphabet)) diff --git a/tests/v2/renderPassword.tests.py b/tests/v2/renderPassword.tests.py deleted file mode 100644 index a8f7708..0000000 --- a/tests/v2/renderPassword.tests.py +++ /dev/null @@ -1,10 +0,0 @@ -def renderPassword(mdp, quotient, alphabet): - if len(mdp) > 14: - return mdp - quotient, remainder = divmod(quotient, len(alphabet)) - mdp += alphabet[remainder] - return renderPassword(mdp, quotient, alphabet) - - -alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' -print(renderPassword('', int('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', 16), alphabet)) From 011fb613b2f6e4693ea5e96defe308a0bb8760a9 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 16:14:10 +0100 Subject: [PATCH 077/124] remove underscore from hidden methods --- src/v2.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/v2.js b/src/v2.js index 6c096ad..9fad7d9 100644 --- a/src/v2.js +++ b/src/v2.js @@ -5,18 +5,18 @@ var bigInt = require("big-integer"); exports.generatePassword = generatePassword; function generatePassword(site, login, masterPassword, passwordProfile) { - return _calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - var setOfCharacters = _getSetOfCharacters(passwordProfile); - return _renderPassword(entropy, setOfCharacters, passwordProfile) + return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + var setOfCharacters = getSetOfCharacters(passwordProfile); + return renderPassword(entropy, setOfCharacters, passwordProfile) }); } -exports._calcEntropy = _calcEntropy; -exports._getSetOfCharacters = _getSetOfCharacters; -exports._renderPassword = _renderPassword; +exports._calcEntropy = calcEntropy; +exports._getSetOfCharacters = getSetOfCharacters; +exports._renderPassword = renderPassword; -function _calcEntropy(site, login, masterPassword, passwordProfile) { +function calcEntropy(site, login, masterPassword, passwordProfile) { return new Promise(function (resolve, reject) { var salt = site + login + passwordProfile.counter.toString(16); var iterations = passwordProfile.iterations || 100000; @@ -32,7 +32,7 @@ function _calcEntropy(site, login, masterPassword, passwordProfile) { }); } -function _getSetOfCharacters(passwordProfile) { +function getSetOfCharacters(passwordProfile) { var subsetOfCharacters = { lowercase: 'abcdefghijklmnopqrstuvwxyz', uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', @@ -53,17 +53,17 @@ function _getSetOfCharacters(passwordProfile) { return setOfCharacters; } -function _consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { +function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { if (generatedPassword.length >= maxLength) { return generatedPassword } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; - return _consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) } -function _renderPassword(entropy, setOfCharacters, passwordProfile) { +function renderPassword(entropy, setOfCharacters, passwordProfile) { var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {}; var length = _passwordProfile.length || 14; - return _consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); + return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); } From f03a7d74e9c14a6233e45c7e35567ff95dd6aafb Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Fri, 18 Nov 2016 16:29:52 +0100 Subject: [PATCH 078/124] refactor code --- index.js | 130 +--- lib/lesspass.js | 1634 ++++++++++++++++++++++++++++++++++++++++++++----- src/v1.js | 121 ++++ src/v2.js | 12 +- tests/v2/api.tests.js | 3 + 5 files changed, 1615 insertions(+), 285 deletions(-) create mode 100644 src/v1.js diff --git a/index.js b/index.js index 9d05e75..78e7455 100644 --- a/index.js +++ b/index.js @@ -1,124 +1,20 @@ -var pbkdf2 = require('pbkdf2'); -var createHmac = require('create-hmac'); -var Promise = require("bluebird"); +var v1 = require('./src/v1'); var v2 = require('./src/v2'); module.exports = { - encryptLogin: _encryptLogin, - renderPassword: _renderPassword, - createFingerprint: createFingerprint, - _deriveEncryptedLogin: _deriveEncryptedLogin, - _getPasswordTemplate: _getPasswordTemplate, - _prettyPrint: _prettyPrint, - _string2charCodes: _string2charCodes, - _getCharType: _getCharType, - _getPasswordChar: _getPasswordChar, - _createHmac: _createHmac, + encryptLogin: v1.encryptLogin, + renderPassword: v1.renderPassword, + createFingerprint: v1.createFingerprint, + _deriveEncryptedLogin: v1._deriveEncryptedLogin, + _getPasswordTemplate: v1._getPasswordTemplate, + _prettyPrint: v1._prettyPrint, + _string2charCodes: v1._string2charCodes, + _getCharType: v1._getCharType, + _getPasswordChar: v1._getPasswordChar, + _createHmac: v1._createHmac, + generatePassword: v2.generatePassword, _calcEntropy: v2._calcEntropy, _getSetOfCharacters: v2._getSetOfCharacters, _renderPassword: v2._renderPassword, -}; - -function _encryptLogin(login, masterPassword, options) { - var _options = options !== undefined ? options : {}; - var iterations = _options.iterations || 8192; - var keylen = _options.keylen || 32; - - return new Promise(function (resolve, reject) { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); - } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }) -} - -function _renderPassword(encryptedLogin, site, passwordOptions) { - return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = passwordOptions.template || _getPasswordTemplate(passwordOptions); - return _prettyPrint(derivedEncryptedLogin, template); - }); -} - -function _createHmac(encryptedLogin, salt) { - return new Promise(function (resolve) { - resolve(createHmac('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); - }); -} - -function _deriveEncryptedLogin(encryptedLogin, site, options) { - var _options = options !== undefined ? options : {}; - var length = _options.length || 12; - var counter = _options.counter || 1; - - var salt = site + counter.toString(); - return _createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, length); - }); -} - -function _getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - var returnedTemplate = ''; - Object.keys(templates).forEach(function (template) { - if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { - returnedTemplate += templates[template] - } - }); - return returnedTemplate; -} - -function _prettyPrint(hash, template) { - var password = ''; - - _string2charCodes(hash).forEach(function (charCode, index) { - var charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; -} - -function _string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} - -function _getCharType(template, index) { - return template[index % template.length]; -} - -function _getPasswordChar(charType, index) { - var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; -} - -function createFingerprint(str) { - return new Promise(function (resolve) { - resolve(createHmac('sha256', new Buffer(str)).digest('hex')) - }); -} \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/lesspass.js b/lib/lesspass.js index 714c2a3..38e2162 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -1,126 +1,25 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LessPass = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var value, n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value, isSmall; + if (compareAbs(a, b) >= 0) { + value = subtract(a,b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var value, n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + function square(a) { + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + for (var j = 0; j < l; j++) { + a_j = a[j]; + product = a_i * a_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + var value = n.value; + if (value === 0) return false; + if (value === 1) return true; + if (value === 2) return this.isEven(); + return this.mod(n).equals(Integer[0]); + }; + SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(25)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + BigInteger.prototype.isPrime = function () { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(), + nPrev = n.prev(); + var a = [2, 3, 5, 7, 11, 13, 17, 19], + b = nPrev, + d, t, i, x; + while (b.isEven()) b = b.divide(2); + for (i = 0; i < a.length; i++) { + x = bigInt(a[i]).modPow(b, n); + if (x.equals(Integer[1]) || x.equals(nPrev)) continue; + for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) { + x = x.square().mod(n); + if (x.equals(nPrev)) t = false; + } + if (t) return false; + } + return true; + }; + SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + // use the Fermat primality test + for (var i = 0; i < t; i++) { + var a = bigInt.randBetween(2, n.minus(2)); + if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite + } + return true; // large chance of being prime + }; + SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.equals(bigInt.zero)) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + return t; + } + SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + + var powersOfTwo = [1]; + while (powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) || + (n instanceof BigInteger && n.value.length <= 1); + } + + BigInteger.prototype.shiftLeft = function (n) { + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftRight(-n); + var result = this; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (n) { + var remQuo; + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero()) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xBits = [], yBits = []; + var xStop = false, yStop = false; + while (!xStop || !yStop) { + if (xRem.isZero()) { // virtual sign extension for simulating two's complement + xStop = true; + xBits.push(xSign ? 1 : 0); + } + else if (xSign) xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers + else xBits.push(xRem.isEven() ? 0 : 1); + + if (yRem.isZero()) { + yStop = true; + yBits.push(ySign ? 1 : 0); + } + else if (ySign) yBits.push(yRem.isEven() ? 1 : 0); + else yBits.push(yRem.isEven() ? 0 : 1); + + xRem = xRem.over(2); + yRem = yRem.over(2); + } + var result = []; + for (var i = 0; i < xBits.length; i++) result.push(fn(xBits[i], yBits[i])); + var sum = bigInt(result.pop()).negate().times(bigInt(2).pow(result.length)); + while (result.length) { + sum = sum.add(bigInt(result.pop()).times(bigInt(2).pow(result.length))); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a,b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = Math.min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b) { + a = parseValue(a); + b = parseValue(b); + var low = min(a, b), high = max(a, b); + var range = high.subtract(low); + if (range.isSmall) return low.add(Math.round(Math.random() * range)); + var length = range.value.length - 1; + var result = [], restricted = true; + for (var i = length; i >= 0; i--) { + var top = restricted ? range.value[i] : BASE; + var digit = truncate(Math.random() * top); + result.unshift(digit); + if (digit < top) restricted = false; + } + result = arrayToSmall(result); + return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false)); + } + var parseBase = function (text, base) { + var val = Integer[0], pow = Integer[1], + length = text.length; + if (2 <= base && base <= 36) { + if (length <= LOG_MAX_INT / Math.log(base)) { + return new SmallInteger(parseInt(text, base)); + } + } + base = parseValue(base); + var digits = []; + var i; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i].toLowerCase(), + charCode = c.charCodeAt(0); + if (48 <= charCode && charCode <= 57) digits.push(parseValue(c)); + else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87)); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">"); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + digits.reverse(); + for (i = 0; i < digits.length; i++) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + }; + + function stringify(digit) { + var v = digit.value; + if (typeof v === "number") v = [v]; + if (v.length === 1 && v[0] <= 35) { + return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]); + } + return "<" + v + ">"; + } + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return "0"; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return "0"; + if (n.isNegative()) return new Array(1 - n).join("10"); + return "1" + new Array(+n).join("01"); + } + var minusSign = ""; + if (n.isNegative() && base.isPositive()) { + minusSign = "-"; + n = n.abs(); + } + if (base.equals(1)) { + if (n.isZero()) return "0"; + return minusSign + new Array(+n + 1).join(1); + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(stringify(digit)); + } + out.push(stringify(left)); + return minusSign + out.reverse().join(""); + } + + BigInteger.prototype.toString = function (radix) { + if (radix === undefined) radix = 10; + if (radix !== 10) return toBase(this, radix); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + SmallInteger.prototype.toString = function (radix) { + if (radix === undefined) radix = 10; + if (radix != 10) return toBase(this, radix); + return String(this.value); + }; + + BigInteger.prototype.valueOf = function () { + return +this.toString(); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return new SmallInteger(x); + throw "Invalid integer: " + v; + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = new SmallInteger(i); + if (i > 0) Integer[-i] = new SmallInteger(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; }; + Integer.randBetween = randBetween; + return Integer; +})(); + +// Node.js check +if (typeof module !== "undefined" && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +},{}],4:[function(require,module,exports){ (function (process,global){ /* @preserve * The MIT License (MIT) @@ -5837,9 +6952,9 @@ module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":21}],4:[function(require,module,exports){ +},{"_process":22}],5:[function(require,module,exports){ -},{}],5:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ (function (global){ 'use strict'; @@ -5951,7 +7066,7 @@ exports.allocUnsafeSlow = function allocUnsafeSlow(size) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"buffer":6}],6:[function(require,module,exports){ +},{"buffer":7}],7:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -7744,7 +8859,7 @@ function isnan (val) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":2,"ieee754":14,"isarray":17}],7:[function(require,module,exports){ +},{"base64-js":2,"ieee754":15,"isarray":18}],8:[function(require,module,exports){ (function (Buffer){ var Transform = require('stream').Transform var inherits = require('inherits') @@ -7838,7 +8953,7 @@ CipherBase.prototype._toString = function (value, enc, fin) { } }).call(this,require("buffer").Buffer) -},{"buffer":6,"inherits":15,"stream":42,"string_decoder":43}],8:[function(require,module,exports){ +},{"buffer":7,"inherits":16,"stream":43,"string_decoder":44}],9:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -7949,7 +9064,7 @@ function objectToString(o) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":16}],9:[function(require,module,exports){ +},{"../../is-buffer/index.js":17}],10:[function(require,module,exports){ (function (Buffer){ 'use strict'; var inherits = require('inherits') @@ -8005,7 +9120,7 @@ module.exports = function createHash (alg) { } }).call(this,require("buffer").Buffer) -},{"./md5":11,"buffer":6,"cipher-base":7,"inherits":15,"ripemd160":33,"sha.js":35}],10:[function(require,module,exports){ +},{"./md5":12,"buffer":7,"cipher-base":8,"inherits":16,"ripemd160":34,"sha.js":36}],11:[function(require,module,exports){ (function (Buffer){ 'use strict'; var intSize = 4; @@ -8042,7 +9157,7 @@ function hash(buf, fn, hashSize, bigEndian) { } exports.hash = hash; }).call(this,require("buffer").Buffer) -},{"buffer":6}],11:[function(require,module,exports){ +},{"buffer":7}],12:[function(require,module,exports){ 'use strict'; /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message @@ -8199,7 +9314,7 @@ function bit_rol(num, cnt) module.exports = function md5(buf) { return helpers.hash(buf, core_md5, 16); }; -},{"./helpers":10}],12:[function(require,module,exports){ +},{"./helpers":11}],13:[function(require,module,exports){ (function (Buffer){ 'use strict'; var createHash = require('create-hash/browser'); @@ -8271,7 +9386,7 @@ module.exports = function createHmac(alg, key) { } }).call(this,require("buffer").Buffer) -},{"buffer":6,"create-hash/browser":9,"inherits":15,"stream":42}],13:[function(require,module,exports){ +},{"buffer":7,"create-hash/browser":10,"inherits":16,"stream":43}],14:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -8575,7 +9690,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],14:[function(require,module,exports){ +},{}],15:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -8661,7 +9776,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],15:[function(require,module,exports){ +},{}],16:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -8686,7 +9801,7 @@ if (typeof Object.create === 'function') { } } -},{}],16:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ /*! * Determine if an object is a Buffer * @@ -8709,14 +9824,14 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -},{}],17:[function(require,module,exports){ +},{}],18:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],18:[function(require,module,exports){ +},{}],19:[function(require,module,exports){ (function (process,Buffer){ var createHmac = require('create-hmac') var checkParameters = require('./precondition') @@ -8788,7 +9903,7 @@ exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { } }).call(this,require('_process'),require("buffer").Buffer) -},{"./precondition":19,"_process":21,"buffer":6,"create-hmac":12}],19:[function(require,module,exports){ +},{"./precondition":20,"_process":22,"buffer":7,"create-hmac":13}],20:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { @@ -8808,7 +9923,7 @@ module.exports = function (iterations, keylen) { } } -},{}],20:[function(require,module,exports){ +},{}],21:[function(require,module,exports){ (function (process){ 'use strict'; @@ -8855,7 +9970,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":21}],21:[function(require,module,exports){ +},{"_process":22}],22:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -9037,10 +10152,10 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],22:[function(require,module,exports){ +},{}],23:[function(require,module,exports){ module.exports = require("./lib/_stream_duplex.js") -},{"./lib/_stream_duplex.js":23}],23:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":24}],24:[function(require,module,exports){ // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from @@ -9116,7 +10231,7 @@ function forEach(xs, f) { f(xs[i], i); } } -},{"./_stream_readable":25,"./_stream_writable":27,"core-util-is":8,"inherits":15,"process-nextick-args":20}],24:[function(require,module,exports){ +},{"./_stream_readable":26,"./_stream_writable":28,"core-util-is":9,"inherits":16,"process-nextick-args":21}],25:[function(require,module,exports){ // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. @@ -9143,7 +10258,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":26,"core-util-is":8,"inherits":15}],25:[function(require,module,exports){ +},{"./_stream_transform":27,"core-util-is":9,"inherits":16}],26:[function(require,module,exports){ (function (process){ 'use strict'; @@ -10083,7 +11198,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process')) -},{"./_stream_duplex":23,"./internal/streams/BufferList":28,"_process":21,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"isarray":17,"process-nextick-args":20,"string_decoder/":43,"util":4}],26:[function(require,module,exports){ +},{"./_stream_duplex":24,"./internal/streams/BufferList":29,"_process":22,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"isarray":18,"process-nextick-args":21,"string_decoder/":44,"util":5}],27:[function(require,module,exports){ // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -10264,7 +11379,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":23,"core-util-is":8,"inherits":15}],27:[function(require,module,exports){ +},{"./_stream_duplex":24,"core-util-is":9,"inherits":16}],28:[function(require,module,exports){ (function (process){ // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all @@ -10793,7 +11908,7 @@ function CorkedRequest(state) { }; } }).call(this,require('_process')) -},{"./_stream_duplex":23,"_process":21,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"process-nextick-args":20,"util-deprecate":44}],28:[function(require,module,exports){ +},{"./_stream_duplex":24,"_process":22,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"process-nextick-args":21,"util-deprecate":45}],29:[function(require,module,exports){ 'use strict'; var Buffer = require('buffer').Buffer; @@ -10858,10 +11973,10 @@ BufferList.prototype.concat = function (n) { } return ret; }; -},{"buffer":6,"buffer-shims":5}],29:[function(require,module,exports){ +},{"buffer":7,"buffer-shims":6}],30:[function(require,module,exports){ module.exports = require("./lib/_stream_passthrough.js") -},{"./lib/_stream_passthrough.js":24}],30:[function(require,module,exports){ +},{"./lib/_stream_passthrough.js":25}],31:[function(require,module,exports){ (function (process){ var Stream = (function (){ try { @@ -10881,13 +11996,13 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { } }).call(this,require('_process')) -},{"./lib/_stream_duplex.js":23,"./lib/_stream_passthrough.js":24,"./lib/_stream_readable.js":25,"./lib/_stream_transform.js":26,"./lib/_stream_writable.js":27,"_process":21}],31:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":24,"./lib/_stream_passthrough.js":25,"./lib/_stream_readable.js":26,"./lib/_stream_transform.js":27,"./lib/_stream_writable.js":28,"_process":22}],32:[function(require,module,exports){ module.exports = require("./lib/_stream_transform.js") -},{"./lib/_stream_transform.js":26}],32:[function(require,module,exports){ +},{"./lib/_stream_transform.js":27}],33:[function(require,module,exports){ module.exports = require("./lib/_stream_writable.js") -},{"./lib/_stream_writable.js":27}],33:[function(require,module,exports){ +},{"./lib/_stream_writable.js":28}],34:[function(require,module,exports){ (function (Buffer){ /* CryptoJS v3.1.2 @@ -11101,7 +12216,7 @@ function ripemd160 (message) { module.exports = ripemd160 }).call(this,require("buffer").Buffer) -},{"buffer":6}],34:[function(require,module,exports){ +},{"buffer":7}],35:[function(require,module,exports){ (function (Buffer){ // prototype class for hash functions function Hash (blockSize, finalSize) { @@ -11174,7 +12289,7 @@ Hash.prototype._update = function () { module.exports = Hash }).call(this,require("buffer").Buffer) -},{"buffer":6}],35:[function(require,module,exports){ +},{"buffer":7}],36:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() @@ -11191,7 +12306,7 @@ exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') -},{"./sha":36,"./sha1":37,"./sha224":38,"./sha256":39,"./sha384":40,"./sha512":41}],36:[function(require,module,exports){ +},{"./sha":37,"./sha1":38,"./sha224":39,"./sha256":40,"./sha384":41,"./sha512":42}],37:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined @@ -11288,7 +12403,7 @@ Sha.prototype._hash = function () { module.exports = Sha }).call(this,require("buffer").Buffer) -},{"./hash":34,"buffer":6,"inherits":15}],37:[function(require,module,exports){ +},{"./hash":35,"buffer":7,"inherits":16}],38:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined @@ -11390,7 +12505,7 @@ Sha1.prototype._hash = function () { module.exports = Sha1 }).call(this,require("buffer").Buffer) -},{"./hash":34,"buffer":6,"inherits":15}],38:[function(require,module,exports){ +},{"./hash":35,"buffer":7,"inherits":16}],39:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -11446,7 +12561,7 @@ Sha224.prototype._hash = function () { module.exports = Sha224 }).call(this,require("buffer").Buffer) -},{"./hash":34,"./sha256":39,"buffer":6,"inherits":15}],39:[function(require,module,exports){ +},{"./hash":35,"./sha256":40,"buffer":7,"inherits":16}],40:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -11584,7 +12699,7 @@ Sha256.prototype._hash = function () { module.exports = Sha256 }).call(this,require("buffer").Buffer) -},{"./hash":34,"buffer":6,"inherits":15}],40:[function(require,module,exports){ +},{"./hash":35,"buffer":7,"inherits":16}],41:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var SHA512 = require('./sha512') @@ -11644,7 +12759,7 @@ Sha384.prototype._hash = function () { module.exports = Sha384 }).call(this,require("buffer").Buffer) -},{"./hash":34,"./sha512":41,"buffer":6,"inherits":15}],41:[function(require,module,exports){ +},{"./hash":35,"./sha512":42,"buffer":7,"inherits":16}],42:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var Hash = require('./hash') @@ -11907,7 +13022,7 @@ Sha512.prototype._hash = function () { module.exports = Sha512 }).call(this,require("buffer").Buffer) -},{"./hash":34,"buffer":6,"inherits":15}],42:[function(require,module,exports){ +},{"./hash":35,"buffer":7,"inherits":16}],43:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -12036,7 +13151,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":13,"inherits":15,"readable-stream/duplex.js":22,"readable-stream/passthrough.js":29,"readable-stream/readable.js":30,"readable-stream/transform.js":31,"readable-stream/writable.js":32}],43:[function(require,module,exports){ +},{"events":14,"inherits":16,"readable-stream/duplex.js":23,"readable-stream/passthrough.js":30,"readable-stream/readable.js":31,"readable-stream/transform.js":32,"readable-stream/writable.js":33}],44:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -12259,7 +13374,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":6}],44:[function(require,module,exports){ +},{"buffer":7}],45:[function(require,module,exports){ (function (global){ /** @@ -12330,5 +13445,200 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}]},{},[1])(1) +},{}],46:[function(require,module,exports){ +(function (Buffer){ +var pbkdf2 = require('pbkdf2'); +var createHMAC = require('create-hmac'); +var Promise = require("bluebird"); + + +module.exports = { + encryptLogin: encryptLogin, + renderPassword: renderPassword, + createFingerprint: createFingerprint, + _deriveEncryptedLogin: deriveEncryptedLogin, + _getPasswordTemplate: getPasswordTemplate, + _prettyPrint: prettyPrint, + _string2charCodes: string2charCodes, + _getCharType: getCharType, + _getPasswordChar: getPasswordChar, + _createHmac: createHmac, +}; + + +function encryptLogin(login, masterPassword, options) { + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + + return new Promise(function (resolve, reject) { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) +} + +function renderPassword(encryptedLogin, site, passwordOptions) { + return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = passwordOptions.template || getPasswordTemplate(passwordOptions); + return prettyPrint(derivedEncryptedLogin, template); + }); +} + +function createHmac(encryptedLogin, salt) { + return new Promise(function (resolve) { + resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + }); +} + +function deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; + + var salt = site + counter.toString(); + return createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, length); + }); +} + +function getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var returnedTemplate = ''; + Object.keys(templates).forEach(function (template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template] + } + }); + return returnedTemplate; +} + +function prettyPrint(hash, template) { + var password = ''; + + string2charCodes(hash).forEach(function (charCode, index) { + var charType = getCharType(template, index); + password += getPasswordChar(charType, charCode); + }); + return password; +} + +function string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function getCharType(template, index) { + return template[index % template.length]; +} + +function getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function createFingerprint(str) { + return new Promise(function (resolve) { + resolve(createHMAC('sha256', new Buffer(str)).digest('hex')) + }); +} +}).call(this,require("buffer").Buffer) +},{"bluebird":4,"buffer":7,"create-hmac":13,"pbkdf2":19}],47:[function(require,module,exports){ +var Promise = require("bluebird"); +var pbkdf2 = require('pbkdf2'); +var bigInt = require("big-integer"); + +module.exports = { + generatePassword: generatePassword, + _calcEntropy: calcEntropy, + _getSetOfCharacters: getSetOfCharacters, + _renderPassword: renderPassword +}; + +function generatePassword(site, login, masterPassword, passwordProfile) { + return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + var setOfCharacters = getSetOfCharacters(passwordProfile); + return renderPassword(entropy, setOfCharacters, passwordProfile) + }); +} + +function calcEntropy(site, login, masterPassword, passwordProfile) { + return new Promise(function (resolve, reject) { + var salt = site + login + passwordProfile.counter.toString(16); + var iterations = passwordProfile.iterations || 100000; + var keylen = passwordProfile.keylen || 32; + var digest = passwordProfile.digest || 'sha256'; + pbkdf2.pbkdf2(masterPassword, salt, iterations, keylen, digest, function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); +} + +function getSetOfCharacters(passwordProfile) { + var subsetOfCharacters = { + lowercase: 'abcdefghijklmnopqrstuvwxyz', + uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + digits: '0123456789', + symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' + }; + + if (typeof passwordProfile === 'undefined') { + return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits; + } + + var setOfCharacters = ''; + ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { + if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { + setOfCharacters += subsetOfCharacters[subset] + } + }); + return setOfCharacters; +} + +function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { + if (generatedPassword.length >= maxLength) { + return generatedPassword + } + var longDivision = quotient.divmod(setOfCharacters.length); + generatedPassword += setOfCharacters[longDivision.remainder]; + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) +} + +function renderPassword(entropy, setOfCharacters, passwordProfile) { + var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {}; + var length = _passwordProfile.length || 14; + return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); +} + +},{"big-integer":3,"bluebird":4,"pbkdf2":19}]},{},[1])(1) }); \ No newline at end of file diff --git a/src/v1.js b/src/v1.js new file mode 100644 index 0000000..1ab4259 --- /dev/null +++ b/src/v1.js @@ -0,0 +1,121 @@ +var pbkdf2 = require('pbkdf2'); +var createHMAC = require('create-hmac'); +var Promise = require("bluebird"); + + +module.exports = { + encryptLogin: encryptLogin, + renderPassword: renderPassword, + createFingerprint: createFingerprint, + _deriveEncryptedLogin: deriveEncryptedLogin, + _getPasswordTemplate: getPasswordTemplate, + _prettyPrint: prettyPrint, + _string2charCodes: string2charCodes, + _getCharType: getCharType, + _getPasswordChar: getPasswordChar, + _createHmac: createHmac, +}; + + +function encryptLogin(login, masterPassword, options) { + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + + return new Promise(function (resolve, reject) { + if (!login || !masterPassword) { + reject('login and master password parameters could not be empty'); + } + pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }) +} + +function renderPassword(encryptedLogin, site, passwordOptions) { + return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = passwordOptions.template || getPasswordTemplate(passwordOptions); + return prettyPrint(derivedEncryptedLogin, template); + }); +} + +function createHmac(encryptedLogin, salt) { + return new Promise(function (resolve) { + resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + }); +} + +function deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; + + var salt = site + counter.toString(); + return createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, length); + }); +} + +function getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var returnedTemplate = ''; + Object.keys(templates).forEach(function (template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template] + } + }); + return returnedTemplate; +} + +function prettyPrint(hash, template) { + var password = ''; + + string2charCodes(hash).forEach(function (charCode, index) { + var charType = getCharType(template, index); + password += getPasswordChar(charType, charCode); + }); + return password; +} + +function string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function getCharType(template, index) { + return template[index % template.length]; +} + +function getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function createFingerprint(str) { + return new Promise(function (resolve) { + resolve(createHMAC('sha256', new Buffer(str)).digest('hex')) + }); +} \ No newline at end of file diff --git a/src/v2.js b/src/v2.js index 9fad7d9..72b9e84 100644 --- a/src/v2.js +++ b/src/v2.js @@ -2,7 +2,12 @@ var Promise = require("bluebird"); var pbkdf2 = require('pbkdf2'); var bigInt = require("big-integer"); -exports.generatePassword = generatePassword; +module.exports = { + generatePassword: generatePassword, + _calcEntropy: calcEntropy, + _getSetOfCharacters: getSetOfCharacters, + _renderPassword: renderPassword +}; function generatePassword(site, login, masterPassword, passwordProfile) { return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { @@ -11,11 +16,6 @@ function generatePassword(site, login, masterPassword, passwordProfile) { }); } -exports._calcEntropy = calcEntropy; -exports._getSetOfCharacters = getSetOfCharacters; -exports._renderPassword = renderPassword; - - function calcEntropy(site, login, masterPassword, passwordProfile) { return new Promise(function (resolve, reject) { var salt = site + login + passwordProfile.counter.toString(16); diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index e8a59f1..7ac32d9 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -3,6 +3,7 @@ var assert = chai.assert; describe('LessPass v2', function () { describe('API', function () { it('render password', function () { + this.timeout(10000); var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; @@ -20,6 +21,7 @@ describe('LessPass v2', function () { }); }); it('render password only digit', function () { + this.timeout(10000); var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; @@ -37,6 +39,7 @@ describe('LessPass v2', function () { }); }); it('render password no number', function () { + this.timeout(10000); var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; From dfacaa044490d15179f0837d329f994e06b2f039 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 20 Nov 2016 11:39:01 +0100 Subject: [PATCH 079/124] change default set of characters, add symbols --- tests/v2/api.tests.js | 2 +- tests/v2/renderPassword.tests.js | 1 - tests/v2/setOfCharacters.tests.js | 7 +++++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index 7ac32d9..55fbaed 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -38,7 +38,7 @@ describe('LessPass v2', function () { assert.equal('874236', generatedPassword); }); }); - it('render password no number', function () { + it('render password no number', function () { this.timeout(10000); var site = 'example.org'; var login = 'contact@example.org'; diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js index 1a5a400..c957fff 100644 --- a/tests/v2/renderPassword.tests.js +++ b/tests/v2/renderPassword.tests.js @@ -24,5 +24,4 @@ describe('LessPass v2', function () { }; assert.equal(20, LessPass._renderPassword(entropy, setOfCharacters, passwordProfile).length); }); - }); \ No newline at end of file diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js index f2ca649..aa881cd 100644 --- a/tests/v2/setOfCharacters.tests.js +++ b/tests/v2/setOfCharacters.tests.js @@ -4,8 +4,11 @@ describe('LessPass v2', function () { describe('set of characters', function () { it('get default set of characters', function () { var setOfCharacters = LessPass._getSetOfCharacters(); - assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); - assert.equal(26 * 2 + 10, setOfCharacters.length); + assert.equal( + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', + setOfCharacters + ); + assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); }); it('get default set of characters with object', function () { var setOfCharacters = LessPass._getSetOfCharacters({ From c7a4ef7158d3273333eed1e42a39877572942921 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 20 Nov 2016 13:04:22 +0100 Subject: [PATCH 080/124] ensure that at least one letter per subset is present --- index.js | 4 +++ lib/lesspass.js | 73 ++++++++++++++++++++++++++++++++------- src/v2.js | 69 +++++++++++++++++++++++++++++------- tests/helper.js | 1 + tests/karma.config.js | 1 + tests/v2/api.tests.js | 24 +++++++++++-- tests/v2/entropy.tests.js | 8 +++-- tests/v2/renderPassword.tests.js | 37 ++++++++++++++++++++ tests/v2/setOfCharacters.tests.js | 20 +++++++++++ 9 files changed, 207 insertions(+), 30 deletions(-) diff --git a/index.js b/index.js index 78e7455..88951f2 100644 --- a/index.js +++ b/index.js @@ -15,6 +15,10 @@ module.exports = { generatePassword: v2.generatePassword, _calcEntropy: v2._calcEntropy, + _consumeEntropy: v2._consumeEntropy, _getSetOfCharacters: v2._getSetOfCharacters, + _numberSubsetsOfChars: v2._numberSubsetsOfChars, + _includeOneCharPerSetOfCharacters: v2._includeOneCharPerSetOfCharacters, + _generateOneCharPerSetOfCharacters: v2._generateOneCharPerSetOfCharacters, _renderPassword: v2._renderPassword, }; \ No newline at end of file diff --git a/lib/lesspass.js b/lib/lesspass.js index 38e2162..03d42b0 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -16,7 +16,11 @@ module.exports = { generatePassword: v2.generatePassword, _calcEntropy: v2._calcEntropy, + _consumeEntropy: v2._consumeEntropy, _getSetOfCharacters: v2._getSetOfCharacters, + _numberSubsetsOfChars: v2._numberSubsetsOfChars, + _includeOneCharPerSetOfCharacters: v2._includeOneCharPerSetOfCharacters, + _generateOneCharPerSetOfCharacters: v2._generateOneCharPerSetOfCharacters, _renderPassword: v2._renderPassword, }; },{"./src/v1":46,"./src/v2":47}],2:[function(require,module,exports){ @@ -13577,7 +13581,11 @@ var bigInt = require("big-integer"); module.exports = { generatePassword: generatePassword, _calcEntropy: calcEntropy, + _consumeEntropy: consumeEntropy, _getSetOfCharacters: getSetOfCharacters, + _numberSubsetsOfChars: numberSubsetsOfChars, + _includeOneCharPerSetOfCharacters: includeOneCharPerSetOfCharacters, + _generateOneCharPerSetOfCharacters: generateOneCharPerSetOfCharacters, _renderPassword: renderPassword }; @@ -13603,19 +13611,17 @@ function calcEntropy(site, login, masterPassword, passwordProfile) { }); }); } +var subsetOfCharacters = { + lowercase: 'abcdefghijklmnopqrstuvwxyz', + uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + digits: '0123456789', + symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' +}; function getSetOfCharacters(passwordProfile) { - var subsetOfCharacters = { - lowercase: 'abcdefghijklmnopqrstuvwxyz', - uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - digits: '0123456789', - symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' - }; - if (typeof passwordProfile === 'undefined') { - return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits; + return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits + subsetOfCharacters.symbols; } - var setOfCharacters = ''; ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { @@ -13627,17 +13633,60 @@ function getSetOfCharacters(passwordProfile) { function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { if (generatedPassword.length >= maxLength) { - return generatedPassword + return {value: generatedPassword, entropy: quotient} } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) } +function includeOneCharPerSetOfCharacters(generatedPassword, entropy, oneCharPerSetOfCharacters) { + var finalPassword = generatedPassword; + var quotient = entropy; + for (var i = 0; i < oneCharPerSetOfCharacters.length; i++) { + var longDivision = quotient.divmod(finalPassword.length); + finalPassword = finalPassword.slice(0, longDivision.remainder) + oneCharPerSetOfCharacters[i] + finalPassword.slice(longDivision.remainder); + quotient = longDivision.quotient; + } + return finalPassword; +} + +function generateOneCharPerSetOfCharacters(entropy, passwordProfile) { + var oneCharPerSetOfCharacters = ''; + var quotient = entropy; + ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { + if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { + var alphabet = subsetOfCharacters[subset]; + var longDivision = quotient.divmod(alphabet.length); + oneCharPerSetOfCharacters += alphabet[longDivision.remainder]; + quotient = longDivision.quotient; + } + }); + return {value: oneCharPerSetOfCharacters, entropy: quotient}; +} + +function numberSubsetsOfChars(passwordProfile) { + var numberOfSubsets = 0; + ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { + if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { + numberOfSubsets += 1; + } + }); + return numberOfSubsets; +} + function renderPassword(entropy, setOfCharacters, passwordProfile) { - var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {}; + var _passwordProfile = passwordProfile !== undefined ? passwordProfile : { + lowercase: true, + uppercase: true, + digits: true, + symbols: true + }; var length = _passwordProfile.length || 14; - return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); + var numberCharsWillBeAdded = numberSubsetsOfChars(_passwordProfile); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length - numberCharsWillBeAdded); + var oneCharPerSetOfCharacters = generateOneCharPerSetOfCharacters(password.entropy, _passwordProfile); + return includeOneCharPerSetOfCharacters(password.value, oneCharPerSetOfCharacters.entropy, oneCharPerSetOfCharacters.value); } },{"big-integer":3,"bluebird":4,"pbkdf2":19}]},{},[1])(1) diff --git a/src/v2.js b/src/v2.js index 72b9e84..8ae0642 100644 --- a/src/v2.js +++ b/src/v2.js @@ -5,7 +5,11 @@ var bigInt = require("big-integer"); module.exports = { generatePassword: generatePassword, _calcEntropy: calcEntropy, + _consumeEntropy: consumeEntropy, _getSetOfCharacters: getSetOfCharacters, + _numberSubsetsOfChars: numberSubsetsOfChars, + _includeOneCharPerSetOfCharacters: includeOneCharPerSetOfCharacters, + _generateOneCharPerSetOfCharacters: generateOneCharPerSetOfCharacters, _renderPassword: renderPassword }; @@ -31,19 +35,17 @@ function calcEntropy(site, login, masterPassword, passwordProfile) { }); }); } +var subsetOfCharacters = { + lowercase: 'abcdefghijklmnopqrstuvwxyz', + uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + digits: '0123456789', + symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' +}; function getSetOfCharacters(passwordProfile) { - var subsetOfCharacters = { - lowercase: 'abcdefghijklmnopqrstuvwxyz', - uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - digits: '0123456789', - symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' - }; - if (typeof passwordProfile === 'undefined') { - return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits; + return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits + subsetOfCharacters.symbols; } - var setOfCharacters = ''; ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { @@ -55,15 +57,58 @@ function getSetOfCharacters(passwordProfile) { function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { if (generatedPassword.length >= maxLength) { - return generatedPassword + return {value: generatedPassword, entropy: quotient} } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) } +function includeOneCharPerSetOfCharacters(generatedPassword, entropy, oneCharPerSetOfCharacters) { + var finalPassword = generatedPassword; + var quotient = entropy; + for (var i = 0; i < oneCharPerSetOfCharacters.length; i++) { + var longDivision = quotient.divmod(finalPassword.length); + finalPassword = finalPassword.slice(0, longDivision.remainder) + oneCharPerSetOfCharacters[i] + finalPassword.slice(longDivision.remainder); + quotient = longDivision.quotient; + } + return finalPassword; +} + +function generateOneCharPerSetOfCharacters(entropy, passwordProfile) { + var oneCharPerSetOfCharacters = ''; + var quotient = entropy; + ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { + if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { + var alphabet = subsetOfCharacters[subset]; + var longDivision = quotient.divmod(alphabet.length); + oneCharPerSetOfCharacters += alphabet[longDivision.remainder]; + quotient = longDivision.quotient; + } + }); + return {value: oneCharPerSetOfCharacters, entropy: quotient}; +} + +function numberSubsetsOfChars(passwordProfile) { + var numberOfSubsets = 0; + ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { + if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { + numberOfSubsets += 1; + } + }); + return numberOfSubsets; +} + function renderPassword(entropy, setOfCharacters, passwordProfile) { - var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {}; + var _passwordProfile = passwordProfile !== undefined ? passwordProfile : { + lowercase: true, + uppercase: true, + digits: true, + symbols: true + }; var length = _passwordProfile.length || 14; - return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length); + var numberCharsWillBeAdded = numberSubsetsOfChars(_passwordProfile); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length - numberCharsWillBeAdded); + var oneCharPerSetOfCharacters = generateOneCharPerSetOfCharacters(password.entropy, _passwordProfile); + return includeOneCharPerSetOfCharacters(password.value, oneCharPerSetOfCharacters.entropy, oneCharPerSetOfCharacters.value); } diff --git a/tests/helper.js b/tests/helper.js index 30a150d..f7b3ea6 100644 --- a/tests/helper.js +++ b/tests/helper.js @@ -1,3 +1,4 @@ // globals global.chai = require('chai'); global.LessPass = require('../index'); +global.bigInt = require("big-integer"); diff --git a/tests/karma.config.js b/tests/karma.config.js index 8cb1241..97309ea 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -4,6 +4,7 @@ module.exports = function (config) { frameworks: ['mocha', 'chai'], files: [ 'node_modules/bluebird/js/browser/bluebird.core.min.js', + 'node_modules/big-integer/BigInteger.min.js', 'lib/lesspass.js', 'tests/**/*.js' ], diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index 55fbaed..ac0dcb8 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -12,12 +12,30 @@ describe('LessPass v2', function () { lowercase: true, uppercase: true, digits: true, + symbols: true, + length: 16, + counter: 1 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { + assert.equal('WHLpUL)e00[iHR+w', generatedPassword); + }); + }); + it('render password no symbols', function () { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 100000, + lowercase: true, + uppercase: true, + digits: true, symbols: false, length: 14, counter: 1 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('y5m7Ctw2695ksh', generatedPassword); + assert.equal('y5Im77Ctww2695', generatedPassword); }); }); it('render password only digit', function () { @@ -35,7 +53,7 @@ describe('LessPass v2', function () { counter: 1 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('874236', generatedPassword); + assert.equal('874623', generatedPassword); }); }); it('render password no number', function () { @@ -53,7 +71,7 @@ describe('LessPass v2', function () { counter: 1 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal("s>{F}wN/-fmMX?", generatedPassword); + assert.equal("sB>{qF}wN%/-fm", generatedPassword); }); }); }); diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index 5554af8..e149753 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -14,7 +14,6 @@ describe('LessPass v2', function () { assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); }); }); - it('calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)', function () { var site = 'example.org'; var login = 'contact@example.org'; @@ -29,7 +28,6 @@ describe('LessPass v2', function () { assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); }) }); - it('calc entropy different if counter different', function () { var site = 'example.org'; var login = 'contact@example.org'; @@ -48,6 +46,10 @@ describe('LessPass v2', function () { assert.notEqual(entropies[0], entropies[1]) }); }); - + it('consume entropy', function () { + var password = LessPass._consumeEntropy('', bigInt(4 * 4 + 2), "abcd", 2); + assert.equal('ca', password.value); + assert.equal(1, password.entropy) + }); }); }); \ No newline at end of file diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js index c957fff..1eda3e8 100644 --- a/tests/v2/renderPassword.tests.js +++ b/tests/v2/renderPassword.tests.js @@ -24,4 +24,41 @@ describe('LessPass v2', function () { }; assert.equal(20, LessPass._renderPassword(entropy, setOfCharacters, passwordProfile).length); }); + it('include one char per set of characters', function () { + var password = LessPass._includeOneCharPerSetOfCharacters('123456', bigInt(7 * 6 + 2), 'uT'); + assert.equal('T12u3456', password); + }); + it('render password return at least one char in every characters set', function () { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'; + var passwordProfile = { + length: 6, + lowercase: true, + uppercase: true, + digits: true, + symbols: true, + }; + var generatedPassword = LessPass._renderPassword(entropy, setOfCharacters, passwordProfile); + var passwordLength = generatedPassword.length; + var lowercaseOk = false; + var uppercaseOk = false; + var digitsOk = false; + var symbolsOk = false; + while (passwordLength--) { + if ('abcdefghijklmnopqrstuvwxyz'.indexOf(generatedPassword[passwordLength]) !== -1) { + lowercaseOk = true; + } + if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(generatedPassword[passwordLength]) !== -1) { + uppercaseOk = true; + } + if ('0123456789'.indexOf(generatedPassword[passwordLength]) !== -1) { + digitsOk = true; + } + if ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.indexOf(generatedPassword[passwordLength]) !== -1) { + symbolsOk = true; + } + } + assert.equal(6, generatedPassword.length); + assert(lowercaseOk && uppercaseOk && digitsOk && symbolsOk, 'there is no at least one char in every characters set'); + }); }); \ No newline at end of file diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js index aa881cd..6e281ec 100644 --- a/tests/v2/setOfCharacters.tests.js +++ b/tests/v2/setOfCharacters.tests.js @@ -51,5 +51,25 @@ describe('LessPass v2', function () { LessPass._getSetOfCharacters({symbols: true, digits: true}) ); }); + it('generate one char per set of characters', function () { + var oneCharPerSetOfCharacters = LessPass._generateOneCharPerSetOfCharacters( + bigInt(26 * 26), + {uppercase: true, lowercase: true} + ); + assert.equal('aA', oneCharPerSetOfCharacters.value); + assert.equal(2, oneCharPerSetOfCharacters.value.length); + assert.equal(1, oneCharPerSetOfCharacters.entropy); + }); + it('number set of characters', function () { + assert.equal(1, LessPass._numberSubsetsOfChars({uppercase: true})); + assert.equal(2, LessPass._numberSubsetsOfChars({uppercase: true, lowercase: true})); + assert.equal(2, LessPass._numberSubsetsOfChars({uppercase: true, lowercase: true, symbols: false})); + assert.equal(4, LessPass._numberSubsetsOfChars({ + lowercase: true, + uppercase: true, + symbols: true, + digits: true + })); + }); }); }); \ No newline at end of file From 09a7366d8f3953eb66db520e2f1c4d04a35e0e7f Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 20 Nov 2016 13:27:24 +0100 Subject: [PATCH 081/124] calc max password length --- tests/v2/debug.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/v2/debug.py b/tests/v2/debug.py index a8f7708..e494f8b 100644 --- a/tests/v2/debug.py +++ b/tests/v2/debug.py @@ -1,3 +1,6 @@ +import math + + def renderPassword(mdp, quotient, alphabet): if len(mdp) > 14: return mdp @@ -8,3 +11,6 @@ def renderPassword(mdp, quotient, alphabet): alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' print(renderPassword('', int('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', 16), alphabet)) + +max_length = math.floor(math.log(int('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', 16))/math.log(26 + 26 + 10 + 32)) - 4 +print('max number of char for password with 32 bytes entropy: %d' % max_length) From 1f06b18ed641223f9255660ccf1712665193500e Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sun, 20 Nov 2016 16:21:16 +0100 Subject: [PATCH 082/124] refactor code --- index.js | 6 +- lib/lesspass.js | 269 ++++++++++++++++++++++++-------------- package.json | 1 + src/v2.js | 110 ++++++++-------- tests/v2/api.tests.js | 16 +-- tests/v2/entropy.tests.js | 15 +-- tests/v2/renderPassword.tests.js | 27 ++-- tests/v2/setOfCharacters.tests.js | 44 ++----- 8 files changed, 268 insertions(+), 220 deletions(-) diff --git a/index.js b/index.js index 88951f2..16faf2d 100644 --- a/index.js +++ b/index.js @@ -17,8 +17,8 @@ module.exports = { _calcEntropy: v2._calcEntropy, _consumeEntropy: v2._consumeEntropy, _getSetOfCharacters: v2._getSetOfCharacters, - _numberSubsetsOfChars: v2._numberSubsetsOfChars, - _includeOneCharPerSetOfCharacters: v2._includeOneCharPerSetOfCharacters, - _generateOneCharPerSetOfCharacters: v2._generateOneCharPerSetOfCharacters, + _validRules: v2._validRules, + _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, + _getOneCharPerRule: v2._getOneCharPerRule, _renderPassword: v2._renderPassword, }; \ No newline at end of file diff --git a/lib/lesspass.js b/lib/lesspass.js index 03d42b0..9ed1892 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -18,12 +18,12 @@ module.exports = { _calcEntropy: v2._calcEntropy, _consumeEntropy: v2._consumeEntropy, _getSetOfCharacters: v2._getSetOfCharacters, - _numberSubsetsOfChars: v2._numberSubsetsOfChars, - _includeOneCharPerSetOfCharacters: v2._includeOneCharPerSetOfCharacters, - _generateOneCharPerSetOfCharacters: v2._generateOneCharPerSetOfCharacters, + _validRules: v2._validRules, + _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, + _getOneCharPerRule: v2._getOneCharPerRule, _renderPassword: v2._renderPassword, }; -},{"./src/v1":46,"./src/v2":47}],2:[function(require,module,exports){ +},{"./src/v1":47,"./src/v2":48}],2:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -6956,7 +6956,7 @@ module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":22}],5:[function(require,module,exports){ +},{"_process":23}],5:[function(require,module,exports){ },{}],6:[function(require,module,exports){ (function (global){ @@ -8957,7 +8957,7 @@ CipherBase.prototype._toString = function (value, enc, fin) { } }).call(this,require("buffer").Buffer) -},{"buffer":7,"inherits":16,"stream":43,"string_decoder":44}],9:[function(require,module,exports){ +},{"buffer":7,"inherits":16,"stream":44,"string_decoder":45}],9:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -9124,7 +9124,7 @@ module.exports = function createHash (alg) { } }).call(this,require("buffer").Buffer) -},{"./md5":12,"buffer":7,"cipher-base":8,"inherits":16,"ripemd160":34,"sha.js":36}],11:[function(require,module,exports){ +},{"./md5":12,"buffer":7,"cipher-base":8,"inherits":16,"ripemd160":35,"sha.js":37}],11:[function(require,module,exports){ (function (Buffer){ 'use strict'; var intSize = 4; @@ -9390,7 +9390,7 @@ module.exports = function createHmac(alg, key) { } }).call(this,require("buffer").Buffer) -},{"buffer":7,"create-hash/browser":10,"inherits":16,"stream":43}],14:[function(require,module,exports){ +},{"buffer":7,"create-hash/browser":10,"inherits":16,"stream":44}],14:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -9836,6 +9836,91 @@ module.exports = Array.isArray || function (arr) { }; },{}],19:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],20:[function(require,module,exports){ (function (process,Buffer){ var createHmac = require('create-hmac') var checkParameters = require('./precondition') @@ -9907,7 +9992,7 @@ exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { } }).call(this,require('_process'),require("buffer").Buffer) -},{"./precondition":20,"_process":22,"buffer":7,"create-hmac":13}],20:[function(require,module,exports){ +},{"./precondition":21,"_process":23,"buffer":7,"create-hmac":13}],21:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { @@ -9927,7 +10012,7 @@ module.exports = function (iterations, keylen) { } } -},{}],21:[function(require,module,exports){ +},{}],22:[function(require,module,exports){ (function (process){ 'use strict'; @@ -9974,7 +10059,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":22}],22:[function(require,module,exports){ +},{"_process":23}],23:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -10156,10 +10241,10 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],23:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ module.exports = require("./lib/_stream_duplex.js") -},{"./lib/_stream_duplex.js":24}],24:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":25}],25:[function(require,module,exports){ // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from @@ -10235,7 +10320,7 @@ function forEach(xs, f) { f(xs[i], i); } } -},{"./_stream_readable":26,"./_stream_writable":28,"core-util-is":9,"inherits":16,"process-nextick-args":21}],25:[function(require,module,exports){ +},{"./_stream_readable":27,"./_stream_writable":29,"core-util-is":9,"inherits":16,"process-nextick-args":22}],26:[function(require,module,exports){ // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. @@ -10262,7 +10347,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":27,"core-util-is":9,"inherits":16}],26:[function(require,module,exports){ +},{"./_stream_transform":28,"core-util-is":9,"inherits":16}],27:[function(require,module,exports){ (function (process){ 'use strict'; @@ -11202,7 +11287,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process')) -},{"./_stream_duplex":24,"./internal/streams/BufferList":29,"_process":22,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"isarray":18,"process-nextick-args":21,"string_decoder/":44,"util":5}],27:[function(require,module,exports){ +},{"./_stream_duplex":25,"./internal/streams/BufferList":30,"_process":23,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"isarray":18,"process-nextick-args":22,"string_decoder/":45,"util":5}],28:[function(require,module,exports){ // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -11383,7 +11468,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":24,"core-util-is":9,"inherits":16}],28:[function(require,module,exports){ +},{"./_stream_duplex":25,"core-util-is":9,"inherits":16}],29:[function(require,module,exports){ (function (process){ // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all @@ -11912,7 +11997,7 @@ function CorkedRequest(state) { }; } }).call(this,require('_process')) -},{"./_stream_duplex":24,"_process":22,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"process-nextick-args":21,"util-deprecate":45}],29:[function(require,module,exports){ +},{"./_stream_duplex":25,"_process":23,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"process-nextick-args":22,"util-deprecate":46}],30:[function(require,module,exports){ 'use strict'; var Buffer = require('buffer').Buffer; @@ -11977,10 +12062,10 @@ BufferList.prototype.concat = function (n) { } return ret; }; -},{"buffer":7,"buffer-shims":6}],30:[function(require,module,exports){ +},{"buffer":7,"buffer-shims":6}],31:[function(require,module,exports){ module.exports = require("./lib/_stream_passthrough.js") -},{"./lib/_stream_passthrough.js":25}],31:[function(require,module,exports){ +},{"./lib/_stream_passthrough.js":26}],32:[function(require,module,exports){ (function (process){ var Stream = (function (){ try { @@ -12000,13 +12085,13 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { } }).call(this,require('_process')) -},{"./lib/_stream_duplex.js":24,"./lib/_stream_passthrough.js":25,"./lib/_stream_readable.js":26,"./lib/_stream_transform.js":27,"./lib/_stream_writable.js":28,"_process":22}],32:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":25,"./lib/_stream_passthrough.js":26,"./lib/_stream_readable.js":27,"./lib/_stream_transform.js":28,"./lib/_stream_writable.js":29,"_process":23}],33:[function(require,module,exports){ module.exports = require("./lib/_stream_transform.js") -},{"./lib/_stream_transform.js":27}],33:[function(require,module,exports){ +},{"./lib/_stream_transform.js":28}],34:[function(require,module,exports){ module.exports = require("./lib/_stream_writable.js") -},{"./lib/_stream_writable.js":28}],34:[function(require,module,exports){ +},{"./lib/_stream_writable.js":29}],35:[function(require,module,exports){ (function (Buffer){ /* CryptoJS v3.1.2 @@ -12220,7 +12305,7 @@ function ripemd160 (message) { module.exports = ripemd160 }).call(this,require("buffer").Buffer) -},{"buffer":7}],35:[function(require,module,exports){ +},{"buffer":7}],36:[function(require,module,exports){ (function (Buffer){ // prototype class for hash functions function Hash (blockSize, finalSize) { @@ -12293,7 +12378,7 @@ Hash.prototype._update = function () { module.exports = Hash }).call(this,require("buffer").Buffer) -},{"buffer":7}],36:[function(require,module,exports){ +},{"buffer":7}],37:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() @@ -12310,7 +12395,7 @@ exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') -},{"./sha":37,"./sha1":38,"./sha224":39,"./sha256":40,"./sha384":41,"./sha512":42}],37:[function(require,module,exports){ +},{"./sha":38,"./sha1":39,"./sha224":40,"./sha256":41,"./sha384":42,"./sha512":43}],38:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined @@ -12407,7 +12492,7 @@ Sha.prototype._hash = function () { module.exports = Sha }).call(this,require("buffer").Buffer) -},{"./hash":35,"buffer":7,"inherits":16}],38:[function(require,module,exports){ +},{"./hash":36,"buffer":7,"inherits":16}],39:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined @@ -12509,7 +12594,7 @@ Sha1.prototype._hash = function () { module.exports = Sha1 }).call(this,require("buffer").Buffer) -},{"./hash":35,"buffer":7,"inherits":16}],39:[function(require,module,exports){ +},{"./hash":36,"buffer":7,"inherits":16}],40:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -12565,7 +12650,7 @@ Sha224.prototype._hash = function () { module.exports = Sha224 }).call(this,require("buffer").Buffer) -},{"./hash":35,"./sha256":40,"buffer":7,"inherits":16}],40:[function(require,module,exports){ +},{"./hash":36,"./sha256":41,"buffer":7,"inherits":16}],41:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -12703,7 +12788,7 @@ Sha256.prototype._hash = function () { module.exports = Sha256 }).call(this,require("buffer").Buffer) -},{"./hash":35,"buffer":7,"inherits":16}],41:[function(require,module,exports){ +},{"./hash":36,"buffer":7,"inherits":16}],42:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var SHA512 = require('./sha512') @@ -12763,7 +12848,7 @@ Sha384.prototype._hash = function () { module.exports = Sha384 }).call(this,require("buffer").Buffer) -},{"./hash":35,"./sha512":42,"buffer":7,"inherits":16}],42:[function(require,module,exports){ +},{"./hash":36,"./sha512":43,"buffer":7,"inherits":16}],43:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var Hash = require('./hash') @@ -13026,7 +13111,7 @@ Sha512.prototype._hash = function () { module.exports = Sha512 }).call(this,require("buffer").Buffer) -},{"./hash":35,"buffer":7,"inherits":16}],43:[function(require,module,exports){ +},{"./hash":36,"buffer":7,"inherits":16}],44:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13155,7 +13240,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":14,"inherits":16,"readable-stream/duplex.js":23,"readable-stream/passthrough.js":30,"readable-stream/readable.js":31,"readable-stream/transform.js":32,"readable-stream/writable.js":33}],44:[function(require,module,exports){ +},{"events":14,"inherits":16,"readable-stream/duplex.js":24,"readable-stream/passthrough.js":31,"readable-stream/readable.js":32,"readable-stream/transform.js":33,"readable-stream/writable.js":34}],45:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13378,7 +13463,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":7}],45:[function(require,module,exports){ +},{"buffer":7}],46:[function(require,module,exports){ (function (global){ /** @@ -13449,7 +13534,7 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],46:[function(require,module,exports){ +},{}],47:[function(require,module,exports){ (function (Buffer){ var pbkdf2 = require('pbkdf2'); var createHMAC = require('create-hmac'); @@ -13573,36 +13658,46 @@ function createFingerprint(str) { }); } }).call(this,require("buffer").Buffer) -},{"bluebird":4,"buffer":7,"create-hmac":13,"pbkdf2":19}],47:[function(require,module,exports){ +},{"bluebird":4,"buffer":7,"create-hmac":13,"pbkdf2":20}],48:[function(require,module,exports){ var Promise = require("bluebird"); var pbkdf2 = require('pbkdf2'); var bigInt = require("big-integer"); +var objectAssign = require('object-assign'); module.exports = { generatePassword: generatePassword, _calcEntropy: calcEntropy, _consumeEntropy: consumeEntropy, _getSetOfCharacters: getSetOfCharacters, - _numberSubsetsOfChars: numberSubsetsOfChars, - _includeOneCharPerSetOfCharacters: includeOneCharPerSetOfCharacters, - _generateOneCharPerSetOfCharacters: generateOneCharPerSetOfCharacters, + _validRules: validRules, + _insertStringPseudoRandomly: insertStringPseudoRandomly, + _getOneCharPerRule: getOneCharPerRule, _renderPassword: renderPassword }; function generatePassword(site, login, masterPassword, passwordProfile) { return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - var setOfCharacters = getSetOfCharacters(passwordProfile); - return renderPassword(entropy, setOfCharacters, passwordProfile) + return renderPassword(entropy, passwordProfile) }); } +var defaultPasswordProfile = { + lowercase: true, + uppercase: true, + digits: true, + symbols: true, + length: 16, + counter: 1, + iterations: 100000, + keylen: 32, + digest: 'sha256' +}; + function calcEntropy(site, login, masterPassword, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); return new Promise(function (resolve, reject) { - var salt = site + login + passwordProfile.counter.toString(16); - var iterations = passwordProfile.iterations || 100000; - var keylen = passwordProfile.keylen || 32; - var digest = passwordProfile.digest || 'sha256'; - pbkdf2.pbkdf2(masterPassword, salt, iterations, keylen, digest, function (error, key) { + var salt = site + login + _passwordProfile.counter.toString(16); + pbkdf2.pbkdf2(masterPassword, salt, _passwordProfile.iterations, _passwordProfile.keylen, _passwordProfile.digest, function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -13611,24 +13706,23 @@ function calcEntropy(site, login, masterPassword, passwordProfile) { }); }); } -var subsetOfCharacters = { + +var subsetOfChars = { lowercase: 'abcdefghijklmnopqrstuvwxyz', uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: '0123456789', symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' }; -function getSetOfCharacters(passwordProfile) { - if (typeof passwordProfile === 'undefined') { - return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits + subsetOfCharacters.symbols; +function getSetOfCharacters(rules) { + if (typeof rules === 'undefined') { + return subsetOfChars.lowercase + subsetOfChars.uppercase + subsetOfChars.digits + subsetOfChars.symbols; } - var setOfCharacters = ''; - ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { - if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { - setOfCharacters += subsetOfCharacters[subset] - } + var setOfChars = ''; + rules.forEach(function (rule) { + setOfChars += subsetOfChars[rule] }); - return setOfCharacters; + return setOfChars; } function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { @@ -13640,54 +13734,39 @@ function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) } -function includeOneCharPerSetOfCharacters(generatedPassword, entropy, oneCharPerSetOfCharacters) { - var finalPassword = generatedPassword; - var quotient = entropy; - for (var i = 0; i < oneCharPerSetOfCharacters.length; i++) { - var longDivision = quotient.divmod(finalPassword.length); - finalPassword = finalPassword.slice(0, longDivision.remainder) + oneCharPerSetOfCharacters[i] + finalPassword.slice(longDivision.remainder); - quotient = longDivision.quotient; +function insertStringPseudoRandomly(generatedPassword, entropy, string) { + for (var i = 0; i < string.length; i++) { + var longDivision = entropy.divmod(generatedPassword.length); + generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); + entropy = longDivision.quotient; } - return finalPassword; + return generatedPassword; } -function generateOneCharPerSetOfCharacters(entropy, passwordProfile) { - var oneCharPerSetOfCharacters = ''; - var quotient = entropy; - ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { - if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { - var alphabet = subsetOfCharacters[subset]; - var longDivision = quotient.divmod(alphabet.length); - oneCharPerSetOfCharacters += alphabet[longDivision.remainder]; - quotient = longDivision.quotient; - } +function getOneCharPerRule(entropy, rules) { + var oneCharPerRules = ''; + rules.forEach(function (rule) { + var password = consumeEntropy('', entropy, subsetOfChars[rule], 1); + oneCharPerRules += password.value; + entropy = password.entropy; }); - return {value: oneCharPerSetOfCharacters, entropy: quotient}; + return {value: oneCharPerRules, entropy: entropy}; } -function numberSubsetsOfChars(passwordProfile) { - var numberOfSubsets = 0; - ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { - if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { - numberOfSubsets += 1; - } +function validRules(passwordProfile) { + return ['lowercase', 'uppercase', 'digits', 'symbols'].filter(function (rule) { + return passwordProfile[rule]; }); - return numberOfSubsets; } -function renderPassword(entropy, setOfCharacters, passwordProfile) { - var _passwordProfile = passwordProfile !== undefined ? passwordProfile : { - lowercase: true, - uppercase: true, - digits: true, - symbols: true - }; - var length = _passwordProfile.length || 14; - var numberCharsWillBeAdded = numberSubsetsOfChars(_passwordProfile); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length - numberCharsWillBeAdded); - var oneCharPerSetOfCharacters = generateOneCharPerSetOfCharacters(password.entropy, _passwordProfile); - return includeOneCharPerSetOfCharacters(password.value, oneCharPerSetOfCharacters.entropy, oneCharPerSetOfCharacters.value); +function renderPassword(entropy, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + var rules = validRules(_passwordProfile); + var setOfCharacters = getSetOfCharacters(rules); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, _passwordProfile.length - rules.length); + var charactersToAdd = getOneCharPerRule(password.entropy, rules); + return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } -},{"big-integer":3,"bluebird":4,"pbkdf2":19}]},{},[1])(1) +},{"big-integer":3,"bluebird":4,"object-assign":19,"pbkdf2":20}]},{},[1])(1) }); \ No newline at end of file diff --git a/package.json b/package.json index 5fec02c..6371006 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "big-integer": "^1.6.17", "bluebird": "^3.4.6", "create-hmac": "^1.1.4", + "object-assign": "^4.1.0", "pbkdf2": "^3.0.9", "unibabel": "^2.1.3" }, diff --git a/src/v2.js b/src/v2.js index 8ae0642..5f2d014 100644 --- a/src/v2.js +++ b/src/v2.js @@ -1,32 +1,42 @@ var Promise = require("bluebird"); var pbkdf2 = require('pbkdf2'); var bigInt = require("big-integer"); +var objectAssign = require('object-assign'); module.exports = { generatePassword: generatePassword, _calcEntropy: calcEntropy, _consumeEntropy: consumeEntropy, _getSetOfCharacters: getSetOfCharacters, - _numberSubsetsOfChars: numberSubsetsOfChars, - _includeOneCharPerSetOfCharacters: includeOneCharPerSetOfCharacters, - _generateOneCharPerSetOfCharacters: generateOneCharPerSetOfCharacters, + _validRules: validRules, + _insertStringPseudoRandomly: insertStringPseudoRandomly, + _getOneCharPerRule: getOneCharPerRule, _renderPassword: renderPassword }; function generatePassword(site, login, masterPassword, passwordProfile) { return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - var setOfCharacters = getSetOfCharacters(passwordProfile); - return renderPassword(entropy, setOfCharacters, passwordProfile) + return renderPassword(entropy, passwordProfile) }); } +var defaultPasswordProfile = { + lowercase: true, + uppercase: true, + digits: true, + symbols: true, + length: 16, + counter: 1, + iterations: 100000, + keylen: 32, + digest: 'sha256' +}; + function calcEntropy(site, login, masterPassword, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); return new Promise(function (resolve, reject) { - var salt = site + login + passwordProfile.counter.toString(16); - var iterations = passwordProfile.iterations || 100000; - var keylen = passwordProfile.keylen || 32; - var digest = passwordProfile.digest || 'sha256'; - pbkdf2.pbkdf2(masterPassword, salt, iterations, keylen, digest, function (error, key) { + var salt = site + login + _passwordProfile.counter.toString(16); + pbkdf2.pbkdf2(masterPassword, salt, _passwordProfile.iterations, _passwordProfile.keylen, _passwordProfile.digest, function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -35,24 +45,23 @@ function calcEntropy(site, login, masterPassword, passwordProfile) { }); }); } -var subsetOfCharacters = { + +var subsetOfChars = { lowercase: 'abcdefghijklmnopqrstuvwxyz', uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: '0123456789', symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' }; -function getSetOfCharacters(passwordProfile) { - if (typeof passwordProfile === 'undefined') { - return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits + subsetOfCharacters.symbols; +function getSetOfCharacters(rules) { + if (typeof rules === 'undefined') { + return subsetOfChars.lowercase + subsetOfChars.uppercase + subsetOfChars.digits + subsetOfChars.symbols; } - var setOfCharacters = ''; - ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { - if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { - setOfCharacters += subsetOfCharacters[subset] - } + var setOfChars = ''; + rules.forEach(function (rule) { + setOfChars += subsetOfChars[rule] }); - return setOfCharacters; + return setOfChars; } function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { @@ -64,51 +73,36 @@ function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) } -function includeOneCharPerSetOfCharacters(generatedPassword, entropy, oneCharPerSetOfCharacters) { - var finalPassword = generatedPassword; - var quotient = entropy; - for (var i = 0; i < oneCharPerSetOfCharacters.length; i++) { - var longDivision = quotient.divmod(finalPassword.length); - finalPassword = finalPassword.slice(0, longDivision.remainder) + oneCharPerSetOfCharacters[i] + finalPassword.slice(longDivision.remainder); - quotient = longDivision.quotient; +function insertStringPseudoRandomly(generatedPassword, entropy, string) { + for (var i = 0; i < string.length; i++) { + var longDivision = entropy.divmod(generatedPassword.length); + generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); + entropy = longDivision.quotient; } - return finalPassword; + return generatedPassword; } -function generateOneCharPerSetOfCharacters(entropy, passwordProfile) { - var oneCharPerSetOfCharacters = ''; - var quotient = entropy; - ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { - if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { - var alphabet = subsetOfCharacters[subset]; - var longDivision = quotient.divmod(alphabet.length); - oneCharPerSetOfCharacters += alphabet[longDivision.remainder]; - quotient = longDivision.quotient; - } +function getOneCharPerRule(entropy, rules) { + var oneCharPerRules = ''; + rules.forEach(function (rule) { + var password = consumeEntropy('', entropy, subsetOfChars[rule], 1); + oneCharPerRules += password.value; + entropy = password.entropy; }); - return {value: oneCharPerSetOfCharacters, entropy: quotient}; + return {value: oneCharPerRules, entropy: entropy}; } -function numberSubsetsOfChars(passwordProfile) { - var numberOfSubsets = 0; - ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) { - if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) { - numberOfSubsets += 1; - } +function validRules(passwordProfile) { + return ['lowercase', 'uppercase', 'digits', 'symbols'].filter(function (rule) { + return passwordProfile[rule]; }); - return numberOfSubsets; } -function renderPassword(entropy, setOfCharacters, passwordProfile) { - var _passwordProfile = passwordProfile !== undefined ? passwordProfile : { - lowercase: true, - uppercase: true, - digits: true, - symbols: true - }; - var length = _passwordProfile.length || 14; - var numberCharsWillBeAdded = numberSubsetsOfChars(_passwordProfile); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length - numberCharsWillBeAdded); - var oneCharPerSetOfCharacters = generateOneCharPerSetOfCharacters(password.entropy, _passwordProfile); - return includeOneCharPerSetOfCharacters(password.value, oneCharPerSetOfCharacters.entropy, oneCharPerSetOfCharacters.value); +function renderPassword(entropy, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + var rules = validRules(_passwordProfile); + var setOfCharacters = getSetOfCharacters(rules); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, _passwordProfile.length - rules.length); + var charactersToAdd = getOneCharPerRule(password.entropy, rules); + return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index ac0dcb8..9958668 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -8,13 +8,13 @@ describe('LessPass v2', function () { var login = 'contact@example.org'; var masterPassword = 'password'; var passwordProfile = { - iterations: 100000, lowercase: true, uppercase: true, digits: true, symbols: true, length: 16, - counter: 1 + counter: 1, + version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { assert.equal('WHLpUL)e00[iHR+w', generatedPassword); @@ -26,13 +26,13 @@ describe('LessPass v2', function () { var login = 'contact@example.org'; var masterPassword = 'password'; var passwordProfile = { - iterations: 100000, lowercase: true, uppercase: true, digits: true, symbols: false, length: 14, - counter: 1 + counter: 1, + version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { assert.equal('y5Im77Ctww2695', generatedPassword); @@ -44,13 +44,13 @@ describe('LessPass v2', function () { var login = 'contact@example.org'; var masterPassword = 'password'; var passwordProfile = { - iterations: 100000, lowercase: false, uppercase: false, digits: true, symbols: false, length: 6, - counter: 1 + counter: 1, + version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { assert.equal('874623', generatedPassword); @@ -62,13 +62,13 @@ describe('LessPass v2', function () { var login = 'contact@example.org'; var masterPassword = 'password'; var passwordProfile = { - iterations: 100000, lowercase: true, uppercase: true, digits: false, symbols: true, length: 14, - counter: 1 + counter: 1, + version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { assert.equal("sB>{qF}wN%/-fm", generatedPassword); diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index e149753..e4fbb74 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -7,10 +7,7 @@ describe('LessPass v2', function () { var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; - var passwordProfile = { - counter: 1 - }; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + return LessPass._calcEntropy(site, login, masterPassword).then(function (entropy) { assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); }); }); @@ -32,14 +29,8 @@ describe('LessPass v2', function () { var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; - var passwordProfile1 = { - iterations: 1, - counter: 1 - }; - var passwordProfile2 = { - iterations: 1, - counter: 2 - }; + var passwordProfile1 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 1}; + var passwordProfile2 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 2}; var p1 = LessPass._calcEntropy(site, login, masterPassword, passwordProfile1); var p2 = LessPass._calcEntropy(site, login, masterPassword, passwordProfile2); return Promise.all([p1, p2]).then(function (entropies) { diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js index 1eda3e8..b7e0e32 100644 --- a/tests/v2/renderPassword.tests.js +++ b/tests/v2/renderPassword.tests.js @@ -1,36 +1,35 @@ var assert = chai.assert; describe('LessPass v2', function () { - it('render password use remainder of long division beetween entropy and set of chars length as an index ', function () { + it('render password use remainder of long division beetween entropy and set of chars length as an index', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - assert.equal('y', LessPass._renderPassword(entropy, setOfCharacters)[0]); + assert.equal('W', LessPass._renderPassword(entropy)[0]); }); it('render password use quotient as second entropy recursively', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - assert.equal('5', LessPass._renderPassword(entropy, setOfCharacters)[1]); + assert.equal('H', LessPass._renderPassword(entropy)[1]); }); - it('render password has default length of 14', function () { + it('render password has default length of 16', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - assert.equal(14, LessPass._renderPassword(entropy, setOfCharacters).length); + assert.equal(16, LessPass._renderPassword(entropy).length); }); it('render password can specify length', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; var passwordProfile = { - length: 20 + length: 20, + lowercase: true, + uppercase: true, + digits: true, + symbols: true }; - assert.equal(20, LessPass._renderPassword(entropy, setOfCharacters, passwordProfile).length); + assert.equal(20, LessPass._renderPassword(entropy, passwordProfile).length); }); it('include one char per set of characters', function () { - var password = LessPass._includeOneCharPerSetOfCharacters('123456', bigInt(7 * 6 + 2), 'uT'); + var password = LessPass._insertStringPseudoRandomly('123456', bigInt(7 * 6 + 2), 'uT'); assert.equal('T12u3456', password); }); it('render password return at least one char in every characters set', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var setOfCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'; var passwordProfile = { length: 6, lowercase: true, @@ -38,7 +37,7 @@ describe('LessPass v2', function () { digits: true, symbols: true, }; - var generatedPassword = LessPass._renderPassword(entropy, setOfCharacters, passwordProfile); + var generatedPassword = LessPass._renderPassword(entropy, passwordProfile); var passwordLength = generatedPassword.length; var lowercaseOk = false; var uppercaseOk = false; diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js index 6e281ec..1798147 100644 --- a/tests/v2/setOfCharacters.tests.js +++ b/tests/v2/setOfCharacters.tests.js @@ -10,61 +10,45 @@ describe('LessPass v2', function () { ); assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); }); - it('get default set of characters with object', function () { - var setOfCharacters = LessPass._getSetOfCharacters({ - lowercase: true, - uppercase: true, - digits: true, - symbols: false - }); + it('get default set of characters concat rules in order', function () { + var setOfCharacters = LessPass._getSetOfCharacters(['lowercase', 'uppercase', 'digits']); assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); assert.equal(26 * 2 + 10, setOfCharacters.length); }); it('get set of characters only lowercase', function () { - var setOfCharacters = LessPass._getSetOfCharacters({lowercase: true}); + var setOfCharacters = LessPass._getSetOfCharacters(['lowercase']); assert.equal('abcdefghijklmnopqrstuvwxyz', setOfCharacters); assert.equal(26, setOfCharacters.length); }); it('get set of characters only uppercase', function () { - var setOfCharacters = LessPass._getSetOfCharacters({uppercase: true}); + var setOfCharacters = LessPass._getSetOfCharacters(['uppercase']); assert.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); assert.equal(26, setOfCharacters.length); }); it('get set of characters only digits', function () { - var setOfCharacters = LessPass._getSetOfCharacters({digits: true}); + var setOfCharacters = LessPass._getSetOfCharacters(['digits']); assert.equal('0123456789', setOfCharacters); assert.equal(10, setOfCharacters.length); }); it('get set of characters only symbols', function () { - var setOfCharacters = LessPass._getSetOfCharacters({symbols: true}); + var setOfCharacters = LessPass._getSetOfCharacters(['symbols']); assert.equal('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', setOfCharacters); assert.equal(32, setOfCharacters.length); }); - it('get set of characters concat two subsets', function () { - var setOfCharacters = LessPass._getSetOfCharacters({lowercase: true, uppercase: true}); - assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); - assert.equal(26 * 2, setOfCharacters.length); - }); - it('get set of characters doesn\'t care of key order in options', function () { - assert.equal( - LessPass._getSetOfCharacters({digits: true, symbols: true}), - LessPass._getSetOfCharacters({symbols: true, digits: true}) - ); - }); - it('generate one char per set of characters', function () { - var oneCharPerSetOfCharacters = LessPass._generateOneCharPerSetOfCharacters( + it('generate one char per rules', function () { + var oneCharPerSetOfCharacters = LessPass._getOneCharPerRule( bigInt(26 * 26), - {uppercase: true, lowercase: true} + ['lowercase', 'uppercase'] ); assert.equal('aA', oneCharPerSetOfCharacters.value); assert.equal(2, oneCharPerSetOfCharacters.value.length); assert.equal(1, oneCharPerSetOfCharacters.entropy); }); - it('number set of characters', function () { - assert.equal(1, LessPass._numberSubsetsOfChars({uppercase: true})); - assert.equal(2, LessPass._numberSubsetsOfChars({uppercase: true, lowercase: true})); - assert.equal(2, LessPass._numberSubsetsOfChars({uppercase: true, lowercase: true, symbols: false})); - assert.equal(4, LessPass._numberSubsetsOfChars({ + it('valid rules', function () { + assert.deepEqual(['uppercase'], LessPass._validRules({uppercase: true})); + assert.deepEqual(['lowercase', 'uppercase'], LessPass._validRules({uppercase: true, lowercase: true})); + assert.deepEqual(['lowercase'], LessPass._validRules({lowercase: true, symbols: false})); + assert.deepEqual(['lowercase', 'uppercase', 'digits', 'symbols'], LessPass._validRules({ lowercase: true, uppercase: true, symbols: true, From 14468db1225577c436cf868314a108c7d9b65285 Mon Sep 17 00:00:00 2001 From: Erik Mulder Date: Mon, 21 Nov 2016 12:42:38 +0100 Subject: [PATCH 083/124] Code Review algorithm v2 The algorithm looks good to me. I just changed some names and added a few semi-colons. --- src/v2.js | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/v2.js b/src/v2.js index 5f2d014..b85ac38 100644 --- a/src/v2.js +++ b/src/v2.js @@ -15,8 +15,9 @@ module.exports = { }; function generatePassword(site, login, masterPassword, passwordProfile) { - return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - return renderPassword(entropy, passwordProfile) + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + return calcEntropy(site, login, masterPassword, _passwordProfile).then(function (entropy) { + return renderPassword(entropy, _passwordProfile); }); } @@ -26,17 +27,16 @@ var defaultPasswordProfile = { digits: true, symbols: true, length: 16, - counter: 1, + index: 1, iterations: 100000, keylen: 32, digest: 'sha256' }; function calcEntropy(site, login, masterPassword, passwordProfile) { - var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); return new Promise(function (resolve, reject) { - var salt = site + login + _passwordProfile.counter.toString(16); - pbkdf2.pbkdf2(masterPassword, salt, _passwordProfile.iterations, _passwordProfile.keylen, _passwordProfile.digest, function (error, key) { + var salt = site + login + passwordProfile.index.toString(16); + pbkdf2.pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest, function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -46,7 +46,7 @@ function calcEntropy(site, login, masterPassword, passwordProfile) { }); } -var subsetOfChars = { +var characterSubsets = { lowercase: 'abcdefghijklmnopqrstuvwxyz', uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', digits: '0123456789', @@ -55,22 +55,22 @@ var subsetOfChars = { function getSetOfCharacters(rules) { if (typeof rules === 'undefined') { - return subsetOfChars.lowercase + subsetOfChars.uppercase + subsetOfChars.digits + subsetOfChars.symbols; + return characterSubsets.lowercase + characterSubsets.uppercase + characterSubsets.digits + characterSubsets.symbols; } var setOfChars = ''; rules.forEach(function (rule) { - setOfChars += subsetOfChars[rule] + setOfChars += characterSubsets[rule]; }); return setOfChars; } function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { if (generatedPassword.length >= maxLength) { - return {value: generatedPassword, entropy: quotient} + return {value: generatedPassword, entropy: quotient}; } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); } function insertStringPseudoRandomly(generatedPassword, entropy, string) { @@ -85,24 +85,23 @@ function insertStringPseudoRandomly(generatedPassword, entropy, string) { function getOneCharPerRule(entropy, rules) { var oneCharPerRules = ''; rules.forEach(function (rule) { - var password = consumeEntropy('', entropy, subsetOfChars[rule], 1); + var password = consumeEntropy('', entropy, characterSubsets[rule], 1); oneCharPerRules += password.value; entropy = password.entropy; }); return {value: oneCharPerRules, entropy: entropy}; } -function validRules(passwordProfile) { +function getConfiguredRules(passwordProfile) { return ['lowercase', 'uppercase', 'digits', 'symbols'].filter(function (rule) { return passwordProfile[rule]; }); } function renderPassword(entropy, passwordProfile) { - var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); - var rules = validRules(_passwordProfile); + var rules = getConfiguredRules(passwordProfile); var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, _passwordProfile.length - rules.length); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, passwordProfile.length - rules.length); var charactersToAdd = getOneCharPerRule(password.entropy, rules); return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } From c00f24124eff075f91c2d21696216dde09c4002e Mon Sep 17 00:00:00 2001 From: Erik Mulder Date: Mon, 21 Nov 2016 12:56:12 +0100 Subject: [PATCH 084/124] Fixed export definition with new method name --- src/v2.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/v2.js b/src/v2.js index b85ac38..74853d6 100644 --- a/src/v2.js +++ b/src/v2.js @@ -8,7 +8,7 @@ module.exports = { _calcEntropy: calcEntropy, _consumeEntropy: consumeEntropy, _getSetOfCharacters: getSetOfCharacters, - _validRules: validRules, + _getConfiguredRules: getConfiguredRules, _insertStringPseudoRandomly: insertStringPseudoRandomly, _getOneCharPerRule: getOneCharPerRule, _renderPassword: renderPassword From 200d16d295eb4d868ef8595335afa25fb26f450f Mon Sep 17 00:00:00 2001 From: Erik Mulder Date: Mon, 21 Nov 2016 12:56:15 +0100 Subject: [PATCH 085/124] Fixed test definition with new method name --- tests/v2/setOfCharacters.tests.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js index 1798147..3e36778 100644 --- a/tests/v2/setOfCharacters.tests.js +++ b/tests/v2/setOfCharacters.tests.js @@ -44,11 +44,11 @@ describe('LessPass v2', function () { assert.equal(2, oneCharPerSetOfCharacters.value.length); assert.equal(1, oneCharPerSetOfCharacters.entropy); }); - it('valid rules', function () { - assert.deepEqual(['uppercase'], LessPass._validRules({uppercase: true})); - assert.deepEqual(['lowercase', 'uppercase'], LessPass._validRules({uppercase: true, lowercase: true})); - assert.deepEqual(['lowercase'], LessPass._validRules({lowercase: true, symbols: false})); - assert.deepEqual(['lowercase', 'uppercase', 'digits', 'symbols'], LessPass._validRules({ + it('configured rules', function () { + assert.deepEqual(['uppercase'], LessPass._getConfiguredRules({uppercase: true})); + assert.deepEqual(['lowercase', 'uppercase'], LessPass._getConfiguredRules({uppercase: true, lowercase: true})); + assert.deepEqual(['lowercase'], LessPass._getConfiguredRules({lowercase: true, symbols: false})); + assert.deepEqual(['lowercase', 'uppercase', 'digits', 'symbols'], LessPass._getConfiguredRules({ lowercase: true, uppercase: true, symbols: true, @@ -56,4 +56,4 @@ describe('LessPass v2', function () { })); }); }); -}); \ No newline at end of file +}); From f284359b18d0e6923caceda336fd2165e4a3656e Mon Sep 17 00:00:00 2001 From: Erik Mulder Date: Mon, 21 Nov 2016 14:10:53 +0100 Subject: [PATCH 086/124] Reverted code duplication prevention change Don't know why, but it doesn't work after the refactoring. Seemed pretty harmless. --- src/v2.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/v2.js b/src/v2.js index 74853d6..714bf75 100644 --- a/src/v2.js +++ b/src/v2.js @@ -15,9 +15,8 @@ module.exports = { }; function generatePassword(site, login, masterPassword, passwordProfile) { - var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); - return calcEntropy(site, login, masterPassword, _passwordProfile).then(function (entropy) { - return renderPassword(entropy, _passwordProfile); + return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { + return renderPassword(entropy, passwordProfile); }); } @@ -34,9 +33,10 @@ var defaultPasswordProfile = { }; function calcEntropy(site, login, masterPassword, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); return new Promise(function (resolve, reject) { - var salt = site + login + passwordProfile.index.toString(16); - pbkdf2.pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest, function (error, key) { + var salt = site + login + _passwordProfile.index.toString(16); + pbkdf2.pbkdf2(masterPassword, salt, _passwordProfile.iterations, _passwordProfile.keylen, _passwordProfile.digest, function (error, key) { if (error) { reject('error in pbkdf2'); } else { @@ -99,9 +99,10 @@ function getConfiguredRules(passwordProfile) { } function renderPassword(entropy, passwordProfile) { - var rules = getConfiguredRules(passwordProfile); + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + var rules = getConfiguredRules(_passwordProfile); var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, passwordProfile.length - rules.length); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, _passwordProfile.length - rules.length); var charactersToAdd = getOneCharPerRule(password.entropy, rules); return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } From b4178b9b4b92f3613da8096c7d197d0fda29896e Mon Sep 17 00:00:00 2001 From: Erik Mulder Date: Mon, 21 Nov 2016 14:14:36 +0100 Subject: [PATCH 087/124] Fix entropy test using new keyword index --- tests/v2/entropy.tests.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index e4fbb74..e1611d8 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -19,18 +19,18 @@ describe('LessPass v2', function () { iterations: 8192, keylen: 16, digest: 'sha512', - counter: 1 + index: 1 }; return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); }) }); - it('calc entropy different if counter different', function () { + it('calc entropy different if index different', function () { var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; - var passwordProfile1 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 1}; - var passwordProfile2 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 2}; + var passwordProfile1 = {iterations: 1, keylen: 16, digest: 'sha256', index: 1}; + var passwordProfile2 = {iterations: 1, keylen: 16, digest: 'sha256', index: 2}; var p1 = LessPass._calcEntropy(site, login, masterPassword, passwordProfile1); var p2 = LessPass._calcEntropy(site, login, masterPassword, passwordProfile2); return Promise.all([p1, p2]).then(function (entropies) { @@ -43,4 +43,4 @@ describe('LessPass v2', function () { assert.equal(1, password.entropy) }); }); -}); \ No newline at end of file +}); From 851b57e2e5402945c120bb6fe690bf11796672c3 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 21 Nov 2016 14:15:48 +0100 Subject: [PATCH 088/124] make tests pass --- index.js | 2 +- tests/v2/api.tests.js | 12 ++++++------ tests/v2/entropy.tests.js | 8 +++++++- tests/v2/renderPassword.tests.js | 13 ++++++++++--- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 16faf2d..77e75f9 100644 --- a/index.js +++ b/index.js @@ -17,7 +17,7 @@ module.exports = { _calcEntropy: v2._calcEntropy, _consumeEntropy: v2._consumeEntropy, _getSetOfCharacters: v2._getSetOfCharacters, - _validRules: v2._validRules, + _getConfiguredRules: v2._getConfiguredRules, _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, _getOneCharPerRule: v2._getOneCharPerRule, _renderPassword: v2._renderPassword, diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index 9958668..2fffb9a 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -13,7 +13,7 @@ describe('LessPass v2', function () { digits: true, symbols: true, length: 16, - counter: 1, + index: 1, version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { @@ -31,11 +31,11 @@ describe('LessPass v2', function () { digits: true, symbols: false, length: 14, - counter: 1, + index: 2, version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('y5Im77Ctww2695', generatedPassword); + assert.equal('MBAsB7b1Prt8Sl', generatedPassword); }); }); it('render password only digit', function () { @@ -49,11 +49,11 @@ describe('LessPass v2', function () { digits: true, symbols: false, length: 6, - counter: 1, + index: 3, version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('874623', generatedPassword); + assert.equal('117843', generatedPassword); }); }); it('render password no number', function () { @@ -67,7 +67,7 @@ describe('LessPass v2', function () { digits: false, symbols: true, length: 14, - counter: 1, + index: 1, version: 2 }; return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index e1611d8..a89e648 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -7,7 +7,13 @@ describe('LessPass v2', function () { var site = 'example.org'; var login = 'contact@example.org'; var masterPassword = 'password'; - return LessPass._calcEntropy(site, login, masterPassword).then(function (entropy) { + var passwordProfile = { + iterations: 100000, + keylen: 32, + digest: 'sha256', + index: 1 + }; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); }); }); diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js index b7e0e32..fb8eaad 100644 --- a/tests/v2/renderPassword.tests.js +++ b/tests/v2/renderPassword.tests.js @@ -1,17 +1,24 @@ var assert = chai.assert; describe('LessPass v2', function () { + var defaultPasswordProfile = { + length: 16, + lowercase: true, + uppercase: true, + digits: true, + symbols: true + }; it('render password use remainder of long division beetween entropy and set of chars length as an index', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal('W', LessPass._renderPassword(entropy)[0]); + assert.equal('W', LessPass._renderPassword(entropy, defaultPasswordProfile)[0]); }); it('render password use quotient as second entropy recursively', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal('H', LessPass._renderPassword(entropy)[1]); + assert.equal('H', LessPass._renderPassword(entropy, defaultPasswordProfile)[1]); }); it('render password has default length of 16', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal(16, LessPass._renderPassword(entropy).length); + assert.equal(16, LessPass._renderPassword(entropy, defaultPasswordProfile).length); }); it('render password can specify length', function () { var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; From 1aa19da4ab3480079fa1a30bffdc30a27f3b5bf5 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 21 Nov 2016 13:55:21 +0100 Subject: [PATCH 089/124] add pbkdf2 polyfill --- index.js | 3 ++ lib/lesspass.js | 104 ++++++++++++++++++++++++++++++++++++-------------- src/pbkdf2.js | 51 +++++++++++++++++++++++++ src/v2.js | 21 +++------- tests/helper.js | 2 +- tests/karma.config.js | 4 +- tests/pbkdf2.tests.js | 16 ++++++++ 7 files changed, 155 insertions(+), 46 deletions(-) create mode 100644 src/pbkdf2.js create mode 100644 tests/pbkdf2.tests.js diff --git a/index.js b/index.js index 77e75f9..1de11ad 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,6 @@ var v1 = require('./src/v1'); var v2 = require('./src/v2'); +var pbkdf2 = require('./src/pbkdf2'); module.exports = { encryptLogin: v1.encryptLogin, @@ -21,4 +22,6 @@ module.exports = { _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, _getOneCharPerRule: v2._getOneCharPerRule, _renderPassword: v2._renderPassword, + + pbkdf2: pbkdf2 }; \ No newline at end of file diff --git a/lib/lesspass.js b/lib/lesspass.js index 9ed1892..3b334c4 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -1,6 +1,7 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LessPass = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= maxLength) { - return {value: generatedPassword, entropy: quotient} + return {value: generatedPassword, entropy: quotient}; } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength) + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); } function insertStringPseudoRandomly(generatedPassword, entropy, string) { @@ -13746,14 +13792,14 @@ function insertStringPseudoRandomly(generatedPassword, entropy, string) { function getOneCharPerRule(entropy, rules) { var oneCharPerRules = ''; rules.forEach(function (rule) { - var password = consumeEntropy('', entropy, subsetOfChars[rule], 1); + var password = consumeEntropy('', entropy, characterSubsets[rule], 1); oneCharPerRules += password.value; entropy = password.entropy; }); return {value: oneCharPerRules, entropy: entropy}; } -function validRules(passwordProfile) { +function getConfiguredRules(passwordProfile) { return ['lowercase', 'uppercase', 'digits', 'symbols'].filter(function (rule) { return passwordProfile[rule]; }); @@ -13761,12 +13807,12 @@ function validRules(passwordProfile) { function renderPassword(entropy, passwordProfile) { var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); - var rules = validRules(_passwordProfile); + var rules = getConfiguredRules(_passwordProfile); var setOfCharacters = getSetOfCharacters(rules); var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, _passwordProfile.length - rules.length); var charactersToAdd = getOneCharPerRule(password.entropy, rules); return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } -},{"big-integer":3,"bluebird":4,"object-assign":19,"pbkdf2":20}]},{},[1])(1) +},{"./pbkdf2":47,"big-integer":3,"object-assign":19}]},{},[1])(1) }); \ No newline at end of file diff --git a/src/pbkdf2.js b/src/pbkdf2.js new file mode 100644 index 0000000..4506582 --- /dev/null +++ b/src/pbkdf2.js @@ -0,0 +1,51 @@ +var pbkdf2 = require('pbkdf2'); +var Promise = require("bluebird"); + + +function shouldUseNative() { + return !!(typeof window !== 'undefined' && window.crypto && window.crypto.subtle); +} + +function pbkdf2Native(password, salt, iterations, keylen, digest) { + var algorithms = { + 'sha1':'SHA-1', + 'sha-1':'SHA-1', + 'sha256':'SHA-256', + 'sha-256':'SHA-256', + 'sha512':'SHA-512', + 'sha-512':'SHA-512', + }; + return window.crypto.subtle.importKey('raw', Unibabel.utf8ToBuffer(password), 'PBKDF2', false, ['deriveKey']) + .then(function (key) { + var algo = { + name: 'PBKDF2', + salt: Unibabel.utf8ToBuffer(salt), + iterations: iterations, + hash: algorithms[digest.toLowerCase()], + }; + return window.crypto.subtle.deriveKey(algo, key, { + name: 'AES-CTR', + length: keylen * 8 + }, true, ['encrypt', 'decrypt']); + }) + .then(function (derivedKey) { + return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { + return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); + }); + }); +} + +function pbkdf2Browserified(password, salt, iterations, keylen, digest) { + return new Promise(function (resolve, reject) { + pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); +} + + +module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; \ No newline at end of file diff --git a/src/v2.js b/src/v2.js index 714bf75..f0e4102 100644 --- a/src/v2.js +++ b/src/v2.js @@ -1,5 +1,4 @@ -var Promise = require("bluebird"); -var pbkdf2 = require('pbkdf2'); +var pbkdf2 = require('./pbkdf2'); var bigInt = require("big-integer"); var objectAssign = require('object-assign'); @@ -15,8 +14,9 @@ module.exports = { }; function generatePassword(site, login, masterPassword, passwordProfile) { - return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - return renderPassword(entropy, passwordProfile); + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + return calcEntropy(site, login, masterPassword, _passwordProfile).then(function (entropy) { + return renderPassword(entropy, _passwordProfile); }); } @@ -33,17 +33,8 @@ var defaultPasswordProfile = { }; function calcEntropy(site, login, masterPassword, passwordProfile) { - var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); - return new Promise(function (resolve, reject) { - var salt = site + login + _passwordProfile.index.toString(16); - pbkdf2.pbkdf2(masterPassword, salt, _passwordProfile.iterations, _passwordProfile.keylen, _passwordProfile.digest, function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }); + var salt = site + login + passwordProfile.index.toString(16); + return pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest); } var characterSubsets = { diff --git a/tests/helper.js b/tests/helper.js index f7b3ea6..a8c194a 100644 --- a/tests/helper.js +++ b/tests/helper.js @@ -1,4 +1,4 @@ // globals global.chai = require('chai'); global.LessPass = require('../index'); -global.bigInt = require("big-integer"); +global.bigInt = require("big-integer"); \ No newline at end of file diff --git a/tests/karma.config.js b/tests/karma.config.js index 97309ea..775a1d0 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -5,6 +5,8 @@ module.exports = function (config) { files: [ 'node_modules/bluebird/js/browser/bluebird.core.min.js', 'node_modules/big-integer/BigInteger.min.js', + 'node_modules/unibabel/index.js', + 'node_modules/unibabel/unibabel.hex.js', 'lib/lesspass.js', 'tests/**/*.js' ], @@ -14,7 +16,7 @@ module.exports = function (config) { 'tests/karma.webcrypto.config.js', ], preprocessors: {}, - reporters: ['progress'], + reporters: ['spec'], port: 9876, colors: true, logLevel: config.LOG_INFO, diff --git a/tests/pbkdf2.tests.js b/tests/pbkdf2.tests.js new file mode 100644 index 0000000..c3f692d --- /dev/null +++ b/tests/pbkdf2.tests.js @@ -0,0 +1,16 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('pbkdf2', function () { + it('should secret, salt, 2, 32, sha256', function () { + return LessPass.pbkdf2('secret', 'salt', 2, 32, 'sha256').then(function (key) { + assert.equal('f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569', key); + }) + }); + }); +}); + + + + + From 58fc698627cc9bd4b2922e0f67192afb87764e3d Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 21 Nov 2016 15:12:50 +0100 Subject: [PATCH 090/124] remove webcrypto after pbkdf2 ponyfill --- example/lesspass.webcrypto.html | 35 ----- gulpfile.js | 13 -- lib/lesspass.js | 42 +++--- lib/lesspass.webcrypto.js | 310 ---------------------------------------- package.json | 6 +- src/pbkdf2.js | 20 +-- src/v1.js | 16 +-- tests/karma.config.js | 2 +- tests/karma.webcrypto.config.js | 30 ---- webcrypto.js | 158 -------------------- 10 files changed, 30 insertions(+), 602 deletions(-) delete mode 100644 example/lesspass.webcrypto.html delete mode 100644 gulpfile.js delete mode 100644 lib/lesspass.webcrypto.js delete mode 100644 tests/karma.webcrypto.config.js delete mode 100644 webcrypto.js diff --git a/example/lesspass.webcrypto.html b/example/lesspass.webcrypto.html deleted file mode 100644 index 2caf890..0000000 --- a/example/lesspass.webcrypto.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index 562f4db..0000000 --- a/gulpfile.js +++ /dev/null @@ -1,13 +0,0 @@ -var gulp = require('gulp'); -var concat = require('gulp-concat'); -var rename = require('gulp-rename'); - -gulp.task('webcrypto', function () { - return gulp.src(['node_modules/unibabel/index.js', 'node_modules/unibabel/unibabel.hex.js', 'webcrypto.js']) - .pipe(concat('lesspass.webcrypto.js')) - .pipe(gulp.dest('lib')); -}); - -gulp.task('default', ['webcrypto'], function () { -}); - diff --git a/lib/lesspass.js b/lib/lesspass.js index 3b334c4..605a733 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -13538,6 +13538,7 @@ function config (name) { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],47:[function(require,module,exports){ +(function (Buffer){ var pbkdf2 = require('pbkdf2'); var Promise = require("bluebird"); @@ -13548,18 +13549,18 @@ function shouldUseNative() { function pbkdf2Native(password, salt, iterations, keylen, digest) { var algorithms = { - 'sha1':'SHA-1', - 'sha-1':'SHA-1', - 'sha256':'SHA-256', - 'sha-256':'SHA-256', - 'sha512':'SHA-512', - 'sha-512':'SHA-512', + 'sha1': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha512': 'SHA-512', + 'sha-512': 'SHA-512', }; - return window.crypto.subtle.importKey('raw', Unibabel.utf8ToBuffer(password), 'PBKDF2', false, ['deriveKey']) + return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']) .then(function (key) { var algo = { name: 'PBKDF2', - salt: Unibabel.utf8ToBuffer(salt), + salt: new Buffer(salt), iterations: iterations, hash: algorithms[digest.toLowerCase()], }; @@ -13569,8 +13570,8 @@ function pbkdf2Native(password, salt, iterations, keylen, digest) { }, true, ['encrypt', 'decrypt']); }) .then(function (derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { - return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); + return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArray) { + return new Buffer(keyArray).toString('hex'); }); }); } @@ -13589,9 +13590,10 @@ function pbkdf2Browserified(password, salt, iterations, keylen, digest) { module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; -},{"bluebird":4,"pbkdf2":20}],48:[function(require,module,exports){ +}).call(this,require("buffer").Buffer) +},{"bluebird":4,"buffer":7,"pbkdf2":20}],48:[function(require,module,exports){ (function (Buffer){ -var pbkdf2 = require('pbkdf2'); +var pbkdf2 = require('./pbkdf2'); var createHMAC = require('create-hmac'); var Promise = require("bluebird"); @@ -13614,19 +13616,7 @@ function encryptLogin(login, masterPassword, options) { var _options = options !== undefined ? options : {}; var iterations = _options.iterations || 8192; var keylen = _options.keylen || 32; - - return new Promise(function (resolve, reject) { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); - } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }) + return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); } function renderPassword(encryptedLogin, site, passwordOptions) { @@ -13713,7 +13703,7 @@ function createFingerprint(str) { }); } }).call(this,require("buffer").Buffer) -},{"bluebird":4,"buffer":7,"create-hmac":13,"pbkdf2":20}],49:[function(require,module,exports){ +},{"./pbkdf2":47,"bluebird":4,"buffer":7,"create-hmac":13}],49:[function(require,module,exports){ var pbkdf2 = require('./pbkdf2'); var bigInt = require("big-integer"); var objectAssign = require('object-assign'); diff --git a/lib/lesspass.webcrypto.js b/lib/lesspass.webcrypto.js deleted file mode 100644 index 0e52f1e..0000000 --- a/lib/lesspass.webcrypto.js +++ /dev/null @@ -1,310 +0,0 @@ -(function () { -'use strict'; - -function utf8ToBinaryString(str) { - var escstr = encodeURIComponent(str); - // replaces any uri escape sequence, such as %0A, - // with binary escape, such as 0x0A - var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) { - return String.fromCharCode(parseInt(p1, 16)); - }); - - return binstr; -} - -function utf8ToBuffer(str) { - var binstr = utf8ToBinaryString(str); - var buf = binaryStringToBuffer(binstr); - return buf; -} - -function utf8ToBase64(str) { - var binstr = utf8ToBinaryString(str); - return btoa(binstr); -} - -function binaryStringToUtf8(binstr) { - var escstr = binstr.replace(/(.)/g, function (m, p) { - var code = p.charCodeAt(0).toString(16).toUpperCase(); - if (code.length < 2) { - code = '0' + code; - } - return '%' + code; - }); - - return decodeURIComponent(escstr); -} - -function bufferToUtf8(buf) { - var binstr = bufferToBinaryString(buf); - - return binaryStringToUtf8(binstr); -} - -function base64ToUtf8(b64) { - var binstr = atob(b64); - - return binaryStringToUtf8(binstr); -} - -function bufferToBinaryString(buf) { - var binstr = Array.prototype.map.call(buf, function (ch) { - return String.fromCharCode(ch); - }).join(''); - - return binstr; -} - -function bufferToBase64(arr) { - var binstr = bufferToBinaryString(arr); - return btoa(binstr); -} - -function binaryStringToBuffer(binstr) { - var buf; - - if ('undefined' !== typeof Uint8Array) { - buf = new Uint8Array(binstr.length); - } else { - buf = []; - } - - Array.prototype.forEach.call(binstr, function (ch, i) { - buf[i] = ch.charCodeAt(0); - }); - - return buf; -} - -function base64ToBuffer(base64) { - var binstr = atob(base64); - var buf = binaryStringToBuffer(binstr); - return buf; -} - -window.Unibabel = { - utf8ToBinaryString: utf8ToBinaryString -, utf8ToBuffer: utf8ToBuffer -, utf8ToBase64: utf8ToBase64 -, binaryStringToUtf8: binaryStringToUtf8 -, bufferToUtf8: bufferToUtf8 -, base64ToUtf8: base64ToUtf8 -, bufferToBinaryString: bufferToBinaryString -, bufferToBase64: bufferToBase64 -, binaryStringToBuffer: binaryStringToBuffer -, base64ToBuffer: base64ToBuffer - -// compat -, strToUtf8Arr: utf8ToBuffer -, utf8ArrToStr: bufferToUtf8 -, arrToBase64: bufferToBase64 -, base64ToArr: base64ToBuffer -}; - -}()); - -(function () { -'use strict'; - -function bufferToHex(arr) { - var i; - var len; - var hex = ''; - var c; - - for (i = 0, len = arr.length; i < len; i += 1) { - c = arr[i].toString(16); - if (c.length < 2) { - c = '0' + c; - } - hex += c; - } - - return hex; -} - -function hexToBuffer(hex) { - // TODO use Uint8Array or ArrayBuffer or DataView - var i; - var byteLen = hex.length / 2; - var arr; - var j = 0; - - if (byteLen !== parseInt(byteLen, 10)) { - throw new Error("Invalid hex length '" + hex.length + "'"); - } - - arr = new Uint8Array(byteLen); - - for (i = 0; i < byteLen; i += 1) { - arr[i] = parseInt(hex[j] + hex[j + 1], 16); - j += 2; - } - - return arr; -} - -// Hex Convenience Functions -window.Unibabel.hexToBuffer = hexToBuffer; -window.Unibabel.bufferToHex = bufferToHex; - -}()); - -(function () { - 'use strict'; - - if (window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle) { - window.crypto.subtle = window.crypto.webkitSubtle; - } - if (!window.crypto || !window.crypto.subtle) { - console.error("Your browser does not support the Web Cryptography API! LessPass will not work."); - return; - } - - function importKey(masterPassword, algo, usages) { - var format = 'raw'; - var masterPasswordArrayBuffer = Unibabel.utf8ToBuffer(masterPassword); - var extractable = false; - return window.crypto.subtle.importKey(format, masterPasswordArrayBuffer, algo, extractable, usages); - } - - function deriveKey(masterKey, salt, iterations, keylen) { - var algo = { - name: 'PBKDF2', - salt: Unibabel.utf8ToBuffer(salt), - iterations: iterations, - hash: 'SHA-256', - }; - var extractable = true; - var derivedKeyAlgo = {name: 'AES-CTR', length: keylen * 8}; - var usages = ['encrypt', 'decrypt']; - return window.crypto.subtle.deriveKey(algo, masterKey, derivedKeyAlgo, extractable, usages); - } - - - function exportKey(derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { - return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); - }); - } - - function encryptLogin(login, masterPassword, options) { - var _options = options !== undefined ? options : {}; - var iterations = _options.iterations || 8192; - var keylen = _options.keylen || 32; - - return importKey(masterPassword, 'PBKDF2', ['deriveKey']) - .then(function (key) { - return deriveKey(key, login, iterations, keylen); - }) - .then(exportKey); - } - - function signKey(masterKey, salt) { - var algo = {name: 'HMAC'}; - var saltArrayBuffer = Unibabel.utf8ToBuffer(salt); - return window.crypto.subtle.sign(algo, masterKey, saltArrayBuffer); - } - - function _createHmac(encryptedLogin, salt) { - return importKey(encryptedLogin, {name: 'HMAC', hash: {name: 'SHA-256'}}, ['sign']) - .then(function (key) { - return signKey(key, salt); - }) - .then(function (derivedHmacKey) { - return Unibabel.bufferToHex(new Uint8Array(derivedHmacKey)) - }); - } - - function _deriveEncryptedLogin(encryptedLogin, site) { - var passwordOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { - length: 12, - counter: 1 - }; - - var salt = site + passwordOptions.counter.toString(); - return _createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, passwordOptions.length); - }); - } - - function createFingerprint(str) { - return _createHmac(str, ''); - } - - function renderPassword(encryptedLogin, site, passwordOptions) { - return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = passwordOptions.template || LessPass._getPasswordTemplate(passwordOptions); - return LessPass._prettyPrint(derivedEncryptedLogin, template); - }); - } - - function _getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - var template = ''; - for (var templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] - } - } - return template; - } - - - function _prettyPrint(hash, template) { - var password = ''; - - _string2charCodes(hash).forEach(function (charCode, index) { - var charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; - } - - function _string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; - } - - function _getCharType(template, index) { - return template[index % template.length]; - } - - function _getPasswordChar(charType, index) { - var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; - } - - window.LessPass = { - encryptLogin: encryptLogin, - renderPassword: renderPassword, - createFingerprint: createFingerprint, - _createHmac: _createHmac, - _deriveEncryptedLogin: _deriveEncryptedLogin, - _getPasswordTemplate: _getPasswordTemplate, - _prettyPrint: _prettyPrint, - _string2charCodes: _string2charCodes, - _getCharType: _getCharType, - _getPasswordChar: _getPasswordChar, - }; -}()); - diff --git a/package.json b/package.json index 6371006..6cdfa8c 100644 --- a/package.json +++ b/package.json @@ -15,11 +15,10 @@ "main": "index.js", "repository": "lesspass/core", "scripts": { - "build": "rimraf lib && mkdir lib && browserify --standalone LessPass index.js > lib/lesspass.js && gulp", + "build": "rimraf lib && mkdir lib && browserify --standalone LessPass index.js > lib/lesspass.js", "prepublish": "npm test && npm run build && npm run test:node && npm run test:browser", "test": "mocha --require ./tests/helper.js tests/*", "test:node": "npm run build && cd tests && node node.js && cd ..", - "test:webcrypto": "karma start tests/karma.webcrypto.config.js", "test:browser": "npm run build && karma start tests/karma.config.js" }, "dependencies": { @@ -33,9 +32,6 @@ "devDependencies": { "browserify": "^13.1.1", "chai": "^3.5.0", - "gulp": "^3.9.1", - "gulp-concat": "^2.6.1", - "gulp-rename": "^1.2.2", "karma": "^1.3.0", "karma-chai": "^0.1.0", "karma-chrome-launcher": "^2.0.0", diff --git a/src/pbkdf2.js b/src/pbkdf2.js index 4506582..a601473 100644 --- a/src/pbkdf2.js +++ b/src/pbkdf2.js @@ -8,18 +8,18 @@ function shouldUseNative() { function pbkdf2Native(password, salt, iterations, keylen, digest) { var algorithms = { - 'sha1':'SHA-1', - 'sha-1':'SHA-1', - 'sha256':'SHA-256', - 'sha-256':'SHA-256', - 'sha512':'SHA-512', - 'sha-512':'SHA-512', + 'sha1': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha512': 'SHA-512', + 'sha-512': 'SHA-512', }; - return window.crypto.subtle.importKey('raw', Unibabel.utf8ToBuffer(password), 'PBKDF2', false, ['deriveKey']) + return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']) .then(function (key) { var algo = { name: 'PBKDF2', - salt: Unibabel.utf8ToBuffer(salt), + salt: new Buffer(salt), iterations: iterations, hash: algorithms[digest.toLowerCase()], }; @@ -29,8 +29,8 @@ function pbkdf2Native(password, salt, iterations, keylen, digest) { }, true, ['encrypt', 'decrypt']); }) .then(function (derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { - return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); + return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArray) { + return new Buffer(keyArray).toString('hex'); }); }); } diff --git a/src/v1.js b/src/v1.js index 1ab4259..5225290 100644 --- a/src/v1.js +++ b/src/v1.js @@ -1,4 +1,4 @@ -var pbkdf2 = require('pbkdf2'); +var pbkdf2 = require('./pbkdf2'); var createHMAC = require('create-hmac'); var Promise = require("bluebird"); @@ -21,19 +21,7 @@ function encryptLogin(login, masterPassword, options) { var _options = options !== undefined ? options : {}; var iterations = _options.iterations || 8192; var keylen = _options.keylen || 32; - - return new Promise(function (resolve, reject) { - if (!login || !masterPassword) { - reject('login and master password parameters could not be empty'); - } - pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); - }) + return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); } function renderPassword(encryptedLogin, site, passwordOptions) { diff --git a/tests/karma.config.js b/tests/karma.config.js index 775a1d0..842e845 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -16,7 +16,7 @@ module.exports = function (config) { 'tests/karma.webcrypto.config.js', ], preprocessors: {}, - reporters: ['spec'], + reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, diff --git a/tests/karma.webcrypto.config.js b/tests/karma.webcrypto.config.js deleted file mode 100644 index d7be84c..0000000 --- a/tests/karma.webcrypto.config.js +++ /dev/null @@ -1,30 +0,0 @@ -module.exports = function (config) { - var configuration = { - basePath: '..', - frameworks: ['mocha', 'chai'], - files: [ - 'node_modules/unibabel/index.js', - 'node_modules/unibabel/unibabel.hex.js', - 'webcrypto.js', - 'tests/**/*.js' - ], - exclude: [ - 'tests/node.js', - 'tests/helper.js', - 'tests/karma.config.js', - ], - preprocessors: {}, - reporters: ['progress'], - port: 9876, - colors: true, - logLevel: config.LOG_INFO, - autoWatch: true, - browsers: ['Chrome', 'Firefox'], - singleRun: true, - concurrency: Infinity - }; - if (process.env.TRAVIS) { - configuration.browsers = ['PhantomJS']; - } - config.set(configuration) -}; diff --git a/webcrypto.js b/webcrypto.js deleted file mode 100644 index d606127..0000000 --- a/webcrypto.js +++ /dev/null @@ -1,158 +0,0 @@ -(function () { - 'use strict'; - - if (window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle) { - window.crypto.subtle = window.crypto.webkitSubtle; - } - if (!window.crypto || !window.crypto.subtle) { - console.error("Your browser does not support the Web Cryptography API! LessPass will not work."); - return; - } - - function importKey(masterPassword, algo, usages) { - var format = 'raw'; - var masterPasswordArrayBuffer = Unibabel.utf8ToBuffer(masterPassword); - var extractable = false; - return window.crypto.subtle.importKey(format, masterPasswordArrayBuffer, algo, extractable, usages); - } - - function deriveKey(masterKey, salt, iterations, keylen) { - var algo = { - name: 'PBKDF2', - salt: Unibabel.utf8ToBuffer(salt), - iterations: iterations, - hash: 'SHA-256', - }; - var extractable = true; - var derivedKeyAlgo = {name: 'AES-CTR', length: keylen * 8}; - var usages = ['encrypt', 'decrypt']; - return window.crypto.subtle.deriveKey(algo, masterKey, derivedKeyAlgo, extractable, usages); - } - - - function exportKey(derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArrayBuffer) { - return Unibabel.bufferToHex(new Uint8Array(keyArrayBuffer)); - }); - } - - function encryptLogin(login, masterPassword, options) { - var _options = options !== undefined ? options : {}; - var iterations = _options.iterations || 8192; - var keylen = _options.keylen || 32; - - return importKey(masterPassword, 'PBKDF2', ['deriveKey']) - .then(function (key) { - return deriveKey(key, login, iterations, keylen); - }) - .then(exportKey); - } - - function signKey(masterKey, salt) { - var algo = {name: 'HMAC'}; - var saltArrayBuffer = Unibabel.utf8ToBuffer(salt); - return window.crypto.subtle.sign(algo, masterKey, saltArrayBuffer); - } - - function _createHmac(encryptedLogin, salt) { - return importKey(encryptedLogin, {name: 'HMAC', hash: {name: 'SHA-256'}}, ['sign']) - .then(function (key) { - return signKey(key, salt); - }) - .then(function (derivedHmacKey) { - return Unibabel.bufferToHex(new Uint8Array(derivedHmacKey)) - }); - } - - function _deriveEncryptedLogin(encryptedLogin, site) { - var passwordOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { - length: 12, - counter: 1 - }; - - var salt = site + passwordOptions.counter.toString(); - return _createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, passwordOptions.length); - }); - } - - function createFingerprint(str) { - return _createHmac(str, ''); - } - - function renderPassword(encryptedLogin, site, passwordOptions) { - return _deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = passwordOptions.template || LessPass._getPasswordTemplate(passwordOptions); - return LessPass._prettyPrint(derivedEncryptedLogin, template); - }); - } - - function _getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - var template = ''; - for (var templateKey in templates) { - if (passwordTypes.hasOwnProperty(templateKey) && passwordTypes[templateKey]) { - template += templates[templateKey] - } - } - return template; - } - - - function _prettyPrint(hash, template) { - var password = ''; - - _string2charCodes(hash).forEach(function (charCode, index) { - var charType = _getCharType(template, index); - password += _getPasswordChar(charType, charCode); - }); - return password; - } - - function _string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; - } - - function _getCharType(template, index) { - return template[index % template.length]; - } - - function _getPasswordChar(charType, index) { - var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; - } - - window.LessPass = { - encryptLogin: encryptLogin, - renderPassword: renderPassword, - createFingerprint: createFingerprint, - _createHmac: _createHmac, - _deriveEncryptedLogin: _deriveEncryptedLogin, - _getPasswordTemplate: _getPasswordTemplate, - _prettyPrint: _prettyPrint, - _string2charCodes: _string2charCodes, - _getCharType: _getCharType, - _getPasswordChar: _getPasswordChar, - }; -}()); - From 6409029d8342c60af1ad6d8109425634afc4fda3 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 21 Nov 2016 15:16:57 +0100 Subject: [PATCH 091/124] use pinkie-promise for smaller bundle size --- lib/lesspass.js | 5998 ++++--------------------------------------------------- package.json | 2 +- src/pbkdf2.js | 2 +- src/v1.js | 2 +- 4 files changed, 352 insertions(+), 5652 deletions(-) diff --git a/lib/lesspass.js b/lib/lesspass.js index 605a733..347ba91 100644 --- a/lib/lesspass.js +++ b/lib/lesspass.js @@ -26,7 +26,7 @@ module.exports = { pbkdf2: pbkdf2 }; -},{"./src/pbkdf2":47,"./src/v1":48,"./src/v2":49}],2:[function(require,module,exports){ +},{"./src/pbkdf2":48,"./src/v1":49,"./src/v2":50}],2:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -1359,5609 +1359,8 @@ if (typeof module !== "undefined" && module.hasOwnProperty("exports")) { } },{}],4:[function(require,module,exports){ -(function (process,global){ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2015 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -/** - * bluebird build version 3.4.6 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - -},{}],4:[function(_dereq_,module,exports){ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = _dereq_("./promise")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - -},{"./promise":22}],5:[function(_dereq_,module,exports){ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (!true) { -var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); -}; - -var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -}; - -var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -}; - -getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); -}; - -getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); -}; -} - -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = "Object " + util.classString(obj) + " has no method '" + - util.toString(methodName) + "'"; - throw new Promise.TypeError(message); - } - return fn; -} - -function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var args = [].slice.call(arguments, 1);; - if (!true) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; - -},{"./util":36}],6:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -},{"./util":36}],7:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util"); -var getKeys = _dereq_("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - -},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - -},{}],9:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - async.invokeLater(this._notifyUnhandledRejection, this, undefined); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0) { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; - -},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - - -},{}],12:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var Objectfreeze = es5.freeze; -var util = _dereq_("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - -},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ -var isES5 = (function(){ - "use strict"; - return this === undefined; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; - - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; - - var ObjectFreeze = function (obj) { - return obj; - }; - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; -} - -},{}],14:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - -},{}],15:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -return PassThroughHandlerContext; -}; - -},{"./util":36}],16:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = _dereq_("./errors"); -var TypeError = errors.TypeError; -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - -},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (!true) { -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (!true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util":36}],18:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); -}; - -MappingPromiseArray.prototype._init = function () {}; - -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; - -},{"./util":36}],19:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - -},{"./util":36}],20:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors"); -var OperationalError = errors.OperationalError; -var es5 = _dereq_("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - -},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var util = _dereq_("./util"); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; - -},{"./util":36}],22:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = _dereq_("./util"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = _dereq_("./es5"); -var Async = _dereq_("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = _dereq_("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = _dereq_("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - if (self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -} - -function Promise(executor) { - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - if (executor !== INTERNAL) { - check(this, executor); - this._resolveFromExecutor(executor); - } - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("expecting an object but got " + - "A catch statement predicate " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); -_dereq_("./direct_resolve")(Promise); -_dereq_("./synchronous_inspection")(Promise); -_dereq_("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.4.6"; -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./call_get.js')(Promise); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -_dereq_('./timers.js')(Promise, INTERNAL, debug); -_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -_dereq_('./nodeify.js')(Promise); -_dereq_('./promisify.js')(Promise, INTERNAL); -_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); -_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); -_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./settle.js')(Promise, PromiseArray, debug); -_dereq_('./some.js')(Promise, PromiseArray, apiRejection); -_dereq_('./filter.js')(Promise, INTERNAL); -_dereq_('./each.js')(Promise, INTERNAL); -_dereq_('./any.js')(Promise); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; - -},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = _dereq_("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util":36}],24:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = _dereq_("./util"); -var nodebackForPromise = _dereq_("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = _dereq_("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (!true) { -var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; -}; - -var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); -}; - -var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); -}; - -var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -}; - -makeNodePromisifiedEval = -function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - - -},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); -var isObject = util.isObject; -var es5 = _dereq_("./es5"); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - -},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ -"use strict"; -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; -} - -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype._unshiftOne = function(value) { - var capacity = this._capacity; - this._checkCapacity(this.length() + 1); - var front = this._front; - var i = (((( front - 1 ) & - ( capacity - 1) ) ^ capacity ) - capacity ); - this[i] = value; - this._front = i; - this._length = this.length() + 1; -}; - -Queue.prototype.unshift = function(fn, receiver, arg) { - this._unshiftOne(arg); - this._unshiftOne(receiver); - this._unshiftOne(fn); -}; - -Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function () { - return this._length; -}; - -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } -}; - -Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); -}; - -module.exports = Queue; - -},{}],27:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - -},{"./util":36}],28:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; - -},{"./util":36}],29:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - -},{"./util":36}],30:[function(_dereq_,module,exports){ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = _dereq_("./util"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; - -},{"./util":36}],31:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = _dereq_("./util"); -var RangeError = _dereq_("./errors").RangeError; -var AggregateError = _dereq_("./errors").AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - -},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],33:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - -},{"./util":36}],34:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = _dereq_("./util"); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; - -},{"./util":36}],35:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = _dereq_("./util"); - var TypeError = _dereq_("./errors").TypeError; - var inherits = _dereq_("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; -}; - -},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"; -} - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); -} - -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -function env(key, def) { - return isNode ? process.env[key] : def; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":13}]},{},[4])(4) -}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":23}],5:[function(require,module,exports){ - -},{}],6:[function(require,module,exports){ +},{}],5:[function(require,module,exports){ (function (global){ 'use strict'; @@ -7073,7 +1472,7 @@ exports.allocUnsafeSlow = function allocUnsafeSlow(size) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"buffer":7}],7:[function(require,module,exports){ +},{"buffer":6}],6:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -8866,7 +3265,7 @@ function isnan (val) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":2,"ieee754":15,"isarray":18}],8:[function(require,module,exports){ +},{"base64-js":2,"ieee754":14,"isarray":17}],7:[function(require,module,exports){ (function (Buffer){ var Transform = require('stream').Transform var inherits = require('inherits') @@ -8960,7 +3359,7 @@ CipherBase.prototype._toString = function (value, enc, fin) { } }).call(this,require("buffer").Buffer) -},{"buffer":7,"inherits":16,"stream":44,"string_decoder":45}],9:[function(require,module,exports){ +},{"buffer":6,"inherits":15,"stream":45,"string_decoder":46}],8:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -9071,7 +3470,7 @@ function objectToString(o) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":17}],10:[function(require,module,exports){ +},{"../../is-buffer/index.js":16}],9:[function(require,module,exports){ (function (Buffer){ 'use strict'; var inherits = require('inherits') @@ -9127,7 +3526,7 @@ module.exports = function createHash (alg) { } }).call(this,require("buffer").Buffer) -},{"./md5":12,"buffer":7,"cipher-base":8,"inherits":16,"ripemd160":35,"sha.js":37}],11:[function(require,module,exports){ +},{"./md5":11,"buffer":6,"cipher-base":7,"inherits":15,"ripemd160":36,"sha.js":38}],10:[function(require,module,exports){ (function (Buffer){ 'use strict'; var intSize = 4; @@ -9164,7 +3563,7 @@ function hash(buf, fn, hashSize, bigEndian) { } exports.hash = hash; }).call(this,require("buffer").Buffer) -},{"buffer":7}],12:[function(require,module,exports){ +},{"buffer":6}],11:[function(require,module,exports){ 'use strict'; /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message @@ -9321,7 +3720,7 @@ function bit_rol(num, cnt) module.exports = function md5(buf) { return helpers.hash(buf, core_md5, 16); }; -},{"./helpers":11}],13:[function(require,module,exports){ +},{"./helpers":10}],12:[function(require,module,exports){ (function (Buffer){ 'use strict'; var createHash = require('create-hash/browser'); @@ -9393,7 +3792,7 @@ module.exports = function createHmac(alg, key) { } }).call(this,require("buffer").Buffer) -},{"buffer":7,"create-hash/browser":10,"inherits":16,"stream":44}],14:[function(require,module,exports){ +},{"buffer":6,"create-hash/browser":9,"inherits":15,"stream":45}],13:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -9697,7 +4096,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],15:[function(require,module,exports){ +},{}],14:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -9783,7 +4182,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],16:[function(require,module,exports){ +},{}],15:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -9808,7 +4207,7 @@ if (typeof Object.create === 'function') { } } -},{}],17:[function(require,module,exports){ +},{}],16:[function(require,module,exports){ /*! * Determine if an object is a Buffer * @@ -9831,14 +4230,14 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -},{}],18:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],19:[function(require,module,exports){ +},{}],18:[function(require,module,exports){ 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; @@ -9923,7 +4322,7 @@ module.exports = shouldUseNative() ? Object.assign : function (target, source) { return to; }; -},{}],20:[function(require,module,exports){ +},{}],19:[function(require,module,exports){ (function (process,Buffer){ var createHmac = require('create-hmac') var checkParameters = require('./precondition') @@ -9995,7 +4394,7 @@ exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { } }).call(this,require('_process'),require("buffer").Buffer) -},{"./precondition":21,"_process":23,"buffer":7,"create-hmac":13}],21:[function(require,module,exports){ +},{"./precondition":20,"_process":24,"buffer":6,"create-hmac":12}],20:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { @@ -10015,7 +4414,308 @@ module.exports = function (iterations, keylen) { } } -},{}],22:[function(require,module,exports){ +},{}],21:[function(require,module,exports){ +'use strict'; + +module.exports = typeof Promise === 'function' ? Promise : require('pinkie'); + +},{"pinkie":22}],22:[function(require,module,exports){ +(function (global){ +'use strict'; + +var PENDING = 'pending'; +var SETTLED = 'settled'; +var FULFILLED = 'fulfilled'; +var REJECTED = 'rejected'; +var NOOP = function () {}; +var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function'; + +var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; +var asyncQueue = []; +var asyncTimer; + +function asyncFlush() { + // run promise callbacks + for (var i = 0; i < asyncQueue.length; i++) { + asyncQueue[i][0](asyncQueue[i][1]); + } + + // reset async asyncQueue + asyncQueue = []; + asyncTimer = false; +} + +function asyncCall(callback, arg) { + asyncQueue.push([callback, arg]); + + if (!asyncTimer) { + asyncTimer = true; + asyncSetTimer(asyncFlush, 0); + } +} + +function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } + + function rejectPromise(reason) { + reject(promise, reason); + } + + try { + resolver(resolvePromise, rejectPromise); + } catch (e) { + rejectPromise(e); + } +} + +function invokeCallback(subscriber) { + var owner = subscriber.owner; + var settled = owner._state; + var value = owner._data; + var callback = subscriber[settled]; + var promise = subscriber.then; + + if (typeof callback === 'function') { + settled = FULFILLED; + try { + value = callback(value); + } catch (e) { + reject(promise, e); + } + } + + if (!handleThenable(promise, value)) { + if (settled === FULFILLED) { + resolve(promise, value); + } + + if (settled === REJECTED) { + reject(promise, value); + } + } +} + +function handleThenable(promise, value) { + var resolved; + + try { + if (promise === value) { + throw new TypeError('A promises callback cannot return that same promise.'); + } + + if (value && (typeof value === 'function' || typeof value === 'object')) { + // then should be retrieved only once + var then = value.then; + + if (typeof then === 'function') { + then.call(value, function (val) { + if (!resolved) { + resolved = true; + + if (value === val) { + fulfill(promise, val); + } else { + resolve(promise, val); + } + } + }, function (reason) { + if (!resolved) { + resolved = true; + + reject(promise, reason); + } + }); + + return true; + } + } + } catch (e) { + if (!resolved) { + reject(promise, e); + } + + return true; + } + + return false; +} + +function resolve(promise, value) { + if (promise === value || !handleThenable(promise, value)) { + fulfill(promise, value); + } +} + +function fulfill(promise, value) { + if (promise._state === PENDING) { + promise._state = SETTLED; + promise._data = value; + + asyncCall(publishFulfillment, promise); + } +} + +function reject(promise, reason) { + if (promise._state === PENDING) { + promise._state = SETTLED; + promise._data = reason; + + asyncCall(publishRejection, promise); + } +} + +function publish(promise) { + promise._then = promise._then.forEach(invokeCallback); +} + +function publishFulfillment(promise) { + promise._state = FULFILLED; + publish(promise); +} + +function publishRejection(promise) { + promise._state = REJECTED; + publish(promise); + if (!promise._handled && isNode) { + global.process.emit('unhandledRejection', promise._data, promise); + } +} + +function notifyRejectionHandled(promise) { + global.process.emit('rejectionHandled', promise); +} + +/** + * @class + */ +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('Promise resolver ' + resolver + ' is not a function'); + } + + if (this instanceof Promise === false) { + throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); + } + + this._then = []; + + invokeResolver(resolver, this); +} + +Promise.prototype = { + constructor: Promise, + + _state: PENDING, + _then: null, + _data: undefined, + _handled: false, + + then: function (onFulfillment, onRejection) { + var subscriber = { + owner: this, + then: new this.constructor(NOOP), + fulfilled: onFulfillment, + rejected: onRejection + }; + + if ((onRejection || onFulfillment) && !this._handled) { + this._handled = true; + if (this._state === REJECTED && isNode) { + asyncCall(notifyRejectionHandled, this); + } + } + + if (this._state === FULFILLED || this._state === REJECTED) { + // already resolved, call callback async + asyncCall(invokeCallback, subscriber); + } else { + // subscribe + this._then.push(subscriber); + } + + return subscriber.then; + }, + + catch: function (onRejection) { + return this.then(null, onRejection); + } +}; + +Promise.all = function (promises) { + if (!Array.isArray(promises)) { + throw new TypeError('You must pass an array to Promise.all().'); + } + + return new Promise(function (resolve, reject) { + var results = []; + var remaining = 0; + + function resolver(index) { + remaining++; + return function (value) { + results[index] = value; + if (!--remaining) { + resolve(results); + } + }; + } + + for (var i = 0, promise; i < promises.length; i++) { + promise = promises[i]; + + if (promise && typeof promise.then === 'function') { + promise.then(resolver(i), reject); + } else { + results[i] = promise; + } + } + + if (!remaining) { + resolve(results); + } + }); +}; + +Promise.race = function (promises) { + if (!Array.isArray(promises)) { + throw new TypeError('You must pass an array to Promise.race().'); + } + + return new Promise(function (resolve, reject) { + for (var i = 0, promise; i < promises.length; i++) { + promise = promises[i]; + + if (promise && typeof promise.then === 'function') { + promise.then(resolve, reject); + } else { + resolve(promise); + } + } + }); +}; + +Promise.resolve = function (value) { + if (value && typeof value === 'object' && value.constructor === Promise) { + return value; + } + + return new Promise(function (resolve) { + resolve(value); + }); +}; + +Promise.reject = function (reason) { + return new Promise(function (resolve, reject) { + reject(reason); + }); +}; + +module.exports = Promise; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],23:[function(require,module,exports){ (function (process){ 'use strict'; @@ -10062,7 +4762,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":23}],23:[function(require,module,exports){ +},{"_process":24}],24:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -10244,10 +4944,10 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],24:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ module.exports = require("./lib/_stream_duplex.js") -},{"./lib/_stream_duplex.js":25}],25:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":26}],26:[function(require,module,exports){ // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from @@ -10323,7 +5023,7 @@ function forEach(xs, f) { f(xs[i], i); } } -},{"./_stream_readable":27,"./_stream_writable":29,"core-util-is":9,"inherits":16,"process-nextick-args":22}],26:[function(require,module,exports){ +},{"./_stream_readable":28,"./_stream_writable":30,"core-util-is":8,"inherits":15,"process-nextick-args":23}],27:[function(require,module,exports){ // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. @@ -10350,7 +5050,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":28,"core-util-is":9,"inherits":16}],27:[function(require,module,exports){ +},{"./_stream_transform":29,"core-util-is":8,"inherits":15}],28:[function(require,module,exports){ (function (process){ 'use strict'; @@ -11290,7 +5990,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process')) -},{"./_stream_duplex":25,"./internal/streams/BufferList":30,"_process":23,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"isarray":18,"process-nextick-args":22,"string_decoder/":45,"util":5}],28:[function(require,module,exports){ +},{"./_stream_duplex":26,"./internal/streams/BufferList":31,"_process":24,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"isarray":17,"process-nextick-args":23,"string_decoder/":46,"util":4}],29:[function(require,module,exports){ // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -11471,7 +6171,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":25,"core-util-is":9,"inherits":16}],29:[function(require,module,exports){ +},{"./_stream_duplex":26,"core-util-is":8,"inherits":15}],30:[function(require,module,exports){ (function (process){ // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all @@ -12000,7 +6700,7 @@ function CorkedRequest(state) { }; } }).call(this,require('_process')) -},{"./_stream_duplex":25,"_process":23,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"process-nextick-args":22,"util-deprecate":46}],30:[function(require,module,exports){ +},{"./_stream_duplex":26,"_process":24,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"process-nextick-args":23,"util-deprecate":47}],31:[function(require,module,exports){ 'use strict'; var Buffer = require('buffer').Buffer; @@ -12065,10 +6765,10 @@ BufferList.prototype.concat = function (n) { } return ret; }; -},{"buffer":7,"buffer-shims":6}],31:[function(require,module,exports){ +},{"buffer":6,"buffer-shims":5}],32:[function(require,module,exports){ module.exports = require("./lib/_stream_passthrough.js") -},{"./lib/_stream_passthrough.js":26}],32:[function(require,module,exports){ +},{"./lib/_stream_passthrough.js":27}],33:[function(require,module,exports){ (function (process){ var Stream = (function (){ try { @@ -12088,13 +6788,13 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { } }).call(this,require('_process')) -},{"./lib/_stream_duplex.js":25,"./lib/_stream_passthrough.js":26,"./lib/_stream_readable.js":27,"./lib/_stream_transform.js":28,"./lib/_stream_writable.js":29,"_process":23}],33:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":26,"./lib/_stream_passthrough.js":27,"./lib/_stream_readable.js":28,"./lib/_stream_transform.js":29,"./lib/_stream_writable.js":30,"_process":24}],34:[function(require,module,exports){ module.exports = require("./lib/_stream_transform.js") -},{"./lib/_stream_transform.js":28}],34:[function(require,module,exports){ +},{"./lib/_stream_transform.js":29}],35:[function(require,module,exports){ module.exports = require("./lib/_stream_writable.js") -},{"./lib/_stream_writable.js":29}],35:[function(require,module,exports){ +},{"./lib/_stream_writable.js":30}],36:[function(require,module,exports){ (function (Buffer){ /* CryptoJS v3.1.2 @@ -12308,7 +7008,7 @@ function ripemd160 (message) { module.exports = ripemd160 }).call(this,require("buffer").Buffer) -},{"buffer":7}],36:[function(require,module,exports){ +},{"buffer":6}],37:[function(require,module,exports){ (function (Buffer){ // prototype class for hash functions function Hash (blockSize, finalSize) { @@ -12381,7 +7081,7 @@ Hash.prototype._update = function () { module.exports = Hash }).call(this,require("buffer").Buffer) -},{"buffer":7}],37:[function(require,module,exports){ +},{"buffer":6}],38:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() @@ -12398,7 +7098,7 @@ exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') -},{"./sha":38,"./sha1":39,"./sha224":40,"./sha256":41,"./sha384":42,"./sha512":43}],38:[function(require,module,exports){ +},{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined @@ -12495,7 +7195,7 @@ Sha.prototype._hash = function () { module.exports = Sha }).call(this,require("buffer").Buffer) -},{"./hash":36,"buffer":7,"inherits":16}],39:[function(require,module,exports){ +},{"./hash":37,"buffer":6,"inherits":15}],40:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined @@ -12597,7 +7297,7 @@ Sha1.prototype._hash = function () { module.exports = Sha1 }).call(this,require("buffer").Buffer) -},{"./hash":36,"buffer":7,"inherits":16}],40:[function(require,module,exports){ +},{"./hash":37,"buffer":6,"inherits":15}],41:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -12653,7 +7353,7 @@ Sha224.prototype._hash = function () { module.exports = Sha224 }).call(this,require("buffer").Buffer) -},{"./hash":36,"./sha256":41,"buffer":7,"inherits":16}],41:[function(require,module,exports){ +},{"./hash":37,"./sha256":42,"buffer":6,"inherits":15}],42:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -12791,7 +7491,7 @@ Sha256.prototype._hash = function () { module.exports = Sha256 }).call(this,require("buffer").Buffer) -},{"./hash":36,"buffer":7,"inherits":16}],42:[function(require,module,exports){ +},{"./hash":37,"buffer":6,"inherits":15}],43:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var SHA512 = require('./sha512') @@ -12851,7 +7551,7 @@ Sha384.prototype._hash = function () { module.exports = Sha384 }).call(this,require("buffer").Buffer) -},{"./hash":36,"./sha512":43,"buffer":7,"inherits":16}],43:[function(require,module,exports){ +},{"./hash":37,"./sha512":44,"buffer":6,"inherits":15}],44:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var Hash = require('./hash') @@ -13114,7 +7814,7 @@ Sha512.prototype._hash = function () { module.exports = Sha512 }).call(this,require("buffer").Buffer) -},{"./hash":36,"buffer":7,"inherits":16}],44:[function(require,module,exports){ +},{"./hash":37,"buffer":6,"inherits":15}],45:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13243,7 +7943,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":14,"inherits":16,"readable-stream/duplex.js":24,"readable-stream/passthrough.js":31,"readable-stream/readable.js":32,"readable-stream/transform.js":33,"readable-stream/writable.js":34}],45:[function(require,module,exports){ +},{"events":13,"inherits":15,"readable-stream/duplex.js":25,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],46:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13466,7 +8166,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":7}],46:[function(require,module,exports){ +},{"buffer":6}],47:[function(require,module,exports){ (function (global){ /** @@ -13537,10 +8237,10 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],47:[function(require,module,exports){ +},{}],48:[function(require,module,exports){ (function (Buffer){ var pbkdf2 = require('pbkdf2'); -var Promise = require("bluebird"); +var Promise = require('pinkie-promise'); function shouldUseNative() { @@ -13591,11 +8291,11 @@ function pbkdf2Browserified(password, salt, iterations, keylen, digest) { module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; }).call(this,require("buffer").Buffer) -},{"bluebird":4,"buffer":7,"pbkdf2":20}],48:[function(require,module,exports){ +},{"buffer":6,"pbkdf2":19,"pinkie-promise":21}],49:[function(require,module,exports){ (function (Buffer){ var pbkdf2 = require('./pbkdf2'); var createHMAC = require('create-hmac'); -var Promise = require("bluebird"); +var Promise = require('pinkie-promise'); module.exports = { @@ -13703,7 +8403,7 @@ function createFingerprint(str) { }); } }).call(this,require("buffer").Buffer) -},{"./pbkdf2":47,"bluebird":4,"buffer":7,"create-hmac":13}],49:[function(require,module,exports){ +},{"./pbkdf2":48,"buffer":6,"create-hmac":12,"pinkie-promise":21}],50:[function(require,module,exports){ var pbkdf2 = require('./pbkdf2'); var bigInt = require("big-integer"); var objectAssign = require('object-assign'); @@ -13804,5 +8504,5 @@ function renderPassword(entropy, passwordProfile) { return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } -},{"./pbkdf2":47,"big-integer":3,"object-assign":19}]},{},[1])(1) +},{"./pbkdf2":48,"big-integer":3,"object-assign":18}]},{},[1])(1) }); \ No newline at end of file diff --git a/package.json b/package.json index 6cdfa8c..83d8ad1 100644 --- a/package.json +++ b/package.json @@ -23,10 +23,10 @@ }, "dependencies": { "big-integer": "^1.6.17", - "bluebird": "^3.4.6", "create-hmac": "^1.1.4", "object-assign": "^4.1.0", "pbkdf2": "^3.0.9", + "pinkie-promise": "^2.0.1", "unibabel": "^2.1.3" }, "devDependencies": { diff --git a/src/pbkdf2.js b/src/pbkdf2.js index a601473..2400e8c 100644 --- a/src/pbkdf2.js +++ b/src/pbkdf2.js @@ -1,5 +1,5 @@ var pbkdf2 = require('pbkdf2'); -var Promise = require("bluebird"); +var Promise = require('pinkie-promise'); function shouldUseNative() { diff --git a/src/v1.js b/src/v1.js index 5225290..9c263da 100644 --- a/src/v1.js +++ b/src/v1.js @@ -1,6 +1,6 @@ var pbkdf2 = require('./pbkdf2'); var createHMAC = require('create-hmac'); -var Promise = require("bluebird"); +var Promise = require('pinkie-promise'); module.exports = { From ee66335f2cf04d5a1da3223a7dcfc336ff89fccc Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 21 Nov 2016 15:32:33 +0100 Subject: [PATCH 092/124] clean tests --- package.json | 3 +- tests/api.tests.js | 345 --------------------------------- tests/deriveEncryptedLogin.tests.js | 70 ------- tests/getPasswordTemplate.tests.js | 63 ------ tests/karma.config.js | 2 - tests/pbkdf2.tests.js | 16 -- tests/prettyPrint.js | 35 ---- tests/v1/api.tests.js | 345 +++++++++++++++++++++++++++++++++ tests/v1/deriveEncryptedLogin.tests.js | 70 +++++++ tests/v1/getPasswordTemplate.tests.js | 63 ++++++ tests/v1/pbkdf2.tests.js | 16 ++ tests/v1/prettyPrint.js | 35 ++++ tests/v2/entropy.tests.js | 2 +- 13 files changed, 532 insertions(+), 533 deletions(-) delete mode 100644 tests/api.tests.js delete mode 100644 tests/deriveEncryptedLogin.tests.js delete mode 100644 tests/getPasswordTemplate.tests.js delete mode 100644 tests/pbkdf2.tests.js delete mode 100644 tests/prettyPrint.js create mode 100644 tests/v1/api.tests.js create mode 100644 tests/v1/deriveEncryptedLogin.tests.js create mode 100644 tests/v1/getPasswordTemplate.tests.js create mode 100644 tests/v1/pbkdf2.tests.js create mode 100644 tests/v1/prettyPrint.js diff --git a/package.json b/package.json index 83d8ad1..962d6ff 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "scripts": { "build": "rimraf lib && mkdir lib && browserify --standalone LessPass index.js > lib/lesspass.js", "prepublish": "npm test && npm run build && npm run test:node && npm run test:browser", - "test": "mocha --require ./tests/helper.js tests/*", + "test": "mocha tests/*", "test:node": "npm run build && cd tests && node node.js && cd ..", "test:browser": "npm run build && karma start tests/karma.config.js" }, @@ -30,6 +30,7 @@ "unibabel": "^2.1.3" }, "devDependencies": { + "bluebird": "^3.4.6", "browserify": "^13.1.1", "chai": "^3.5.0", "karma": "^1.3.0", diff --git a/tests/api.tests.js b/tests/api.tests.js deleted file mode 100644 index 18b345c..0000000 --- a/tests/api.tests.js +++ /dev/null @@ -1,345 +0,0 @@ -var assert = chai.assert; - -describe('LessPass', function () { - describe('encryptLogin', function () { - it('should use pbkdf2 with 8192 iterations and sha256', function (done) { - LessPass.encryptLogin('test@example.org', 'password').then(function (encryptedLogin) { - assert.equal('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); - done(); - }); - }); - - it('should allow to customize number of iterations', function (done) { - LessPass.encryptLogin('test@example.org', 'password', {iterations: 4096}).then(function (encryptedLogin) { - assert.equal('0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f', encryptedLogin); - done(); - }); - }); - - it('should allow to customize key length', function (done) { - LessPass.encryptLogin('test@example.org', 'password', {keylen: 16}).then(function (encryptedLogin) { - assert.equal('d8af5f918db6b65b1db3d3984e5a400e', encryptedLogin); - done(); - }); - }); - - it('should allow to customize iterations and key length', function (done) { - LessPass.encryptLogin('test@example.org', 'password', { - iterations: 4096, - keylen: 16 - }).then(function (encryptedLogin) { - assert.equal('0a91208545e3aa4935d3a22984ca097a', encryptedLogin); - done(); - }); - }); - - it('should allow utf8 parameter', function () { - return LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { - assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); - }); - }); - - it('auto generated encrypt login tests', function () { - this.timeout(10000); - var promises = []; - var passwords = [ - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password', - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - }, - { - login: 'lesspass', - masterPassword: 'password', - encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', - }, - { - login: 'contact@lesspass.com', - masterPassword: 'password2', - encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', - } - ]; - - passwords.forEach(function (entry) { - promises.push(LessPass.encryptLogin(entry.login, entry.masterPassword)); - }); - - return Promise.all(promises).then(function (values) { - for (var i = 0; i < values.length; i++) { - assert.equal(passwords[i].encryptedLogin, values[i]); - } - }); - }); - }); -}); - -describe('LessPass', function () { - describe('renderPassword', function () { - it('render password', function (done) { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - done(); - }) - }); - - it('render password with a custom template', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'n' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - var i = generatedPassword.length; - while (i--) { - assert('0123456789'.indexOf(generatedPassword[i]) !== -1) - } - }) - }); - - it('render password with a custom template too short', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'CvcnCVsn' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('Sor4WU:8Wad5', generatedPassword); - }) - }); - - it('render password with a custom template too long', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 6, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'CvcnCVsn' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('Sor4WU', generatedPassword); - }) - }); - - it('auto generated render password tests', function () { - var promises = []; - var passwords = [ - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'azYS7,olOL2]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 14, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'azYS7,olOL2]iz' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: false, - numbers: false, - symbols: false, - generatedPassword: 'azyseqololat' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: false, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'AZ3[EQ7@OL2]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: true, - symbols: true, - generatedPassword: '4?3[7,7@7@2]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: false, - symbols: true, - generatedPassword: '[?=[&,:@:@[]' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: false, - generatedPassword: 'azYS7uwAW8at' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: false, - symbols: false, - generatedPassword: 'azYSeqOLolAT' - }, - { - encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', - site: 'lesspass.com', - counter: 2, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'obYT2=olOV9=' - }, - { - encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'erOC1%imIW3,' - }, - { - encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', - site: 'lesspass.com', - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - generatedPassword: 'uvUM5_ucUP5=' - } - ]; - - passwords.forEach(function (entry) { - var passwordOption = { - counter: entry.counter, - length: entry.length, - lowercase: entry.lowercase, - uppercase: entry.uppercase, - numbers: entry.numbers, - symbols: entry.symbols, - }; - promises.push(LessPass.renderPassword(entry.encryptedLogin, entry.site, passwordOption)); - }); - - return Promise.all(promises).then(function(values) { - for (var i = 0; i < values.length; i++) { - assert.equal(passwords[i].generatedPassword, values[i]); - } - }); - }); - }); -}); - -describe('LessPass', function () { - describe('fingerprint', function () { - it('createFingerprint', function () { - return LessPass.createFingerprint('password').then(function (fingerprint) { - assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); - }) - }); - }); -}); - diff --git a/tests/deriveEncryptedLogin.tests.js b/tests/deriveEncryptedLogin.tests.js deleted file mode 100644 index 5c888f6..0000000 --- a/tests/deriveEncryptedLogin.tests.js +++ /dev/null @@ -1,70 +0,0 @@ -var assert = chai.assert; - -describe('LessPass', function () { - describe('deriveEncryptedLogin', function () { - it('should createHmac', function () { - var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - var salt = 'lesspass.com1'; - return LessPass._createHmac(encryptedLogin, salt).then(function (hmac) { - assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); - }); - }); - it('should derive encrypted login with default options', function () { - const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - const option = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - }; - var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); - var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); - Promise.all([p1, p2]).then(function (generatedPasswords) { - assert.equal(generatedPasswords[0], generatedPasswords[1]) - }); - }); - it('should derive encrypted login with defined length', function () { - var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - var site = 'lesspass.com'; - var option = { - counter: 1, - length: 10, - }; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { - assert.equal(10, generatedPassword.length); - }); - }); - it('should return two different passwords if site different', function () { - const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'google.com'; - const site2 = 'facebook.com'; - var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); - var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site2); - return Promise.all([p1, p2]).then(function (derivedEncryptedLogins) { - assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) - }); - }); - it('should return two different passwords if counter different', function () { - const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option = {counter: 1}; - const option2 = {counter: 2}; - var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); - var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option2); - return Promise.all([p1, p2]).then(function (derivedEncryptedLogins) { - assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) - }); - }); - it('should derive encrypted login with sha 256', function () { - const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (encryptedLogin) { - assert.equal('be00f942fc8a', encryptedLogin); - }); - }); - }); -}); - diff --git a/tests/getPasswordTemplate.tests.js b/tests/getPasswordTemplate.tests.js deleted file mode 100644 index a8718d4..0000000 --- a/tests/getPasswordTemplate.tests.js +++ /dev/null @@ -1,63 +0,0 @@ -var assert = chai.assert; - -describe('LessPass', function () { - describe('getPasswordTemplate', function () { - it('should get default template', function () { - assert.equal('vcVCns', LessPass._getPasswordTemplate({ - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - })); - }); - it('should get lowercase template', function () { - assert.equal('vc', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: false, - symbols: false - })); - }); - it('should get uppercase template', function () { - assert.equal('VC', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: true, - numbers: false, - symbols: false - })); - }); - it('should get numbers template', function () { - assert.equal('n', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: true, - symbols: false - })); - }); - it('should get symbols template', function () { - assert.equal('s', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: false, - symbols: true - })); - }); - it('should concatenate template if two password settings', function () { - assert.equal('vcVC', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: true, - numbers: false, - symbols: false - })); - assert.equal('vcns', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: true, - symbols: true - })); - }); - }); -}); - diff --git a/tests/karma.config.js b/tests/karma.config.js index 842e845..97309ea 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -5,8 +5,6 @@ module.exports = function (config) { files: [ 'node_modules/bluebird/js/browser/bluebird.core.min.js', 'node_modules/big-integer/BigInteger.min.js', - 'node_modules/unibabel/index.js', - 'node_modules/unibabel/unibabel.hex.js', 'lib/lesspass.js', 'tests/**/*.js' ], diff --git a/tests/pbkdf2.tests.js b/tests/pbkdf2.tests.js deleted file mode 100644 index c3f692d..0000000 --- a/tests/pbkdf2.tests.js +++ /dev/null @@ -1,16 +0,0 @@ -var assert = chai.assert; - -describe('LessPass', function () { - describe('pbkdf2', function () { - it('should secret, salt, 2, 32, sha256', function () { - return LessPass.pbkdf2('secret', 'salt', 2, 32, 'sha256').then(function (key) { - assert.equal('f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569', key); - }) - }); - }); -}); - - - - - diff --git a/tests/prettyPrint.js b/tests/prettyPrint.js deleted file mode 100644 index bb09c0c..0000000 --- a/tests/prettyPrint.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = chai.assert; - -describe('LessPass', function () { - describe('prettyPrint', function () { - it('should print different password if templates different', function () { - var encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; - assert.notEqual(LessPass._prettyPrint(encryptedLogin, 'cv'), LessPass._prettyPrint(encryptedLogin, 'vc')); - }); - it('must return a string of the same length as the input', function () { - var hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; - assert.equal(hash.length, LessPass._prettyPrint(hash, 'cv').length); - }); - it('should return char inside a string based on modulo of the index', function () { - var template = 'cv'; - assert.equal('c', LessPass._getCharType(template, 0)); - assert.equal('v', LessPass._getCharType(template, 1)); - assert.equal('c', LessPass._getCharType(template, 10)); - }); - it('should convert a string into an array of char code', function () { - var charCodes = LessPass._string2charCodes('ab40f6ee71'); - assert.equal(97, charCodes[0]); - assert.equal(98, charCodes[1]); - assert.equal(10, charCodes.length); - }); - it('should get password char based on its type and index', function () { - var typeVowel = 'V'; - assert.equal('A', LessPass._getPasswordChar(typeVowel, 0)); - }); - it('should modulo if overflow', function () { - var typeVowel = 'V'; - assert.equal('E', LessPass._getPasswordChar(typeVowel, 1)); - assert.equal('E', LessPass._getPasswordChar(typeVowel, 7)); - }); - }); -}); diff --git a/tests/v1/api.tests.js b/tests/v1/api.tests.js new file mode 100644 index 0000000..18b345c --- /dev/null +++ b/tests/v1/api.tests.js @@ -0,0 +1,345 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('encryptLogin', function () { + it('should use pbkdf2 with 8192 iterations and sha256', function (done) { + LessPass.encryptLogin('test@example.org', 'password').then(function (encryptedLogin) { + assert.equal('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); + done(); + }); + }); + + it('should allow to customize number of iterations', function (done) { + LessPass.encryptLogin('test@example.org', 'password', {iterations: 4096}).then(function (encryptedLogin) { + assert.equal('0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f', encryptedLogin); + done(); + }); + }); + + it('should allow to customize key length', function (done) { + LessPass.encryptLogin('test@example.org', 'password', {keylen: 16}).then(function (encryptedLogin) { + assert.equal('d8af5f918db6b65b1db3d3984e5a400e', encryptedLogin); + done(); + }); + }); + + it('should allow to customize iterations and key length', function (done) { + LessPass.encryptLogin('test@example.org', 'password', { + iterations: 4096, + keylen: 16 + }).then(function (encryptedLogin) { + assert.equal('0a91208545e3aa4935d3a22984ca097a', encryptedLogin); + done(); + }); + }); + + it('should allow utf8 parameter', function () { + return LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { + assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); + }); + }); + + it('auto generated encrypt login tests', function () { + this.timeout(10000); + var promises = []; + var passwords = [ + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password', + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + }, + { + login: 'lesspass', + masterPassword: 'password', + encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', + }, + { + login: 'contact@lesspass.com', + masterPassword: 'password2', + encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', + } + ]; + + passwords.forEach(function (entry) { + promises.push(LessPass.encryptLogin(entry.login, entry.masterPassword)); + }); + + return Promise.all(promises).then(function (values) { + for (var i = 0; i < values.length; i++) { + assert.equal(passwords[i].encryptedLogin, values[i]); + } + }); + }); + }); +}); + +describe('LessPass', function () { + describe('renderPassword', function () { + it('render password', function (done) { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + assert.equal('azYS7,olOL2]', generatedPassword); + done(); + }) + }); + + it('render password with a custom template', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'n' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + var i = generatedPassword.length; + while (i--) { + assert('0123456789'.indexOf(generatedPassword[i]) !== -1) + } + }) + }); + + it('render password with a custom template too short', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'CvcnCVsn' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + assert.equal('Sor4WU:8Wad5', generatedPassword); + }) + }); + + it('render password with a custom template too long', function () { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 6, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'CvcnCVsn' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { + assert.equal('Sor4WU', generatedPassword); + }) + }); + + it('auto generated render password tests', function () { + var promises = []; + var passwords = [ + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'azYS7,olOL2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 14, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'azYS7,olOL2]iz' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: false, + numbers: false, + symbols: false, + generatedPassword: 'azyseqololat' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'AZ3[EQ7@OL2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: true, + symbols: true, + generatedPassword: '4?3[7,7@7@2]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: false, + symbols: true, + generatedPassword: '[?=[&,:@:@[]' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + generatedPassword: 'azYS7uwAW8at' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: false, + symbols: false, + generatedPassword: 'azYSeqOLolAT' + }, + { + encryptedLogin: '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', + site: 'lesspass.com', + counter: 2, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'obYT2=olOV9=' + }, + { + encryptedLogin: '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'erOC1%imIW3,' + }, + { + encryptedLogin: 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', + site: 'lesspass.com', + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + generatedPassword: 'uvUM5_ucUP5=' + } + ]; + + passwords.forEach(function (entry) { + var passwordOption = { + counter: entry.counter, + length: entry.length, + lowercase: entry.lowercase, + uppercase: entry.uppercase, + numbers: entry.numbers, + symbols: entry.symbols, + }; + promises.push(LessPass.renderPassword(entry.encryptedLogin, entry.site, passwordOption)); + }); + + return Promise.all(promises).then(function(values) { + for (var i = 0; i < values.length; i++) { + assert.equal(passwords[i].generatedPassword, values[i]); + } + }); + }); + }); +}); + +describe('LessPass', function () { + describe('fingerprint', function () { + it('createFingerprint', function () { + return LessPass.createFingerprint('password').then(function (fingerprint) { + assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); + }) + }); + }); +}); + diff --git a/tests/v1/deriveEncryptedLogin.tests.js b/tests/v1/deriveEncryptedLogin.tests.js new file mode 100644 index 0000000..5c888f6 --- /dev/null +++ b/tests/v1/deriveEncryptedLogin.tests.js @@ -0,0 +1,70 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('deriveEncryptedLogin', function () { + it('should createHmac', function () { + var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + var salt = 'lesspass.com1'; + return LessPass._createHmac(encryptedLogin, salt).then(function (hmac) { + assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); + }); + }); + it('should derive encrypted login with default options', function () { + const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + const site = 'lesspass.com'; + const option = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + }; + var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); + var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); + Promise.all([p1, p2]).then(function (generatedPasswords) { + assert.equal(generatedPasswords[0], generatedPasswords[1]) + }); + }); + it('should derive encrypted login with defined length', function () { + var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; + var site = 'lesspass.com'; + var option = { + counter: 1, + length: 10, + }; + return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { + assert.equal(10, generatedPassword.length); + }); + }); + it('should return two different passwords if site different', function () { + const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'google.com'; + const site2 = 'facebook.com'; + var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site); + var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site2); + return Promise.all([p1, p2]).then(function (derivedEncryptedLogins) { + assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) + }); + }); + it('should return two different passwords if counter different', function () { + const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option = {counter: 1}; + const option2 = {counter: 2}; + var p1 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option); + var p2 = LessPass._deriveEncryptedLogin(encryptedLogin, site, option2); + return Promise.all([p1, p2]).then(function (derivedEncryptedLogins) { + assert.notEqual(derivedEncryptedLogins[0], derivedEncryptedLogins[1]) + }); + }); + it('should derive encrypted login with sha 256', function () { + const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (encryptedLogin) { + assert.equal('be00f942fc8a', encryptedLogin); + }); + }); + }); +}); + diff --git a/tests/v1/getPasswordTemplate.tests.js b/tests/v1/getPasswordTemplate.tests.js new file mode 100644 index 0000000..a8718d4 --- /dev/null +++ b/tests/v1/getPasswordTemplate.tests.js @@ -0,0 +1,63 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('getPasswordTemplate', function () { + it('should get default template', function () { + assert.equal('vcVCns', LessPass._getPasswordTemplate({ + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + })); + }); + it('should get lowercase template', function () { + assert.equal('vc', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: false, + symbols: false + })); + }); + it('should get uppercase template', function () { + assert.equal('VC', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: true, + numbers: false, + symbols: false + })); + }); + it('should get numbers template', function () { + assert.equal('n', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: true, + symbols: false + })); + }); + it('should get symbols template', function () { + assert.equal('s', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + })); + }); + it('should concatenate template if two password settings', function () { + assert.equal('vcVC', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + })); + assert.equal('vcns', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: true, + symbols: true + })); + }); + }); +}); + diff --git a/tests/v1/pbkdf2.tests.js b/tests/v1/pbkdf2.tests.js new file mode 100644 index 0000000..c3f692d --- /dev/null +++ b/tests/v1/pbkdf2.tests.js @@ -0,0 +1,16 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('pbkdf2', function () { + it('should secret, salt, 2, 32, sha256', function () { + return LessPass.pbkdf2('secret', 'salt', 2, 32, 'sha256').then(function (key) { + assert.equal('f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569', key); + }) + }); + }); +}); + + + + + diff --git a/tests/v1/prettyPrint.js b/tests/v1/prettyPrint.js new file mode 100644 index 0000000..bb09c0c --- /dev/null +++ b/tests/v1/prettyPrint.js @@ -0,0 +1,35 @@ +var assert = chai.assert; + +describe('LessPass', function () { + describe('prettyPrint', function () { + it('should print different password if templates different', function () { + var encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; + assert.notEqual(LessPass._prettyPrint(encryptedLogin, 'cv'), LessPass._prettyPrint(encryptedLogin, 'vc')); + }); + it('must return a string of the same length as the input', function () { + var hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; + assert.equal(hash.length, LessPass._prettyPrint(hash, 'cv').length); + }); + it('should return char inside a string based on modulo of the index', function () { + var template = 'cv'; + assert.equal('c', LessPass._getCharType(template, 0)); + assert.equal('v', LessPass._getCharType(template, 1)); + assert.equal('c', LessPass._getCharType(template, 10)); + }); + it('should convert a string into an array of char code', function () { + var charCodes = LessPass._string2charCodes('ab40f6ee71'); + assert.equal(97, charCodes[0]); + assert.equal(98, charCodes[1]); + assert.equal(10, charCodes.length); + }); + it('should get password char based on its type and index', function () { + var typeVowel = 'V'; + assert.equal('A', LessPass._getPasswordChar(typeVowel, 0)); + }); + it('should modulo if overflow', function () { + var typeVowel = 'V'; + assert.equal('E', LessPass._getPasswordChar(typeVowel, 1)); + assert.equal('E', LessPass._getPasswordChar(typeVowel, 7)); + }); + }); +}); diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index a89e648..c2b6739 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -29,7 +29,7 @@ describe('LessPass v2', function () { }; return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); - }) + }); }); it('calc entropy different if index different', function () { var site = 'example.org'; From d07bc6c1508843d7f6e71d3cfb1c58a35d03d396 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Mon, 21 Nov 2016 19:34:52 +0100 Subject: [PATCH 093/124] 6.0.0-beta.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 962d6ff..ade4b3d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "5.2.2", + "version": "6.0.0-beta.1", "description": "LessPass node module used to generate LessPass passwords", "keywords": [ "crypto", From 060dbc90baca8cf84c88d7e92e6aecef746f5772 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 22 Nov 2016 12:10:02 +0100 Subject: [PATCH 094/124] add missing files in npm --- dist/lesspass.js | 8542 +++++++++++++++++++++++++++++++++++++++++++++++++ example/lesspass.html | 2 +- lib/lesspass.js | 8508 ------------------------------------------------ package.json | 4 +- tests/karma.config.js | 2 +- 5 files changed, 8547 insertions(+), 8511 deletions(-) create mode 100644 dist/lesspass.js delete mode 100644 lib/lesspass.js diff --git a/dist/lesspass.js b/dist/lesspass.js new file mode 100644 index 0000000..9130224 --- /dev/null +++ b/dist/lesspass.js @@ -0,0 +1,8542 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LessPass = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} + +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],3:[function(require,module,exports){ +var bigInt = (function (undefined) { + "use strict"; + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + LOG_MAX_INT = Math.log(MAX_INT); + + function Integer(v, radix) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var value, n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value, isSmall; + if (compareAbs(a, b) >= 0) { + value = subtract(a,b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var value, n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + function square(a) { + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + for (var j = 0; j < l; j++) { + a_j = a[j]; + product = a_i * a_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + var value = n.value; + if (value === 0) return false; + if (value === 1) return true; + if (value === 2) return this.isEven(); + return this.mod(n).equals(Integer[0]); + }; + SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(25)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + BigInteger.prototype.isPrime = function () { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(), + nPrev = n.prev(); + var a = [2, 3, 5, 7, 11, 13, 17, 19], + b = nPrev, + d, t, i, x; + while (b.isEven()) b = b.divide(2); + for (i = 0; i < a.length; i++) { + x = bigInt(a[i]).modPow(b, n); + if (x.equals(Integer[1]) || x.equals(nPrev)) continue; + for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) { + x = x.square().mod(n); + if (x.equals(nPrev)) t = false; + } + if (t) return false; + } + return true; + }; + SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + // use the Fermat primality test + for (var i = 0; i < t; i++) { + var a = bigInt.randBetween(2, n.minus(2)); + if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite + } + return true; // large chance of being prime + }; + SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.equals(bigInt.zero)) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + return t; + } + SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + + var powersOfTwo = [1]; + while (powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) || + (n instanceof BigInteger && n.value.length <= 1); + } + + BigInteger.prototype.shiftLeft = function (n) { + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftRight(-n); + var result = this; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (n) { + var remQuo; + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero()) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xBits = [], yBits = []; + var xStop = false, yStop = false; + while (!xStop || !yStop) { + if (xRem.isZero()) { // virtual sign extension for simulating two's complement + xStop = true; + xBits.push(xSign ? 1 : 0); + } + else if (xSign) xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers + else xBits.push(xRem.isEven() ? 0 : 1); + + if (yRem.isZero()) { + yStop = true; + yBits.push(ySign ? 1 : 0); + } + else if (ySign) yBits.push(yRem.isEven() ? 1 : 0); + else yBits.push(yRem.isEven() ? 0 : 1); + + xRem = xRem.over(2); + yRem = yRem.over(2); + } + var result = []; + for (var i = 0; i < xBits.length; i++) result.push(fn(xBits[i], yBits[i])); + var sum = bigInt(result.pop()).negate().times(bigInt(2).pow(result.length)); + while (result.length) { + sum = sum.add(bigInt(result.pop()).times(bigInt(2).pow(result.length))); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a,b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = Math.min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b) { + a = parseValue(a); + b = parseValue(b); + var low = min(a, b), high = max(a, b); + var range = high.subtract(low); + if (range.isSmall) return low.add(Math.round(Math.random() * range)); + var length = range.value.length - 1; + var result = [], restricted = true; + for (var i = length; i >= 0; i--) { + var top = restricted ? range.value[i] : BASE; + var digit = truncate(Math.random() * top); + result.unshift(digit); + if (digit < top) restricted = false; + } + result = arrayToSmall(result); + return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false)); + } + var parseBase = function (text, base) { + var val = Integer[0], pow = Integer[1], + length = text.length; + if (2 <= base && base <= 36) { + if (length <= LOG_MAX_INT / Math.log(base)) { + return new SmallInteger(parseInt(text, base)); + } + } + base = parseValue(base); + var digits = []; + var i; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i].toLowerCase(), + charCode = c.charCodeAt(0); + if (48 <= charCode && charCode <= 57) digits.push(parseValue(c)); + else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87)); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">"); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + digits.reverse(); + for (i = 0; i < digits.length; i++) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + }; + + function stringify(digit) { + var v = digit.value; + if (typeof v === "number") v = [v]; + if (v.length === 1 && v[0] <= 35) { + return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]); + } + return "<" + v + ">"; + } + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return "0"; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return "0"; + if (n.isNegative()) return new Array(1 - n).join("10"); + return "1" + new Array(+n).join("01"); + } + var minusSign = ""; + if (n.isNegative() && base.isPositive()) { + minusSign = "-"; + n = n.abs(); + } + if (base.equals(1)) { + if (n.isZero()) return "0"; + return minusSign + new Array(+n + 1).join(1); + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(stringify(digit)); + } + out.push(stringify(left)); + return minusSign + out.reverse().join(""); + } + + BigInteger.prototype.toString = function (radix) { + if (radix === undefined) radix = 10; + if (radix !== 10) return toBase(this, radix); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + SmallInteger.prototype.toString = function (radix) { + if (radix === undefined) radix = 10; + if (radix != 10) return toBase(this, radix); + return String(this.value); + }; + + BigInteger.prototype.valueOf = function () { + return +this.toString(); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return new SmallInteger(x); + throw "Invalid integer: " + v; + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = new SmallInteger(i); + if (i > 0) Integer[-i] = new SmallInteger(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; }; + Integer.randBetween = randBetween; + return Integer; +})(); + +// Node.js check +if (typeof module !== "undefined" && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +},{}],4:[function(require,module,exports){ + +},{}],5:[function(require,module,exports){ +(function (global){ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"buffer":6}],6:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":2,"ieee754":14,"isarray":17}],7:[function(require,module,exports){ +(function (Buffer){ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + return out +} + +}).call(this,require("buffer").Buffer) +},{"buffer":6,"inherits":15,"stream":45,"string_decoder":46}],8:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":16}],9:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var inherits = require('inherits') +var md5 = require('./md5') +var rmd160 = require('ripemd160') +var sha = require('sha.js') + +var Base = require('cipher-base') + +function HashNoConstructor(hash) { + Base.call(this, 'digest') + + this._hash = hash + this.buffers = [] +} + +inherits(HashNoConstructor, Base) + +HashNoConstructor.prototype._update = function (data) { + this.buffers.push(data) +} + +HashNoConstructor.prototype._final = function () { + var buf = Buffer.concat(this.buffers) + var r = this._hash(buf) + this.buffers = null + + return r +} + +function Hash(hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if ('md5' === alg) return new HashNoConstructor(md5) + if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160) + + return new Hash(sha(alg)) +} + +}).call(this,require("buffer").Buffer) +},{"./md5":11,"buffer":6,"cipher-base":7,"inherits":15,"ripemd160":36,"sha.js":38}],10:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} +exports.hash = hash; +}).call(this,require("buffer").Buffer) +},{"buffer":6}],11:[function(require,module,exports){ +'use strict'; +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = require('./helpers'); + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; +},{"./helpers":10}],12:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var createHash = require('create-hash/browser'); +var inherits = require('inherits') + +var Transform = require('stream').Transform + +var ZEROS = new Buffer(128) +ZEROS.fill(0) + +function Hmac(alg, key) { + Transform.call(this) + alg = alg.toLowerCase() + if (typeof key === 'string') { + key = new Buffer(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + + if (key.length > blocksize) { + key = createHash(alg).update(key).digest() + + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = new Buffer(blocksize) + var opad = this._opad = new Buffer(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = createHash(alg).update(ipad) +} + +inherits(Hmac, Transform) + +Hmac.prototype.update = function (data, enc) { + this._hash.update(data, enc) + + return this +} + +Hmac.prototype._transform = function (data, _, next) { + this._hash.update(data) + + next() +} + +Hmac.prototype._flush = function (next) { + this.push(this.digest()) + + next() +} + +Hmac.prototype.digest = function (enc) { + var h = this._hash.digest() + + return createHash(this._alg).update(this._opad).update(h).digest(enc) +} + +module.exports = function createHmac(alg, key) { + return new Hmac(alg, key) +} + +}).call(this,require("buffer").Buffer) +},{"buffer":6,"create-hash/browser":9,"inherits":15,"stream":45}],13:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],14:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],15:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],16:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],17:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],18:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],19:[function(require,module,exports){ +(function (process,Buffer){ +var createHmac = require('create-hmac') +var checkParameters = require('./precondition') + +exports.pbkdf2 = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + checkParameters(iterations, keylen) + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + + setTimeout(function () { + callback(null, exports.pbkdf2Sync(password, salt, iterations, keylen, digest)) + }) +} + +var defaultEncoding +if (process.browser) { + defaultEncoding = 'utf-8' +} else { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} + +exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { + if (!Buffer.isBuffer(password)) password = new Buffer(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, defaultEncoding) + + checkParameters(iterations, keylen) + + digest = digest || 'sha1' + + var hLen + var l = 1 + var DK = new Buffer(keylen) + var block1 = new Buffer(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var r + var T + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + var U = createHmac(digest, password).update(block1).digest() + + if (!hLen) { + hLen = U.length + T = new Buffer(hLen) + l = Math.ceil(keylen / hLen) + r = keylen - (l - 1) * hLen + } + + U.copy(T, 0, 0, hLen) + + for (var j = 1; j < iterations; j++) { + U = createHmac(digest, password).update(U).digest() + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + var destPos = (i - 1) * hLen + var len = (i === l ? r : hLen) + T.copy(DK, destPos, 0, len) + } + + return DK +} + +}).call(this,require('_process'),require("buffer").Buffer) +},{"./precondition":20,"_process":24,"buffer":6,"create-hmac":12}],20:[function(require,module,exports){ +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + +},{}],21:[function(require,module,exports){ +'use strict'; + +module.exports = typeof Promise === 'function' ? Promise : require('pinkie'); + +},{"pinkie":22}],22:[function(require,module,exports){ +(function (global){ +'use strict'; + +var PENDING = 'pending'; +var SETTLED = 'settled'; +var FULFILLED = 'fulfilled'; +var REJECTED = 'rejected'; +var NOOP = function () {}; +var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function'; + +var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; +var asyncQueue = []; +var asyncTimer; + +function asyncFlush() { + // run promise callbacks + for (var i = 0; i < asyncQueue.length; i++) { + asyncQueue[i][0](asyncQueue[i][1]); + } + + // reset async asyncQueue + asyncQueue = []; + asyncTimer = false; +} + +function asyncCall(callback, arg) { + asyncQueue.push([callback, arg]); + + if (!asyncTimer) { + asyncTimer = true; + asyncSetTimer(asyncFlush, 0); + } +} + +function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } + + function rejectPromise(reason) { + reject(promise, reason); + } + + try { + resolver(resolvePromise, rejectPromise); + } catch (e) { + rejectPromise(e); + } +} + +function invokeCallback(subscriber) { + var owner = subscriber.owner; + var settled = owner._state; + var value = owner._data; + var callback = subscriber[settled]; + var promise = subscriber.then; + + if (typeof callback === 'function') { + settled = FULFILLED; + try { + value = callback(value); + } catch (e) { + reject(promise, e); + } + } + + if (!handleThenable(promise, value)) { + if (settled === FULFILLED) { + resolve(promise, value); + } + + if (settled === REJECTED) { + reject(promise, value); + } + } +} + +function handleThenable(promise, value) { + var resolved; + + try { + if (promise === value) { + throw new TypeError('A promises callback cannot return that same promise.'); + } + + if (value && (typeof value === 'function' || typeof value === 'object')) { + // then should be retrieved only once + var then = value.then; + + if (typeof then === 'function') { + then.call(value, function (val) { + if (!resolved) { + resolved = true; + + if (value === val) { + fulfill(promise, val); + } else { + resolve(promise, val); + } + } + }, function (reason) { + if (!resolved) { + resolved = true; + + reject(promise, reason); + } + }); + + return true; + } + } + } catch (e) { + if (!resolved) { + reject(promise, e); + } + + return true; + } + + return false; +} + +function resolve(promise, value) { + if (promise === value || !handleThenable(promise, value)) { + fulfill(promise, value); + } +} + +function fulfill(promise, value) { + if (promise._state === PENDING) { + promise._state = SETTLED; + promise._data = value; + + asyncCall(publishFulfillment, promise); + } +} + +function reject(promise, reason) { + if (promise._state === PENDING) { + promise._state = SETTLED; + promise._data = reason; + + asyncCall(publishRejection, promise); + } +} + +function publish(promise) { + promise._then = promise._then.forEach(invokeCallback); +} + +function publishFulfillment(promise) { + promise._state = FULFILLED; + publish(promise); +} + +function publishRejection(promise) { + promise._state = REJECTED; + publish(promise); + if (!promise._handled && isNode) { + global.process.emit('unhandledRejection', promise._data, promise); + } +} + +function notifyRejectionHandled(promise) { + global.process.emit('rejectionHandled', promise); +} + +/** + * @class + */ +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('Promise resolver ' + resolver + ' is not a function'); + } + + if (this instanceof Promise === false) { + throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); + } + + this._then = []; + + invokeResolver(resolver, this); +} + +Promise.prototype = { + constructor: Promise, + + _state: PENDING, + _then: null, + _data: undefined, + _handled: false, + + then: function (onFulfillment, onRejection) { + var subscriber = { + owner: this, + then: new this.constructor(NOOP), + fulfilled: onFulfillment, + rejected: onRejection + }; + + if ((onRejection || onFulfillment) && !this._handled) { + this._handled = true; + if (this._state === REJECTED && isNode) { + asyncCall(notifyRejectionHandled, this); + } + } + + if (this._state === FULFILLED || this._state === REJECTED) { + // already resolved, call callback async + asyncCall(invokeCallback, subscriber); + } else { + // subscribe + this._then.push(subscriber); + } + + return subscriber.then; + }, + + catch: function (onRejection) { + return this.then(null, onRejection); + } +}; + +Promise.all = function (promises) { + if (!Array.isArray(promises)) { + throw new TypeError('You must pass an array to Promise.all().'); + } + + return new Promise(function (resolve, reject) { + var results = []; + var remaining = 0; + + function resolver(index) { + remaining++; + return function (value) { + results[index] = value; + if (!--remaining) { + resolve(results); + } + }; + } + + for (var i = 0, promise; i < promises.length; i++) { + promise = promises[i]; + + if (promise && typeof promise.then === 'function') { + promise.then(resolver(i), reject); + } else { + results[i] = promise; + } + } + + if (!remaining) { + resolve(results); + } + }); +}; + +Promise.race = function (promises) { + if (!Array.isArray(promises)) { + throw new TypeError('You must pass an array to Promise.race().'); + } + + return new Promise(function (resolve, reject) { + for (var i = 0, promise; i < promises.length; i++) { + promise = promises[i]; + + if (promise && typeof promise.then === 'function') { + promise.then(resolve, reject); + } else { + resolve(promise); + } + } + }); +}; + +Promise.resolve = function (value) { + if (value && typeof value === 'object' && value.constructor === Promise) { + return value; + } + + return new Promise(function (resolve) { + resolve(value); + }); +}; + +Promise.reject = function (reason) { + return new Promise(function (resolve, reject) { + reject(reason); + }); +}; + +module.exports = Promise; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],23:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + +}).call(this,require('_process')) +},{"_process":24}],24:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],25:[function(require,module,exports){ +module.exports = require("./lib/_stream_duplex.js") + +},{"./lib/_stream_duplex.js":26}],26:[function(require,module,exports){ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":28,"./_stream_writable":30,"core-util-is":8,"inherits":15,"process-nextick-args":23}],27:[function(require,module,exports){ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":29,"core-util-is":8,"inherits":15}],28:[function(require,module,exports){ +(function (process){ +'use strict'; + +module.exports = Readable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var StringDecoder; + +util.inherits(Readable, Stream); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = bufferShim.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process')) +},{"./_stream_duplex":26,"./internal/streams/BufferList":31,"_process":24,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"isarray":17,"process-nextick-args":23,"string_decoder/":46,"util":4}],29:[function(require,module,exports){ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er, data) { + done(stream, er, data); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data !== null && data !== undefined) stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":26,"core-util-is":8,"inherits":15}],30:[function(require,module,exports){ +(function (process){ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +util.inherits(Writable, Stream); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = bufferShim.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} +}).call(this,require('_process')) +},{"./_stream_duplex":26,"_process":24,"buffer":6,"buffer-shims":5,"core-util-is":8,"events":13,"inherits":15,"process-nextick-args":23,"util-deprecate":47}],31:[function(require,module,exports){ +'use strict'; + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +module.exports = BufferList; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return bufferShim.alloc(0); + if (this.length === 1) return this.head.data; + var ret = bufferShim.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; +},{"buffer":6,"buffer-shims":5}],32:[function(require,module,exports){ +module.exports = require("./lib/_stream_passthrough.js") + +},{"./lib/_stream_passthrough.js":27}],33:[function(require,module,exports){ +(function (process){ +var Stream = (function (){ + try { + return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify + } catch(_){} +}()); +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream || exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; +} + +}).call(this,require('_process')) +},{"./lib/_stream_duplex.js":26,"./lib/_stream_passthrough.js":27,"./lib/_stream_readable.js":28,"./lib/_stream_transform.js":29,"./lib/_stream_writable.js":30,"_process":24}],34:[function(require,module,exports){ +module.exports = require("./lib/_stream_transform.js") + +},{"./lib/_stream_transform.js":29}],35:[function(require,module,exports){ +module.exports = require("./lib/_stream_writable.js") + +},{"./lib/_stream_writable.js":30}],36:[function(require,module,exports){ +(function (Buffer){ +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** @preserve +(c) 2012 by Cédric Mesnil. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// constants table +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] +var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] + +function bytesToWords (bytes) { + var words = [] + for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { + words[b >>> 5] |= bytes[i] << (24 - b % 32) + } + return words +} + +function wordsToBytes (words) { + var bytes = [] + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) + } + return bytes +} + +function processBlock (H, M, offset) { + // swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i + var M_offset_i = M[offset_i] + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ) + } + + // Working variables + var al, bl, cl, dl, el + var ar, br, cr, dr, er + + ar = al = H[0] + br = bl = H[1] + cr = cl = H[2] + dr = dl = H[3] + er = el = H[4] + + // computation + var t + for (i = 0; i < 80; i += 1) { + t = (al + M[offset + zl[i]]) | 0 + if (i < 16) { + t += f1(bl, cl, dl) + hl[0] + } else if (i < 32) { + t += f2(bl, cl, dl) + hl[1] + } else if (i < 48) { + t += f3(bl, cl, dl) + hl[2] + } else if (i < 64) { + t += f4(bl, cl, dl) + hl[3] + } else {// if (i<80) { + t += f5(bl, cl, dl) + hl[4] + } + t = t | 0 + t = rotl(t, sl[i]) + t = (t + el) | 0 + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = t + + t = (ar + M[offset + zr[i]]) | 0 + if (i < 16) { + t += f5(br, cr, dr) + hr[0] + } else if (i < 32) { + t += f4(br, cr, dr) + hr[1] + } else if (i < 48) { + t += f3(br, cr, dr) + hr[2] + } else if (i < 64) { + t += f2(br, cr, dr) + hr[3] + } else {// if (i<80) { + t += f1(br, cr, dr) + hr[4] + } + + t = t | 0 + t = rotl(t, sr[i]) + t = (t + er) | 0 + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = t + } + + // intermediate hash value + t = (H[1] + cl + dr) | 0 + H[1] = (H[2] + dl + er) | 0 + H[2] = (H[3] + el + ar) | 0 + H[3] = (H[4] + al + br) | 0 + H[4] = (H[0] + bl + cr) | 0 + H[0] = t +} + +function f1 (x, y, z) { + return ((x) ^ (y) ^ (z)) +} + +function f2 (x, y, z) { + return (((x) & (y)) | ((~x) & (z))) +} + +function f3 (x, y, z) { + return (((x) | (~(y))) ^ (z)) +} + +function f4 (x, y, z) { + return (((x) & (z)) | ((y) & (~(z)))) +} + +function f5 (x, y, z) { + return ((x) ^ ((y) | (~(z)))) +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function ripemd160 (message) { + var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] + + if (typeof message === 'string') { + message = new Buffer(message, 'utf8') + } + + var m = bytesToWords(message) + + var nBitsLeft = message.length * 8 + var nBitsTotal = message.length * 8 + + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) + m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ) + + for (var i = 0; i < m.length; i += 16) { + processBlock(H, m, i) + } + + // swap endian + for (i = 0; i < 5; i++) { + // shortcut + var H_i = H[i] + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00) + } + + var digestbytes = wordsToBytes(H) + return new Buffer(digestbytes) +} + +module.exports = ripemd160 + +}).call(this,require("buffer").Buffer) +},{"buffer":6}],37:[function(require,module,exports){ +(function (Buffer){ +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = new Buffer(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + this._s = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = new Buffer(data, enc) + } + + var l = this._len += data.length + var s = this._s || 0 + var f = 0 + var buffer = this._block + + while (s < l) { + var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) + var ch = (t - f) + + for (var i = 0; i < ch; i++) { + buffer[(s % this._blockSize) + i] = data[i + f] + } + + s += ch + f += ch + + if ((s % this._blockSize) === 0) { + this._update(buffer) + } + } + this._s = s + + return this +} + +Hash.prototype.digest = function (enc) { + // Suppose the length of the message M, in bits, is l + var l = this._len * 8 + + // Append the bit 1 to the end of the message + this._block[this._len % this._blockSize] = 0x80 + + // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize + this._block.fill(0, this._len % this._blockSize + 1) + + if (l % (this._blockSize * 8) >= this._finalSize * 8) { + this._update(this._block) + this._block.fill(0) + } + + // to this append the block which is equal to the number l written in binary + // TODO: handle case where l is > Math.pow(2, 29) + this._block.writeInt32BE(l, this._blockSize - 4) + + var hash = this._update(this._block) || this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + +}).call(this,require("buffer").Buffer) +},{"buffer":6}],38:[function(require,module,exports){ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') + +},{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(require,module,exports){ +(function (Buffer){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":6,"inherits":15}],40:[function(require,module,exports){ +(function (Buffer){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":6,"inherits":15}],41:[function(require,module,exports){ +(function (Buffer){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = new Buffer(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"./sha256":42,"buffer":6,"inherits":15}],42:[function(require,module,exports){ +(function (Buffer){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = new Buffer(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":6,"inherits":15}],43:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = new Buffer(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"./sha512":44,"buffer":6,"inherits":15}],44:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = new Buffer(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":6,"inherits":15}],45:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":13,"inherits":15,"readable-stream/duplex.js":25,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],46:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +},{"buffer":6}],47:[function(require,module,exports){ +(function (global){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],48:[function(require,module,exports){ +(function (Buffer){ +var pbkdf2 = require('pbkdf2'); +var Promise = require('pinkie-promise'); + + +function shouldUseNative() { + return !!(typeof window !== 'undefined' && window.crypto && window.crypto.subtle); +} + +function pbkdf2Native(password, salt, iterations, keylen, digest) { + var algorithms = { + 'sha1': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha512': 'SHA-512', + 'sha-512': 'SHA-512', + }; + return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']) + .then(function (key) { + var algo = { + name: 'PBKDF2', + salt: new Buffer(salt), + iterations: iterations, + hash: algorithms[digest.toLowerCase()], + }; + return window.crypto.subtle.deriveKey(algo, key, { + name: 'AES-CTR', + length: keylen * 8 + }, true, ['encrypt', 'decrypt']); + }) + .then(function (derivedKey) { + return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArray) { + return new Buffer(keyArray).toString('hex'); + }); + }); +} + +function pbkdf2Browserified(password, salt, iterations, keylen, digest) { + return new Promise(function (resolve, reject) { + pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function (error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } + }); + }); +} + + +module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; +}).call(this,require("buffer").Buffer) +},{"buffer":6,"pbkdf2":19,"pinkie-promise":21}],49:[function(require,module,exports){ +(function (Buffer){ +var pbkdf2 = require('./pbkdf2'); +var createHMAC = require('create-hmac'); +var Promise = require('pinkie-promise'); + + +module.exports = { + encryptLogin: encryptLogin, + renderPassword: renderPassword, + createFingerprint: createFingerprint, + _deriveEncryptedLogin: deriveEncryptedLogin, + _getPasswordTemplate: getPasswordTemplate, + _prettyPrint: prettyPrint, + _string2charCodes: string2charCodes, + _getCharType: getCharType, + _getPasswordChar: getPasswordChar, + _createHmac: createHmac, +}; + + +function encryptLogin(login, masterPassword, options) { + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); +} + +function renderPassword(encryptedLogin, site, passwordOptions) { + return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { + var template = passwordOptions.template || getPasswordTemplate(passwordOptions); + return prettyPrint(derivedEncryptedLogin, template); + }); +} + +function createHmac(encryptedLogin, salt) { + return new Promise(function (resolve) { + resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + }); +} + +function deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; + + var salt = site + counter.toString(); + return createHmac(encryptedLogin, salt).then(function (derivedHash) { + return derivedHash.substring(0, length); + }); +} + +function getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var returnedTemplate = ''; + Object.keys(templates).forEach(function (template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template] + } + }); + return returnedTemplate; +} + +function prettyPrint(hash, template) { + var password = ''; + + string2charCodes(hash).forEach(function (charCode, index) { + var charType = getCharType(template, index); + password += getPasswordChar(charType, charCode); + }); + return password; +} + +function string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function getCharType(template, index) { + return template[index % template.length]; +} + +function getPasswordChar(charType, index) { + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +function createFingerprint(str) { + return new Promise(function (resolve) { + resolve(createHMAC('sha256', new Buffer(str)).digest('hex')) + }); +} +}).call(this,require("buffer").Buffer) +},{"./pbkdf2":48,"buffer":6,"create-hmac":12,"pinkie-promise":21}],50:[function(require,module,exports){ +var pbkdf2 = require('./pbkdf2'); +var bigInt = require("big-integer"); +var objectAssign = require('object-assign'); + +module.exports = { + generatePassword: generatePassword, + _calcEntropy: calcEntropy, + _consumeEntropy: consumeEntropy, + _getSetOfCharacters: getSetOfCharacters, + _getConfiguredRules: getConfiguredRules, + _insertStringPseudoRandomly: insertStringPseudoRandomly, + _getOneCharPerRule: getOneCharPerRule, + _renderPassword: renderPassword +}; + +function generatePassword(site, login, masterPassword, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + return calcEntropy(site, login, masterPassword, _passwordProfile).then(function (entropy) { + return renderPassword(entropy, _passwordProfile); + }); +} + +var defaultPasswordProfile = { + lowercase: true, + uppercase: true, + digits: true, + symbols: true, + length: 16, + index: 1, + iterations: 100000, + keylen: 32, + digest: 'sha256' +}; + +function calcEntropy(site, login, masterPassword, passwordProfile) { + var salt = site + login + passwordProfile.index.toString(16); + return pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest); +} + +var characterSubsets = { + lowercase: 'abcdefghijklmnopqrstuvwxyz', + uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + digits: '0123456789', + symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' +}; + +function getSetOfCharacters(rules) { + if (typeof rules === 'undefined') { + return characterSubsets.lowercase + characterSubsets.uppercase + characterSubsets.digits + characterSubsets.symbols; + } + var setOfChars = ''; + rules.forEach(function (rule) { + setOfChars += characterSubsets[rule]; + }); + return setOfChars; +} + +function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { + if (generatedPassword.length >= maxLength) { + return {value: generatedPassword, entropy: quotient}; + } + var longDivision = quotient.divmod(setOfCharacters.length); + generatedPassword += setOfCharacters[longDivision.remainder]; + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); +} + +function insertStringPseudoRandomly(generatedPassword, entropy, string) { + for (var i = 0; i < string.length; i++) { + var longDivision = entropy.divmod(generatedPassword.length); + generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); + entropy = longDivision.quotient; + } + return generatedPassword; +} + +function getOneCharPerRule(entropy, rules) { + var oneCharPerRules = ''; + rules.forEach(function (rule) { + var password = consumeEntropy('', entropy, characterSubsets[rule], 1); + oneCharPerRules += password.value; + entropy = password.entropy; + }); + return {value: oneCharPerRules, entropy: entropy}; +} + +function getConfiguredRules(passwordProfile) { + return ['lowercase', 'uppercase', 'digits', 'symbols'].filter(function (rule) { + return passwordProfile[rule]; + }); +} + +function renderPassword(entropy, passwordProfile) { + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + var rules = getConfiguredRules(_passwordProfile); + var setOfCharacters = getSetOfCharacters(rules); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, _passwordProfile.length - rules.length); + var charactersToAdd = getOneCharPerRule(password.entropy, rules); + return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); +} + +},{"./pbkdf2":48,"big-integer":3,"object-assign":18}]},{},[1])(1) +}); \ No newline at end of file diff --git a/example/lesspass.html b/example/lesspass.html index 3c46d32..ea891cc 100644 --- a/example/lesspass.html +++ b/example/lesspass.html @@ -2,7 +2,7 @@ - + + + - \ No newline at end of file + diff --git a/src/lesspass.js b/src/lesspass.js index 3c24127..9d3c1da 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -4,59 +4,59 @@ var pbkdf2 = require('./pbkdf2'); var objectAssign = require('object-assign'); module.exports = { - encryptLogin: v1.encryptLogin, - renderPassword: v1.renderPassword, - createFingerprint: v1.createFingerprint, - _deriveEncryptedLogin: v1._deriveEncryptedLogin, - _getPasswordTemplate: v1._getPasswordTemplate, - _prettyPrint: v1._prettyPrint, - _string2charCodes: v1._string2charCodes, - _getCharType: v1._getCharType, - _getPasswordChar: v1._getPasswordChar, - _createHmac: v1._createHmac, + encryptLogin: v1.encryptLogin, + renderPassword: v1.renderPassword, + createFingerprint: v1.createFingerprint, + _deriveEncryptedLogin: v1._deriveEncryptedLogin, + _getPasswordTemplate: v1._getPasswordTemplate, + _prettyPrint: v1._prettyPrint, + _string2charCodes: v1._string2charCodes, + _getCharType: v1._getCharType, + _getPasswordChar: v1._getPasswordChar, + _createHmac: v1._createHmac, - generatePassword: generatePassword, - _calcEntropy: v2._calcEntropy, - _consumeEntropy: v2._consumeEntropy, - _getSetOfCharacters: v2._getSetOfCharacters, - _getConfiguredRules: v2._getConfiguredRules, - _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, - _getOneCharPerRule: v2._getOneCharPerRule, - _renderPassword: v2._renderPassword, + generatePassword: generatePassword, + _calcEntropy: v2._calcEntropy, + _consumeEntropy: v2._consumeEntropy, + _getSetOfCharacters: v2._getSetOfCharacters, + _getConfiguredRules: v2._getConfiguredRules, + _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, + _getOneCharPerRule: v2._getOneCharPerRule, + _renderPassword: v2._renderPassword, - pbkdf2: pbkdf2 + pbkdf2: pbkdf2 }; var defaultPasswordProfile = { - version: 2, - lowercase: true, - numbers: true, - uppercase: true, - symbols: true, - keylen: 32, - digest: 'sha256', - length: 16, - index: 1, - iterations: 100000 + version: 2, + lowercase: true, + numbers: true, + uppercase: true, + symbols: true, + keylen: 32, + digest: 'sha256', + length: 16, + index: 1, + iterations: 100000 }; function generatePassword(site, login, masterPassword, passwordProfile) { - var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); - if (_passwordProfile.version === 1) { - var options = { - counter: _passwordProfile.counter, - length: _passwordProfile.length, - lowercase: _passwordProfile.lowercase, - uppercase: _passwordProfile.uppercase, - numbers: _passwordProfile.numbers, - symbols: _passwordProfile.symbols - }; - return v1.encryptLogin(login, masterPassword) - .then(function (encryptedLogin) { - return v1.renderPassword(encryptedLogin, site, options).then(function (generatedPassword) { - return generatedPassword - }); - }); - } - return v2.generatePassword(site, login, masterPassword, _passwordProfile); -} \ No newline at end of file + var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); + if (_passwordProfile.version === 1) { + var options = { + counter: _passwordProfile.counter, + length: _passwordProfile.length, + lowercase: _passwordProfile.lowercase, + uppercase: _passwordProfile.uppercase, + numbers: _passwordProfile.numbers, + symbols: _passwordProfile.symbols + }; + return v1.encryptLogin(login, masterPassword) + .then(function(encryptedLogin) { + return v1.renderPassword(encryptedLogin, site, options).then(function(generatedPassword) { + return generatedPassword + }); + }); + } + return v2.generatePassword(site, login, masterPassword, _passwordProfile); +} diff --git a/src/pbkdf2.js b/src/pbkdf2.js index 2400e8c..560b826 100644 --- a/src/pbkdf2.js +++ b/src/pbkdf2.js @@ -3,49 +3,49 @@ var Promise = require('pinkie-promise'); function shouldUseNative() { - return !!(typeof window !== 'undefined' && window.crypto && window.crypto.subtle); + return !!(typeof window !== 'undefined' && window.crypto && window.crypto.subtle); } function pbkdf2Native(password, salt, iterations, keylen, digest) { - var algorithms = { - 'sha1': 'SHA-1', - 'sha-1': 'SHA-1', - 'sha256': 'SHA-256', - 'sha-256': 'SHA-256', - 'sha512': 'SHA-512', - 'sha-512': 'SHA-512', - }; - return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']) - .then(function (key) { - var algo = { - name: 'PBKDF2', - salt: new Buffer(salt), - iterations: iterations, - hash: algorithms[digest.toLowerCase()], - }; - return window.crypto.subtle.deriveKey(algo, key, { - name: 'AES-CTR', - length: keylen * 8 - }, true, ['encrypt', 'decrypt']); - }) - .then(function (derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArray) { - return new Buffer(keyArray).toString('hex'); - }); - }); + var algorithms = { + 'sha1': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha512': 'SHA-512', + 'sha-512': 'SHA-512', + }; + return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']) + .then(function(key) { + var algo = { + name: 'PBKDF2', + salt: new Buffer(salt), + iterations: iterations, + hash: algorithms[digest.toLowerCase()], + }; + return window.crypto.subtle.deriveKey(algo, key, { + name: 'AES-CTR', + length: keylen * 8 + }, true, ['encrypt', 'decrypt']); + }) + .then(function(derivedKey) { + return window.crypto.subtle.exportKey('raw', derivedKey).then(function(keyArray) { + return new Buffer(keyArray).toString('hex'); + }); + }); } function pbkdf2Browserified(password, salt, iterations, keylen, digest) { - return new Promise(function (resolve, reject) { - pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); - } - }); + return new Promise(function(resolve, reject) { + pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function(error, key) { + if (error) { + reject('error in pbkdf2'); + } else { + resolve(key.toString('hex')); + } }); + }); } -module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; \ No newline at end of file +module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; diff --git a/src/v1.js b/src/v1.js index 9c263da..6901581 100644 --- a/src/v1.js +++ b/src/v1.js @@ -4,106 +4,106 @@ var Promise = require('pinkie-promise'); module.exports = { - encryptLogin: encryptLogin, - renderPassword: renderPassword, - createFingerprint: createFingerprint, - _deriveEncryptedLogin: deriveEncryptedLogin, - _getPasswordTemplate: getPasswordTemplate, - _prettyPrint: prettyPrint, - _string2charCodes: string2charCodes, - _getCharType: getCharType, - _getPasswordChar: getPasswordChar, - _createHmac: createHmac, + encryptLogin: encryptLogin, + renderPassword: renderPassword, + createFingerprint: createFingerprint, + _deriveEncryptedLogin: deriveEncryptedLogin, + _getPasswordTemplate: getPasswordTemplate, + _prettyPrint: prettyPrint, + _string2charCodes: string2charCodes, + _getCharType: getCharType, + _getPasswordChar: getPasswordChar, + _createHmac: createHmac, }; function encryptLogin(login, masterPassword, options) { - var _options = options !== undefined ? options : {}; - var iterations = _options.iterations || 8192; - var keylen = _options.keylen || 32; - return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); + var _options = options !== undefined ? options : {}; + var iterations = _options.iterations || 8192; + var keylen = _options.keylen || 32; + return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); } function renderPassword(encryptedLogin, site, passwordOptions) { - return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = passwordOptions.template || getPasswordTemplate(passwordOptions); - return prettyPrint(derivedEncryptedLogin, template); - }); + return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function(derivedEncryptedLogin) { + var template = passwordOptions.template || getPasswordTemplate(passwordOptions); + return prettyPrint(derivedEncryptedLogin, template); + }); } function createHmac(encryptedLogin, salt) { - return new Promise(function (resolve) { - resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); - }); + return new Promise(function(resolve) { + resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + }); } function deriveEncryptedLogin(encryptedLogin, site, options) { - var _options = options !== undefined ? options : {}; - var length = _options.length || 12; - var counter = _options.counter || 1; + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; - var salt = site + counter.toString(); - return createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, length); - }); + var salt = site + counter.toString(); + return createHmac(encryptedLogin, salt).then(function(derivedHash) { + return derivedHash.substring(0, length); + }); } function getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', - }; - var returnedTemplate = ''; - Object.keys(templates).forEach(function (template) { - if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { - returnedTemplate += templates[template] - } - }); - return returnedTemplate; + var templates = { + lowercase: 'vc', + uppercase: 'VC', + numbers: 'n', + symbols: 's', + }; + var returnedTemplate = ''; + Object.keys(templates).forEach(function(template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template] + } + }); + return returnedTemplate; } function prettyPrint(hash, template) { - var password = ''; + var password = ''; - string2charCodes(hash).forEach(function (charCode, index) { - var charType = getCharType(template, index); - password += getPasswordChar(charType, charCode); - }); - return password; + string2charCodes(hash).forEach(function(charCode, index) { + var charType = getCharType(template, index); + password += getPasswordChar(charType, charCode); + }); + return password; } function string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; } function getCharType(template, index) { - return template[index % template.length]; + return template[index % template.length]; } function getPasswordChar(charType, index) { - var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; + var passwordsChars = { + V: 'AEIOUY', + C: 'BCDFGHJKLMNPQRSTVWXZ', + v: 'aeiouy', + c: 'bcdfghjklmnpqrstvwxz', + A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', + a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', + n: '0123456789', + s: '@&%?,=[]_:-+*$#!\'^~;()/.', + x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; } function createFingerprint(str) { - return new Promise(function (resolve) { - resolve(createHMAC('sha256', new Buffer(str)).digest('hex')) - }); -} \ No newline at end of file + return new Promise(function(resolve) { + resolve(createHMAC('sha256', new Buffer(str)).digest('hex')) + }); +} diff --git a/src/v2.js b/src/v2.js index d770fd2..3c6995f 100644 --- a/src/v2.js +++ b/src/v2.js @@ -2,83 +2,83 @@ var pbkdf2 = require('./pbkdf2'); var bigInt = require("big-integer"); module.exports = { - generatePassword: generatePassword, - _calcEntropy: calcEntropy, - _consumeEntropy: consumeEntropy, - _getSetOfCharacters: getSetOfCharacters, - _getConfiguredRules: getConfiguredRules, - _insertStringPseudoRandomly: insertStringPseudoRandomly, - _getOneCharPerRule: getOneCharPerRule, - _renderPassword: renderPassword + generatePassword: generatePassword, + _calcEntropy: calcEntropy, + _consumeEntropy: consumeEntropy, + _getSetOfCharacters: getSetOfCharacters, + _getConfiguredRules: getConfiguredRules, + _insertStringPseudoRandomly: insertStringPseudoRandomly, + _getOneCharPerRule: getOneCharPerRule, + _renderPassword: renderPassword }; function generatePassword(site, login, masterPassword, passwordProfile) { - return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - return renderPassword(entropy, passwordProfile); - }); + return calcEntropy(site, login, masterPassword, passwordProfile).then(function(entropy) { + return renderPassword(entropy, passwordProfile); + }); } function calcEntropy(site, login, masterPassword, passwordProfile) { - var salt = site + login + passwordProfile.counter.toString(16); - return pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest); + var salt = site + login + passwordProfile.counter.toString(16); + return pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest); } var characterSubsets = { - lowercase: 'abcdefghijklmnopqrstuvwxyz', - uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - numbers: '0123456789', - symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' + lowercase: 'abcdefghijklmnopqrstuvwxyz', + uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + numbers: '0123456789', + symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' }; function getSetOfCharacters(rules) { - if (typeof rules === 'undefined') { - return characterSubsets.lowercase + characterSubsets.uppercase + characterSubsets.numbers + characterSubsets.symbols; - } - var setOfChars = ''; - rules.forEach(function (rule) { - setOfChars += characterSubsets[rule]; - }); - return setOfChars; + if (typeof rules === 'undefined') { + return characterSubsets.lowercase + characterSubsets.uppercase + characterSubsets.numbers + characterSubsets.symbols; + } + var setOfChars = ''; + rules.forEach(function(rule) { + setOfChars += characterSubsets[rule]; + }); + return setOfChars; } function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { - if (generatedPassword.length >= maxLength) { - return {value: generatedPassword, entropy: quotient}; - } - var longDivision = quotient.divmod(setOfCharacters.length); - generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); + if (generatedPassword.length >= maxLength) { + return {value: generatedPassword, entropy: quotient}; + } + var longDivision = quotient.divmod(setOfCharacters.length); + generatedPassword += setOfCharacters[longDivision.remainder]; + return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); } function insertStringPseudoRandomly(generatedPassword, entropy, string) { - for (var i = 0; i < string.length; i++) { - var longDivision = entropy.divmod(generatedPassword.length); - generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); - entropy = longDivision.quotient; - } - return generatedPassword; + for (var i = 0; i < string.length; i++) { + var longDivision = entropy.divmod(generatedPassword.length); + generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); + entropy = longDivision.quotient; + } + return generatedPassword; } function getOneCharPerRule(entropy, rules) { - var oneCharPerRules = ''; - rules.forEach(function (rule) { - var password = consumeEntropy('', entropy, characterSubsets[rule], 1); - oneCharPerRules += password.value; - entropy = password.entropy; - }); - return {value: oneCharPerRules, entropy: entropy}; + var oneCharPerRules = ''; + rules.forEach(function(rule) { + var password = consumeEntropy('', entropy, characterSubsets[rule], 1); + oneCharPerRules += password.value; + entropy = password.entropy; + }); + return {value: oneCharPerRules, entropy: entropy}; } function getConfiguredRules(passwordProfile) { - return ['lowercase', 'uppercase', 'numbers', 'symbols'].filter(function (rule) { - return passwordProfile[rule]; - }); + return ['lowercase', 'uppercase', 'numbers', 'symbols'].filter(function(rule) { + return passwordProfile[rule]; + }); } function renderPassword(entropy, passwordProfile) { - var rules = getConfiguredRules(passwordProfile); - var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, passwordProfile.length - rules.length); - var charactersToAdd = getOneCharPerRule(password.entropy, rules); - return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); + var rules = getConfiguredRules(passwordProfile); + var setOfCharacters = getSetOfCharacters(rules); + var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, passwordProfile.length - rules.length); + var charactersToAdd = getOneCharPerRule(password.entropy, rules); + return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); } diff --git a/tests/karma.config.js b/tests/karma.config.js index 6ba61c5..8cd0675 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -1,29 +1,29 @@ -module.exports = function (config) { - var configuration = { - basePath: '..', - frameworks: ['mocha', 'chai'], - files: [ - 'node_modules/big-integer/BigInteger.min.js', - 'dist/lesspass.js', - 'tests/**/*.js' - ], - exclude: [ - 'tests/node.js', - 'tests/helper.js', - 'tests/karma.webcrypto.config.js', - ], - preprocessors: {}, - reporters: ['progress'], - port: 9876, - colors: true, - logLevel: config.LOG_INFO, - autoWatch: true, - browsers: ['Chrome', 'Firefox'], - singleRun: true, - concurrency: Infinity - }; - if (process.env.TRAVIS) { - configuration.browsers = ['PhantomJS']; - } - config.set(configuration) +module.exports = function(config) { + var configuration = { + basePath: '..', + frameworks: ['mocha', 'chai'], + files: [ + 'node_modules/big-integer/BigInteger.min.js', + 'dist/lesspass.js', + 'tests/**/*.js' + ], + exclude: [ + 'tests/node.js', + 'tests/helper.js', + 'tests/karma.webcrypto.config.js', + ], + preprocessors: {}, + reporters: ['progress'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome', 'Firefox'], + singleRun: true, + concurrency: Infinity + }; + if (process.env.TRAVIS) { + configuration.browsers = ['PhantomJS']; + } + config.set(configuration) }; diff --git a/tests/node.js b/tests/node.js index e2a3a34..cba9e73 100644 --- a/tests/node.js +++ b/tests/node.js @@ -5,19 +5,19 @@ const site = 'lesspass.com'; const login = 'contact@lesspass.com'; const masterPassword = 'password'; const passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 16, - counter: 1, - version: 2 + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 16, + counter: 1, + version: 2 }; LessPass.generatePassword(site, login, masterPassword, passwordProfile) - .then(function (generatedPassword) { - assert.equal(generatedPassword, '\\g-A1-.OHEwrXjT#'); - console.log('generated password ok'); - }) - .catch(function (e) { - console.log(e); - }); \ No newline at end of file + .then(function(generatedPassword) { + assert.equal(generatedPassword, '\\g-A1-.OHEwrXjT#'); + console.log('generated password ok'); + }) + .catch(function(e) { + console.log(e); + }); diff --git a/tests/pbkdf2.tests.js b/tests/pbkdf2.tests.js index c3f692d..c2f9dbf 100644 --- a/tests/pbkdf2.tests.js +++ b/tests/pbkdf2.tests.js @@ -1,13 +1,13 @@ var assert = chai.assert; -describe('LessPass', function () { - describe('pbkdf2', function () { - it('should secret, salt, 2, 32, sha256', function () { - return LessPass.pbkdf2('secret', 'salt', 2, 32, 'sha256').then(function (key) { - assert.equal('f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569', key); - }) - }); +describe('LessPass', function() { + describe('pbkdf2', function() { + it('should secret, salt, 2, 32, sha256', function() { + return LessPass.pbkdf2('secret', 'salt', 2, 32, 'sha256').then(function(key) { + assert.equal('f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569', key); + }) }); + }); }); diff --git a/tests/v1/api.tests.js b/tests/v1/api.tests.js index a455edb..648955e 100644 --- a/tests/v1/api.tests.js +++ b/tests/v1/api.tests.js @@ -1,584 +1,545 @@ var assert = chai.assert; -describe('LessPass v1', function () { - describe('encryptLogin', function () { - it('should use pbkdf2 with 8192 iterations and sha256', function (done) { - LessPass.encryptLogin('test@example.org', 'password').then(function (encryptedLogin) { - assert.equal('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); - done(); - }); - }); - - it('should allow to customize number of iterations', function (done) { - LessPass.encryptLogin('test@example.org', 'password', {iterations: 4096}).then(function (encryptedLogin) { - assert.equal('0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f', encryptedLogin); - done(); - }); - }); - - it('should allow to customize key length', function (done) { - LessPass.encryptLogin('test@example.org', 'password', {keylen: 16}).then(function (encryptedLogin) { - assert.equal('d8af5f918db6b65b1db3d3984e5a400e', encryptedLogin); - done(); - }); - }); - - it('should allow to customize iterations and key length', function (done) { - LessPass.encryptLogin('test@example.org', 'password', { - iterations: 4096, - keylen: 16 - }).then(function (encryptedLogin) { - assert.equal('0a91208545e3aa4935d3a22984ca097a', encryptedLogin); - done(); - }); - }); - - it('should allow utf8 parameter', function () { - return LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function (encryptedLogin) { - assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 0', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 1', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 2', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 3', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 4', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 5', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 6', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 7', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 8', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function (encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 9', function () { - return LessPass.encryptLogin('lesspass', 'password').then(function (encryptedLogin) { - assert.equal('7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', encryptedLogin); - }); - }); - - it('encryptLogin auto generated test 10', function () { - return LessPass.encryptLogin('contact@lesspass.com', 'password2').then(function (encryptedLogin) { - assert.equal('ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', encryptedLogin); - }); - }); +describe('LessPass v1', function() { + describe('encryptLogin', function() { + it('should use pbkdf2 with 8192 iterations and sha256', function(done) { + LessPass.encryptLogin('test@example.org', 'password').then(function(encryptedLogin) { + assert.equal('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); + done(); + }); }); - - describe('renderPassword', function () { - it('render password', function (done) { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - done(); - }) - }); - - it('render password with a custom template', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'n' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - var i = generatedPassword.length; - while (i--) { - assert('0123456789'.indexOf(generatedPassword[i]) !== -1) - } - }) - }); - - it('render password with a custom template too short', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'CvcnCVsn' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('Sor4WU:8Wad5', generatedPassword); - }) - }); - - it('render password with a custom template too long', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 6, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'CvcnCVsn' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('Sor4WU', generatedPassword); - }) - }); - - it('render password auto generated test 0', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - }) - }); - - it('render password auto generated test 1', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 14, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azYS7,olOL2]iz', generatedPassword); - }) - }); - - it('render password auto generated test 2', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: false, - numbers: false, - symbols: false, - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azyseqololat', generatedPassword); - }) - }); - - it('render password auto generated test 3', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: false, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('AZ3[EQ7@OL2]', generatedPassword); - }) - }); - - it('render password auto generated test 4', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('4?3[7,7@7@2]', generatedPassword); - }) - }); - - it('render password auto generated test 5', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: false, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('[?=[&,:@:@[]', generatedPassword); - }) - }); - - it('render password auto generated test 6', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: false - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azYS7uwAW8at', generatedPassword); - }) - }); - - it('render password auto generated test 7', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: false, - symbols: false - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('azYSeqOLolAT', generatedPassword); - }) - }); - - it('render password auto generated test 8', function () { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 2, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('obYT2=olOV9=', generatedPassword); - }) - }); - - it('render password auto generated test 9', function () { - var site = 'lesspass.com'; - var encryptedLogin = '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('erOC1%imIW3,', generatedPassword); - }) - }); - - it('render password auto generated test 10', function () { - var site = 'lesspass.com'; - var encryptedLogin = 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function (generatedPassword) { - assert.equal('uvUM5_ucUP5=', generatedPassword); - }) - }); - - + it('should allow to customize number of iterations', function(done) { + LessPass.encryptLogin('test@example.org', 'password', {iterations: 4096}).then(function(encryptedLogin) { + assert.equal('0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f', encryptedLogin); + done(); + }); }); - describe('fingerprint', function () { - it('createFingerprint', function () { - return LessPass.createFingerprint('password').then(function (fingerprint) { - assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); - }) - }); + it('should allow to customize key length', function(done) { + LessPass.encryptLogin('test@example.org', 'password', {keylen: 16}).then(function(encryptedLogin) { + assert.equal('d8af5f918db6b65b1db3d3984e5a400e', encryptedLogin); + done(); + }); + }); + it('should allow to customize iterations and key length', function(done) { + LessPass.encryptLogin('test@example.org', 'password', { + iterations: 4096, + keylen: 16 + }).then(function(encryptedLogin) { + assert.equal('0a91208545e3aa4935d3a22984ca097a', encryptedLogin); + done(); + }); + }); + it('should allow utf8 parameter', function() { + return LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function(encryptedLogin) { + assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 0', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 1', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 2', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 3', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 4', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 5', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 6', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 7', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 8', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { + assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 9', function() { + return LessPass.encryptLogin('lesspass', 'password').then(function(encryptedLogin) { + assert.equal('7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', encryptedLogin); + }); + }); + it('encryptLogin auto generated test 10', function() { + return LessPass.encryptLogin('contact@lesspass.com', 'password2').then(function(encryptedLogin) { + assert.equal('ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', encryptedLogin); + }); + }); + }); + + describe('renderPassword', function() { + it('render password', function(done) { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('azYS7,olOL2]', generatedPassword); + done(); + }) + }); + it('render password with a custom template', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'n' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + var i = generatedPassword.length; + while (i--) { + assert('0123456789'.indexOf(generatedPassword[i]) !== -1) + } + }) + }); + it('render password with a custom template too short', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'CvcnCVsn' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('Sor4WU:8Wad5', generatedPassword); + }) + }); + it('render password with a custom template too long', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 6, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: 'CvcnCVsn' + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('Sor4WU', generatedPassword); + }) + }); + it('render password auto generated test 0', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('azYS7,olOL2]', generatedPassword); + }) + }); + it('render password auto generated test 1', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 14, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('azYS7,olOL2]iz', generatedPassword); + }) + }); + it('render password auto generated test 2', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: false, + numbers: false, + symbols: false, + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('azyseqololat', generatedPassword); + }) + }); + it('render password auto generated test 3', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: false, + uppercase: true, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('AZ3[EQ7@OL2]', generatedPassword); + }) + }); + it('render password auto generated test 4', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('4?3[7,7@7@2]', generatedPassword); + }) + }); + it('render password auto generated test 5', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('[?=[&,:@:@[]', generatedPassword); + }) + }); + it('render password auto generated test 6', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: false + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('azYS7uwAW8at', generatedPassword); + }) + }); + it('render password auto generated test 7', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('azYSeqOLolAT', generatedPassword); + }) + }); + it('render password auto generated test 8', function() { + var site = 'lesspass.com'; + var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; + var passwordOptions = { + counter: 2, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('obYT2=olOV9=', generatedPassword); + }) + }); + it('render password auto generated test 9', function() { + var site = 'lesspass.com'; + var encryptedLogin = '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('erOC1%imIW3,', generatedPassword); + }) + }); + it('render password auto generated test 10', function() { + var site = 'lesspass.com'; + var encryptedLogin = 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4'; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { + assert.equal('uvUM5_ucUP5=', generatedPassword); + }) }); - describe('generatePassword', function () { - it('generate password', function () { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('izIS5@ozYM2?', generatedPassword); - }); - }); - it('generate password auto generated test 0', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - }); - }); - - it('generate password auto generated test 1', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 14, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('azYS7,olOL2]iz', generatedPassword); - }); - }); - - it('generate password auto generated test 2', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: false, - numbers: false, - symbols: false, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('azyseqololat', generatedPassword); - }); - }); - - it('generate password auto generated test 3', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('AZ3[EQ7@OL2]', generatedPassword); - }); - }); - - it('generate password auto generated test 4', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: false, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('4?3[7,7@7@2]', generatedPassword); - }); - }); - - it('generate password auto generated test 5', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: false, - numbers: false, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('[?=[&,:@:@[]', generatedPassword); - }); - }); - - it('generate password auto generated test 6', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: false, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('azYS7uwAW8at', generatedPassword); - }); - }); - - it('generate password auto generated test 7', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: false, - symbols: false, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('azYSeqOLolAT', generatedPassword); - }); - }); - - it('generate password auto generated test 8', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 2, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('obYT2=olOV9=', generatedPassword); - }); - }); - - it('generate password auto generated test 9', function () { - var site = 'lesspass.com'; - var login = 'lesspass'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('erOC1%imIW3,', generatedPassword); - }); - }); - it('generate password auto generated test 10', function () { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password2'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('uvUM5_ucUP5=', generatedPassword); - }); - }); + }); + describe('fingerprint', function() { + it('createFingerprint', function() { + return LessPass.createFingerprint('password').then(function(fingerprint) { + assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); + }) + }); + }); + + describe('generatePassword', function() { + it('generate password', function() { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('izIS5@ozYM2?', generatedPassword); + }); + }); + it('generate password auto generated test 0', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('azYS7,olOL2]', generatedPassword); + }); + }); + it('generate password auto generated test 1', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 14, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('azYS7,olOL2]iz', generatedPassword); + }); + }); + it('generate password auto generated test 2', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: false, + numbers: false, + symbols: false, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('azyseqololat', generatedPassword); + }); + }); + it('generate password auto generated test 3', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: false, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('AZ3[EQ7@OL2]', generatedPassword); + }); + }); + it('generate password auto generated test 4', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: false, + uppercase: false, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('4?3[7,7@7@2]', generatedPassword); + }); + }); + it('generate password auto generated test 5', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: false, + uppercase: false, + numbers: false, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('[?=[&,:@:@[]', generatedPassword); + }); + }); + it('generate password auto generated test 6', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('azYS7uwAW8at', generatedPassword); + }); + }); + it('generate password auto generated test 7', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: false, + symbols: false, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('azYSeqOLolAT', generatedPassword); + }); + }); + it('generate password auto generated test 8', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 2, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('obYT2=olOV9=', generatedPassword); + }); + }); + it('generate password auto generated test 9', function() { + var site = 'lesspass.com'; + var login = 'lesspass'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('erOC1%imIW3,', generatedPassword); + }); + }); + it('generate password auto generated test 10', function() { + var site = 'lesspass.com'; + var login = 'contact@lesspass.com'; + var masterPassword = 'password2'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1, + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('uvUM5_ucUP5=', generatedPassword); + }); }); + }); }); diff --git a/tests/v1/deriveEncryptedLogin.tests.js b/tests/v1/deriveEncryptedLogin.tests.js index 7395946..ca5045f 100644 --- a/tests/v1/deriveEncryptedLogin.tests.js +++ b/tests/v1/deriveEncryptedLogin.tests.js @@ -1,84 +1,84 @@ var assert = chai.assert; -describe('LessPass v1', function () { - describe('deriveEncryptedLogin', function () { - it('should createHmac', function () { - var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - var salt = 'lesspass.com1'; - return LessPass._createHmac(encryptedLogin, salt).then(function (hmac) { - assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); - }); - }); - it('should derive encrypted login with default options 1', function () { - const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (generatedPassword) { - assert.equal('ecd16aefc7e5', generatedPassword); - }); - }); - it('should derive encrypted login with default options 2', function () { - const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - const option = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - }; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { - assert.equal('ecd16aefc7e5', generatedPassword); - }); - }); - it('should derive encrypted login with defined length', function () { - var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - var site = 'lesspass.com'; - var option = { - counter: 1, - length: 10, - }; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (generatedPassword) { - assert.equal(10, generatedPassword.length); - }); - }); - it('should return two different passwords if site different 1', function () { - const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'google.com'; - return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (derivedEncryptedLogin) { - assert.equal('a957c3a459ec', derivedEncryptedLogin) - }); - }); - it('should return two different passwords if site different 2', function () { - const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'facebook.com'; - return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (derivedEncryptedLogin) { - assert.equal('d9f3a918c34b', derivedEncryptedLogin) - }); - }); - it('should return two different passwords if counter different 1', function () { - const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option = {counter: 1}; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function (derivedEncryptedLogins) { - assert.equal('bb2e0b34036d', derivedEncryptedLogins) - }); - }); - it('should return two different passwords if counter different 2', function () { - const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option2 = {counter: 2}; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option2).then(function (derivedEncryptedLogins) { - assert.equal('67fe8c05a248', derivedEncryptedLogins) - }); - }); - it('should derive encrypted login with sha 256', function () { - const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function (encryptedLogin) { - assert.equal('be00f942fc8a', encryptedLogin); - }); - }); +describe('LessPass v1', function() { + describe('deriveEncryptedLogin', function() { + it('should createHmac', function() { + var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + var salt = 'lesspass.com1'; + return LessPass._createHmac(encryptedLogin, salt).then(function(hmac) { + assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); + }); }); + it('should derive encrypted login with default options 1', function() { + const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + const site = 'lesspass.com'; + return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(generatedPassword) { + assert.equal('ecd16aefc7e5', generatedPassword); + }); + }); + it('should derive encrypted login with default options 2', function() { + const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; + const site = 'lesspass.com'; + const option = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + }; + return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function(generatedPassword) { + assert.equal('ecd16aefc7e5', generatedPassword); + }); + }); + it('should derive encrypted login with defined length', function() { + var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; + var site = 'lesspass.com'; + var option = { + counter: 1, + length: 10, + }; + return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function(generatedPassword) { + assert.equal(10, generatedPassword.length); + }); + }); + it('should return two different passwords if site different 1', function() { + const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'google.com'; + return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(derivedEncryptedLogin) { + assert.equal('a957c3a459ec', derivedEncryptedLogin) + }); + }); + it('should return two different passwords if site different 2', function() { + const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; + const site = 'facebook.com'; + return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(derivedEncryptedLogin) { + assert.equal('d9f3a918c34b', derivedEncryptedLogin) + }); + }); + it('should return two different passwords if counter different 1', function() { + const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option = {counter: 1}; + return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function(derivedEncryptedLogins) { + assert.equal('bb2e0b34036d', derivedEncryptedLogins) + }); + }); + it('should return two different passwords if counter different 2', function() { + const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; + const site = 'lesspass.com'; + const option2 = {counter: 2}; + return LessPass._deriveEncryptedLogin(encryptedLogin, site, option2).then(function(derivedEncryptedLogins) { + assert.equal('67fe8c05a248', derivedEncryptedLogins) + }); + }); + it('should derive encrypted login with sha 256', function() { + const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; + const site = 'lesspass.com'; + LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(encryptedLogin) { + assert.equal('be00f942fc8a', encryptedLogin); + }); + }); + }); }); diff --git a/tests/v1/getPasswordTemplate.tests.js b/tests/v1/getPasswordTemplate.tests.js index 1e39beb..1072173 100644 --- a/tests/v1/getPasswordTemplate.tests.js +++ b/tests/v1/getPasswordTemplate.tests.js @@ -1,63 +1,63 @@ var assert = chai.assert; -describe('Lessass v1', function () { - describe('getPasswordTemplate', function () { - it('should get default template', function () { - assert.equal('vcVCns', LessPass._getPasswordTemplate({ - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - })); - }); - it('should get lowercase template', function () { - assert.equal('vc', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: false, - symbols: false - })); - }); - it('should get uppercase template', function () { - assert.equal('VC', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: true, - numbers: false, - symbols: false - })); - }); - it('should get numbers template', function () { - assert.equal('n', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: true, - symbols: false - })); - }); - it('should get symbols template', function () { - assert.equal('s', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: false, - symbols: true - })); - }); - it('should concatenate template if two password settings', function () { - assert.equal('vcVC', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: true, - numbers: false, - symbols: false - })); - assert.equal('vcns', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: true, - symbols: true - })); - }); +describe('Lessass v1', function() { + describe('getPasswordTemplate', function() { + it('should get default template', function() { + assert.equal('vcVCns', LessPass._getPasswordTemplate({ + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + })); }); + it('should get lowercase template', function() { + assert.equal('vc', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: false, + symbols: false + })); + }); + it('should get uppercase template', function() { + assert.equal('VC', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: true, + numbers: false, + symbols: false + })); + }); + it('should get numbers template', function() { + assert.equal('n', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: true, + symbols: false + })); + }); + it('should get symbols template', function() { + assert.equal('s', LessPass._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + })); + }); + it('should concatenate template if two password settings', function() { + assert.equal('vcVC', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + })); + assert.equal('vcns', LessPass._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: true, + symbols: true + })); + }); + }); }); diff --git a/tests/v1/prettyPrint.js b/tests/v1/prettyPrint.js index d7ef563..ff259db 100644 --- a/tests/v1/prettyPrint.js +++ b/tests/v1/prettyPrint.js @@ -1,35 +1,35 @@ var assert = chai.assert; -describe('LessPass v1', function () { - describe('prettyPrint', function () { - it('should print different password if templates different', function () { - var encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; - assert.notEqual(LessPass._prettyPrint(encryptedLogin, 'cv'), LessPass._prettyPrint(encryptedLogin, 'vc')); - }); - it('must return a string of the same length as the input', function () { - var hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; - assert.equal(hash.length, LessPass._prettyPrint(hash, 'cv').length); - }); - it('should return char inside a string based on modulo of the index', function () { - var template = 'cv'; - assert.equal('c', LessPass._getCharType(template, 0)); - assert.equal('v', LessPass._getCharType(template, 1)); - assert.equal('c', LessPass._getCharType(template, 10)); - }); - it('should convert a string into an array of char code', function () { - var charCodes = LessPass._string2charCodes('ab40f6ee71'); - assert.equal(97, charCodes[0]); - assert.equal(98, charCodes[1]); - assert.equal(10, charCodes.length); - }); - it('should get password char based on its type and index', function () { - var typeVowel = 'V'; - assert.equal('A', LessPass._getPasswordChar(typeVowel, 0)); - }); - it('should modulo if overflow', function () { - var typeVowel = 'V'; - assert.equal('E', LessPass._getPasswordChar(typeVowel, 1)); - assert.equal('E', LessPass._getPasswordChar(typeVowel, 7)); - }); +describe('LessPass v1', function() { + describe('prettyPrint', function() { + it('should print different password if templates different', function() { + var encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; + assert.notEqual(LessPass._prettyPrint(encryptedLogin, 'cv'), LessPass._prettyPrint(encryptedLogin, 'vc')); }); + it('must return a string of the same length as the input', function() { + var hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; + assert.equal(hash.length, LessPass._prettyPrint(hash, 'cv').length); + }); + it('should return char inside a string based on modulo of the index', function() { + var template = 'cv'; + assert.equal('c', LessPass._getCharType(template, 0)); + assert.equal('v', LessPass._getCharType(template, 1)); + assert.equal('c', LessPass._getCharType(template, 10)); + }); + it('should convert a string into an array of char code', function() { + var charCodes = LessPass._string2charCodes('ab40f6ee71'); + assert.equal(97, charCodes[0]); + assert.equal(98, charCodes[1]); + assert.equal(10, charCodes.length); + }); + it('should get password char based on its type and index', function() { + var typeVowel = 'V'; + assert.equal('A', LessPass._getPasswordChar(typeVowel, 0)); + }); + it('should modulo if overflow', function() { + var typeVowel = 'V'; + assert.equal('E', LessPass._getPasswordChar(typeVowel, 1)); + assert.equal('E', LessPass._getPasswordChar(typeVowel, 7)); + }); + }); }); diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index a7231bd..d6e988d 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -1,79 +1,79 @@ var assert = chai.assert; -describe('LessPass v2', function () { - describe('API', function () { - it('render password', function () { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 16, - counter: 1, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('WHLpUL)e00[iHR+w', generatedPassword); - }); - }); - it('render password no symbols', function () { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: false, - length: 14, - counter: 2, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('MBAsB7b1Prt8Sl', generatedPassword); - }); - }); - it('render password only digit', function () { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: false, - numbers: true, - symbols: false, - length: 6, - counter: 3, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal('117843', generatedPassword); - }); - }); - it('render password no number', function () { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: false, - symbols: true, - length: 14, - counter: 1, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function (generatedPassword) { - assert.equal("sB>{qF}wN%/-fm", generatedPassword); - }); - }); +describe('LessPass v2', function() { + describe('API', function() { + it('render password', function() { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 16, + counter: 1, + version: 2 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('WHLpUL)e00[iHR+w', generatedPassword); + }); }); + it('render password no symbols', function() { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + length: 14, + counter: 2, + version: 2 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('MBAsB7b1Prt8Sl', generatedPassword); + }); + }); + it('render password only digit', function() { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: false, + uppercase: false, + numbers: true, + symbols: false, + length: 6, + counter: 3, + version: 2 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal('117843', generatedPassword); + }); + }); + it('render password no number', function() { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + lowercase: true, + uppercase: true, + numbers: false, + symbols: true, + length: 14, + counter: 1, + version: 2 + }; + return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { + assert.equal("sB>{qF}wN%/-fm", generatedPassword); + }); + }); + }); }); diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js index cfc2814..30c25f2 100644 --- a/tests/v2/entropy.tests.js +++ b/tests/v2/entropy.tests.js @@ -1,58 +1,58 @@ var assert = chai.assert; -describe('LessPass v2', function () { - describe('entropy', function () { - it('calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)', function () { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - iterations: 100000, - keylen: 32, - digest: 'sha256', - counter: 1 - }; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); - }); - }); - it('calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)', function () { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - iterations: 8192, - keylen: 16, - digest: 'sha512', - counter: 1 - }; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); - }); - }); - it('calc entropy different if counter different 1', function () { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile1 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 1}; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile1).then(function (entropy) { - assert.equal('d3ec1e988dd0b3640c7491cd2c2a88b5', entropy) - }); - }); - it('calc entropy different if counter different 2', function () { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile2 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 2}; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile2).then(function (entropy) { - assert.equal('ddfb1136260f930c21f6d72f6eddbd40', entropy) - }); - }); - it('consume entropy', function () { - var password = LessPass._consumeEntropy('', bigInt(4 * 4 + 2), "abcd", 2); - assert.equal('ca', password.value); - assert.equal(1, password.entropy) - }); +describe('LessPass v2', function() { + describe('entropy', function() { + it('calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)', function() { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 100000, + keylen: 32, + digest: 'sha256', + counter: 1 + }; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function(entropy) { + assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); + }); }); + it('calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)', function() { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile = { + iterations: 8192, + keylen: 16, + digest: 'sha512', + counter: 1 + }; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function(entropy) { + assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); + }); + }); + it('calc entropy different if counter different 1', function() { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile1 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 1}; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile1).then(function(entropy) { + assert.equal('d3ec1e988dd0b3640c7491cd2c2a88b5', entropy) + }); + }); + it('calc entropy different if counter different 2', function() { + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + var passwordProfile2 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 2}; + return LessPass._calcEntropy(site, login, masterPassword, passwordProfile2).then(function(entropy) { + assert.equal('ddfb1136260f930c21f6d72f6eddbd40', entropy) + }); + }); + it('consume entropy', function() { + var password = LessPass._consumeEntropy('', bigInt(4 * 4 + 2), "abcd", 2); + assert.equal('ca', password.value); + assert.equal(1, password.entropy) + }); + }); }); diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js index ee671ac..2de96f1 100644 --- a/tests/v2/renderPassword.tests.js +++ b/tests/v2/renderPassword.tests.js @@ -1,70 +1,70 @@ var assert = chai.assert; -describe('LessPass v2', function () { - var defaultPasswordProfile = { - length: 16, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true +describe('LessPass v2', function() { + var defaultPasswordProfile = { + length: 16, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + it('render password use remainder of long division beetween entropy and set of chars length as an index', function() { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + assert.equal('W', LessPass._renderPassword(entropy, defaultPasswordProfile)[0]); + }); + it('render password use quotient as second entropy recursively', function() { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + assert.equal('H', LessPass._renderPassword(entropy, defaultPasswordProfile)[1]); + }); + it('render password has default length of 16', function() { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + assert.equal(16, LessPass._renderPassword(entropy, defaultPasswordProfile).length); + }); + it('render password can specify length', function() { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var passwordProfile = { + length: 20, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true }; - it('render password use remainder of long division beetween entropy and set of chars length as an index', function () { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal('W', LessPass._renderPassword(entropy, defaultPasswordProfile)[0]); - }); - it('render password use quotient as second entropy recursively', function () { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal('H', LessPass._renderPassword(entropy, defaultPasswordProfile)[1]); - }); - it('render password has default length of 16', function () { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal(16, LessPass._renderPassword(entropy, defaultPasswordProfile).length); - }); - it('render password can specify length', function () { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var passwordProfile = { - length: 20, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - assert.equal(20, LessPass._renderPassword(entropy, passwordProfile).length); - }); - it('include one char per set of characters', function () { - var password = LessPass._insertStringPseudoRandomly('123456', bigInt(7 * 6 + 2), 'uT'); - assert.equal('T12u3456', password); - }); - it('render password return at least one char in every characters set', function () { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var passwordProfile = { - length: 6, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - }; - var generatedPassword = LessPass._renderPassword(entropy, passwordProfile); - var passwordLength = generatedPassword.length; - var lowercaseOk = false; - var uppercaseOk = false; - var numbersOk = false; - var symbolsOk = false; - while (passwordLength--) { - if ('abcdefghijklmnopqrstuvwxyz'.indexOf(generatedPassword[passwordLength]) !== -1) { - lowercaseOk = true; - } - if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(generatedPassword[passwordLength]) !== -1) { - uppercaseOk = true; - } - if ('0123456789'.indexOf(generatedPassword[passwordLength]) !== -1) { - numbersOk = true; - } - if ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.indexOf(generatedPassword[passwordLength]) !== -1) { - symbolsOk = true; - } - } - assert.equal(6, generatedPassword.length); - assert(lowercaseOk && uppercaseOk && numbersOk && symbolsOk, 'there is no at least one char in every characters set'); - }); -}); \ No newline at end of file + assert.equal(20, LessPass._renderPassword(entropy, passwordProfile).length); + }); + it('include one char per set of characters', function() { + var password = LessPass._insertStringPseudoRandomly('123456', bigInt(7 * 6 + 2), 'uT'); + assert.equal('T12u3456', password); + }); + it('render password return at least one char in every characters set', function() { + var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; + var passwordProfile = { + length: 6, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + }; + var generatedPassword = LessPass._renderPassword(entropy, passwordProfile); + var passwordLength = generatedPassword.length; + var lowercaseOk = false; + var uppercaseOk = false; + var numbersOk = false; + var symbolsOk = false; + while (passwordLength--) { + if ('abcdefghijklmnopqrstuvwxyz'.indexOf(generatedPassword[passwordLength]) !== -1) { + lowercaseOk = true; + } + if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(generatedPassword[passwordLength]) !== -1) { + uppercaseOk = true; + } + if ('0123456789'.indexOf(generatedPassword[passwordLength]) !== -1) { + numbersOk = true; + } + if ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.indexOf(generatedPassword[passwordLength]) !== -1) { + symbolsOk = true; + } + } + assert.equal(6, generatedPassword.length); + assert(lowercaseOk && uppercaseOk && numbersOk && symbolsOk, 'there is no at least one char in every characters set'); + }); +}); diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js index ef96c5f..82134fa 100644 --- a/tests/v2/setOfCharacters.tests.js +++ b/tests/v2/setOfCharacters.tests.js @@ -1,59 +1,59 @@ var assert = chai.assert; -describe('LessPass v2', function () { - describe('set of characters', function () { - it('get default set of characters', function () { - var setOfCharacters = LessPass._getSetOfCharacters(); - assert.equal( - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', - setOfCharacters - ); - assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); - }); - it('get default set of characters concat rules in order', function () { - var setOfCharacters = LessPass._getSetOfCharacters(['lowercase', 'uppercase', 'numbers']); - assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); - assert.equal(26 * 2 + 10, setOfCharacters.length); - }); - it('get set of characters only lowercase', function () { - var setOfCharacters = LessPass._getSetOfCharacters(['lowercase']); - assert.equal('abcdefghijklmnopqrstuvwxyz', setOfCharacters); - assert.equal(26, setOfCharacters.length); - }); - it('get set of characters only uppercase', function () { - var setOfCharacters = LessPass._getSetOfCharacters(['uppercase']); - assert.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); - assert.equal(26, setOfCharacters.length); - }); - it('get set of characters only numbers', function () { - var setOfCharacters = LessPass._getSetOfCharacters(['numbers']); - assert.equal('0123456789', setOfCharacters); - assert.equal(10, setOfCharacters.length); - }); - it('get set of characters only symbols', function () { - var setOfCharacters = LessPass._getSetOfCharacters(['symbols']); - assert.equal('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', setOfCharacters); - assert.equal(32, setOfCharacters.length); - }); - it('generate one char per rules', function () { - var oneCharPerSetOfCharacters = LessPass._getOneCharPerRule( - bigInt(26 * 26), - ['lowercase', 'uppercase'] - ); - assert.equal('aA', oneCharPerSetOfCharacters.value); - assert.equal(2, oneCharPerSetOfCharacters.value.length); - assert.equal(1, oneCharPerSetOfCharacters.entropy); - }); - it('configured rules', function () { - assert.deepEqual(['uppercase'], LessPass._getConfiguredRules({uppercase: true})); - assert.deepEqual(['lowercase', 'uppercase'], LessPass._getConfiguredRules({uppercase: true, lowercase: true})); - assert.deepEqual(['lowercase'], LessPass._getConfiguredRules({lowercase: true, symbols: false})); - assert.deepEqual(['lowercase', 'uppercase', 'numbers', 'symbols'], LessPass._getConfiguredRules({ - lowercase: true, - uppercase: true, - symbols: true, - numbers: true - })); - }); +describe('LessPass v2', function() { + describe('set of characters', function() { + it('get default set of characters', function() { + var setOfCharacters = LessPass._getSetOfCharacters(); + assert.equal( + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', + setOfCharacters + ); + assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); }); + it('get default set of characters concat rules in order', function() { + var setOfCharacters = LessPass._getSetOfCharacters(['lowercase', 'uppercase', 'numbers']); + assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); + assert.equal(26 * 2 + 10, setOfCharacters.length); + }); + it('get set of characters only lowercase', function() { + var setOfCharacters = LessPass._getSetOfCharacters(['lowercase']); + assert.equal('abcdefghijklmnopqrstuvwxyz', setOfCharacters); + assert.equal(26, setOfCharacters.length); + }); + it('get set of characters only uppercase', function() { + var setOfCharacters = LessPass._getSetOfCharacters(['uppercase']); + assert.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); + assert.equal(26, setOfCharacters.length); + }); + it('get set of characters only numbers', function() { + var setOfCharacters = LessPass._getSetOfCharacters(['numbers']); + assert.equal('0123456789', setOfCharacters); + assert.equal(10, setOfCharacters.length); + }); + it('get set of characters only symbols', function() { + var setOfCharacters = LessPass._getSetOfCharacters(['symbols']); + assert.equal('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', setOfCharacters); + assert.equal(32, setOfCharacters.length); + }); + it('generate one char per rules', function() { + var oneCharPerSetOfCharacters = LessPass._getOneCharPerRule( + bigInt(26 * 26), + ['lowercase', 'uppercase'] + ); + assert.equal('aA', oneCharPerSetOfCharacters.value); + assert.equal(2, oneCharPerSetOfCharacters.value.length); + assert.equal(1, oneCharPerSetOfCharacters.entropy); + }); + it('configured rules', function() { + assert.deepEqual(['uppercase'], LessPass._getConfiguredRules({uppercase: true})); + assert.deepEqual(['lowercase', 'uppercase'], LessPass._getConfiguredRules({uppercase: true, lowercase: true})); + assert.deepEqual(['lowercase'], LessPass._getConfiguredRules({lowercase: true, symbols: false})); + assert.deepEqual(['lowercase', 'uppercase', 'numbers', 'symbols'], LessPass._getConfiguredRules({ + lowercase: true, + uppercase: true, + symbols: true, + numbers: true + })); + }); + }); }); diff --git a/webpack.config.js b/webpack.config.js index 2f35fc9..ca67413 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -4,22 +4,22 @@ var webpack = require('webpack'); var production = process.env.NODE_ENV === 'production' || false; module.exports = { - entry: './src/lesspass.js', - output: { - filename: production ? 'lesspass.min.js' : 'lesspass.js', - path: path.resolve(__dirname, 'dist'), - library: 'LessPass', - libraryTarget: 'umd' - }, - module: { - rules: [ - {test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"} - ] - }, - plugins: production ? [ - new webpack.optimize.UglifyJsPlugin({ - beautify: false, - comments: false - }) - ] : [] -}; \ No newline at end of file + entry: './src/lesspass.js', + output: { + filename: production ? 'lesspass.min.js' : 'lesspass.js', + path: path.resolve(__dirname, 'dist'), + library: 'LessPass', + libraryTarget: 'umd' + }, + module: { + rules: [ + {test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"} + ] + }, + plugins: production ? [ + new webpack.optimize.UglifyJsPlugin({ + beautify: false, + comments: false + }) + ] : [] +}; From e22cabda4f8d4ecc4104b70b530663e0812a59f4 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 14 Mar 2017 11:40:38 +0100 Subject: [PATCH 114/124] Use Firefox for travis tests --- .travis.yml | 4 +++- package.json | 11 ++++------- tests/karma.config.js | 5 +---- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 10d8531..173b32f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,5 @@ +dist: trusty +sudo: required language: node_js node_js: - - 6 \ No newline at end of file + - 6 diff --git a/package.json b/package.json index d07df27..9bae031 100644 --- a/package.json +++ b/package.json @@ -19,12 +19,12 @@ "scripts": { "precommit": "npm test", "prepush": "npm test", - "build": "rimraf dist && npm run build:debug && npm run build:min", - "build:debug": "webpack", + "dev": "webpack", + "build": "rimraf dist && npm run build:min", "build:min": "cross-env NODE_ENV=production webpack -p", - "prepublish": "npm test && npm run build && npm run test:umd && npm run test:browser", + "prepublish": "npm run build", "test": "mocha tests/*", - "test:umd": "npm run build && cd tests && node node.js && cd ..", + "test:node": "npm run build && cd tests && node node.js && cd ..", "test:browser": "npm run build && karma start tests/karma.config.js" }, "dependencies": { @@ -42,12 +42,9 @@ "husky": "^0.13.2", "karma": "^1.3.0", "karma-chai": "^0.1.0", - "karma-chrome-launcher": "^2.0.0", "karma-firefox-launcher": "^1.0.0", "karma-mocha": "^1.3.0", - "karma-phantomjs-launcher": "^1.0.2", "mocha": "^3.1.2", - "phantomjs": "^2.1.7", "rimraf": "^2.5.4", "webpack": "^2.2.1" } diff --git a/tests/karma.config.js b/tests/karma.config.js index 8cd0675..d64f908 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -18,12 +18,9 @@ module.exports = function(config) { colors: true, logLevel: config.LOG_INFO, autoWatch: true, - browsers: ['Chrome', 'Firefox'], + browsers: ['Firefox'], singleRun: true, concurrency: Infinity }; - if (process.env.TRAVIS) { - configuration.browsers = ['PhantomJS']; - } config.set(configuration) }; From 02794899e86cd1af470ed631018cf708eced0330 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Wed, 29 Mar 2017 09:46:42 +0200 Subject: [PATCH 115/124] variable "index" should be "counter" fix https://github.com/lesspass/lesspass/issues/178 --- src/lesspass.js | 2 +- tests/v2/api.tests.js | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/lesspass.js b/src/lesspass.js index 9d3c1da..86a377d 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -36,7 +36,7 @@ var defaultPasswordProfile = { keylen: 32, digest: 'sha256', length: 16, - index: 1, + counter: 1, iterations: 100000 }; diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js index d6e988d..e6ffcb1 100644 --- a/tests/v2/api.tests.js +++ b/tests/v2/api.tests.js @@ -74,6 +74,15 @@ describe('LessPass v2', function() { assert.equal("sB>{qF}wN%/-fm", generatedPassword); }); }); + it('render password with default options', function() { + this.timeout(10000); + var site = 'example.org'; + var login = 'contact@example.org'; + var masterPassword = 'password'; + return LessPass.generatePassword(site, login, masterPassword).then(function(generatedPassword) { + assert.equal('WHLpUL)e00[iHR+w', generatedPassword); + }); + }); }); }); From d4359d95b930d57ac3317923e7695515dcbd47d6 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Sat, 29 Apr 2017 10:34:30 +0200 Subject: [PATCH 116/124] refactor core to use browserify --- .travis.yml | 12 + dist/lesspass.js | 19364 ++++++++++++++++++------------- dist/lesspass.min.js | 4 - example/index.html | 53 + example/lesspass.html | 31 - package.json | 53 +- src/lesspass.js | 75 +- src/pbkdf2.js | 65 +- src/v1.js | 101 +- src/v2.js | 96 +- test/api.tests.js | 388 + test/karma.conf.js | 19 + test/pbkdf2.tests.js | 227 + test/v1/deriveEncryptedLogin.tests.js | 110 + test/v1/getPasswordTemplate.tests.js | 82 + test/v1/prettyPrint.js | 39 + test/v1/renderPassword.tests.js | 281 + test/v2/entropy.tests.js | 79 + test/v2/renderPassword.tests.js | 99 + test/v2/setOfCharacters.tests.js | 78 + tests/helper.js | 4 - tests/karma.config.js | 26 - tests/node.js | 23 - tests/pbkdf2.tests.js | 16 - tests/v1/api.tests.js | 545 - tests/v1/deriveEncryptedLogin.tests.js | 84 - tests/v1/getPasswordTemplate.tests.js | 63 - tests/v1/prettyPrint.js | 35 - tests/v2/api.tests.js | 88 - tests/v2/entropy.tests.js | 58 - tests/v2/renderPassword.tests.js | 70 - tests/v2/setOfCharacters.tests.js | 59 - webpack.config.js | 25 - 33 files changed, 12776 insertions(+), 9576 deletions(-) delete mode 100644 dist/lesspass.min.js create mode 100644 example/index.html delete mode 100644 example/lesspass.html create mode 100644 test/api.tests.js create mode 100644 test/karma.conf.js create mode 100644 test/pbkdf2.tests.js create mode 100644 test/v1/deriveEncryptedLogin.tests.js create mode 100644 test/v1/getPasswordTemplate.tests.js create mode 100644 test/v1/prettyPrint.js create mode 100644 test/v1/renderPassword.tests.js create mode 100644 test/v2/entropy.tests.js create mode 100644 test/v2/renderPassword.tests.js create mode 100644 test/v2/setOfCharacters.tests.js delete mode 100644 tests/helper.js delete mode 100644 tests/karma.config.js delete mode 100644 tests/node.js delete mode 100644 tests/pbkdf2.tests.js delete mode 100644 tests/v1/api.tests.js delete mode 100644 tests/v1/deriveEncryptedLogin.tests.js delete mode 100644 tests/v1/getPasswordTemplate.tests.js delete mode 100644 tests/v1/prettyPrint.js delete mode 100644 tests/v2/api.tests.js delete mode 100644 tests/v2/entropy.tests.js delete mode 100644 tests/v2/renderPassword.tests.js delete mode 100644 tests/v2/setOfCharacters.tests.js delete mode 100644 webpack.config.js diff --git a/.travis.yml b/.travis.yml index 173b32f..41f7647 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,3 +3,15 @@ sudo: required language: node_js node_js: - 6 +addons: + firefox: "latest" + apt: + sources: + - google-chrome + packages: + - google-chrome-stable +before_script: + - export CHROME_BIN=/usr/bin/google-chrome + - "export DISPLAY=:99.0" + - "sh -e /etc/init.d/xvfb start" + - sleep 3 diff --git a/dist/lesspass.js b/dist/lesspass.js index 2c0c862..5c835f8 100644 --- a/dist/lesspass.js +++ b/dist/lesspass.js @@ -1,8186 +1,9461 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["LessPass"] = factory(); - else - root["LessPass"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.l = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // identity function for calling harmony imports with the correct context -/******/ __webpack_require__.i = function(value) { return value; }; - -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); -/******/ } -/******/ }; - -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; - -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 52); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ +(function(f) { + if (typeof exports === "object" && typeof module !== "undefined") { + module.exports = f(); + } else if (typeof define === "function" && define.amd) { + define([], f); + } else { + var g; + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } else { + g = this; + } + g.LessPass = f(); + } +})(function() { + var define, module, exports; + return (function e(t, n, r) { + function s(o, u) { + if (!n[o]) { + if (!t[o]) { + var a = typeof require == "function" && require; + if (!u && a) return a(o, !0); + if (i) return i(o, !0); + var f = new Error("Cannot find module '" + o + "'"); + throw ((f.code = "MODULE_NOT_FOUND"), f); + } + var l = (n[o] = { exports: {} }); + t[o][0].call( + l.exports, + function(e) { + var n = t[o][1][e]; + return s(n ? n : e); + }, + l, + l.exports, + e, + t, + n, + r + ); + } + return n[o].exports; + } + var i = typeof require == "function" && require; + for (var o = 0; o < r.length; o++) s(r[o]); + return s; + })( + { + 1: [ + function(require, module, exports) { + "use strict"; + exports.byteLength = byteLength; + exports.toByteArray = toByteArray; + exports.fromByteArray = fromByteArray; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + + var code = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function placeHoldersCount(b64) { + var len = b64.length; + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } -var base64 = __webpack_require__(26) -var ieee754 = __webpack_require__(32) -var isArray = __webpack_require__(16) + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0; + } -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 + function byteLength(b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64); + } -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. + function toByteArray(b64) { + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + placeHolders = placeHoldersCount(b64); - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() + arr = new Arr(len * 3 / 4 - placeHolders); -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} + var L = 0; -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } + for ((i = 0), (j = 0); i < l; (i += 4), (j += 3)) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xff; + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } - return that -} + if (placeHolders === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xff; + } else if (placeHolders === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ + return arr; + } -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } + function tripletToBase64(num) { + return ( + lookup[(num >> 18) & 0x3f] + + lookup[(num >> 12) & 0x3f] + + lookup[(num >> 6) & 0x3f] + + lookup[num & 0x3f] + ); + } - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } -Buffer.poolSize = 8192 // not used by this implementation + function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ""; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for ( + var i = 0, len2 = len - extraBytes; + i < len2; + i += maxChunkLength + ) { + parts.push( + encodeChunk( + uint8, + i, + i + maxChunkLength > len2 ? len2 : i + maxChunkLength + ) + ); + } -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3f]; + output += "=="; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3f]; + output += lookup[(tmp << 2) & 0x3f]; + output += "="; + } -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } + parts.push(output); - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } + return parts.join(""); + } + }, + {} + ], + 2: [ + function(require, module, exports) { + var bigInt = (function(undefined) { + "use strict"; + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + LOG_MAX_INT = Math.log(MAX_INT); + + function Integer(v, radix) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") + return +radix === 10 ? parseValue(v) : parseBase(v, radix); + return parseValue(v); + } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); - return fromObject(that, value) -} + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} + function smallToArray(n) { + // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) return [n]; + if (n < 1e14) return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} + function arrayToSmall(arr) { + // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: + return 0; + case 1: + return arr[0]; + case 2: + return arr[0] + arr[1] * BASE; + default: + return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} - -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that -} + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} + function createArray(length) { + // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } + function add(a, b) { + // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, + i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } - var actual = that.write(string, encoding) + function addSmall(a, carry) { + // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, r = new Array(l), base = BASE, sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } + BigInteger.prototype.add = function(v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function(v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + function subtract(a, b) { + // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, + difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } - return that -} + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} + function subtractSmall(a, b, sign) { + // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, + difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } + return new BigInteger(r, sign); + } -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer + BigInteger.prototype.subtract = function(v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function(v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } + BigInteger.prototype.negate = function() { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function() { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } + BigInteger.prototype.abs = function() { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function() { + return new SmallInteger(Math.abs(this.value)); + }; - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, + carry, + i, + a_i, + b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} + function multiplySmall(a, b) { + // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, + i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) + r.push(0); + return r.concat(x); + } - if (that.length === 0) { - return that - } + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); - obj.copy(that, 0, 0, len) - return that - } + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} + var product = addAny( + addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), + shiftLeft(bd, 2 * n) + ); + trim(product); + return product; + } -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} + BigInteger.prototype.multiply = function(v) { + var n = parseValue(v), + a = this.value, + b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if ( + useKaratsuba(a.length, b.length) // Karatsuba is only faster for certain array sizes + ) + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} + BigInteger.prototype.times = BigInteger.prototype.multiply; -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + function multiplySmallAndArray(a, b, sign) { + // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function(a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray( + Math.abs(a.value), + smallToArray(Math.abs(this.value)), + this.sign !== a.sign + ); + }; + BigInteger.prototype._multiplyBySmall = function(a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray( + Math.abs(a.value), + this.value, + this.sign !== a.sign + ); + }; + SmallInteger.prototype.multiply = function(v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + function square(a) { + var l = a.length, + r = createArray(l + l), + base = BASE, + product, + carry, + i, + a_i, + a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + for (var j = 0; j < l; j++) { + a_j = a[j]; + product = a_i * a_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } - if (a === b) return 0 + BigInteger.prototype.square = function() { + return new BigInteger(square(this.value), false); + }; - var x = a.length - var y = b.length + SmallInteger.prototype.square = function() { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger( + square(smallToArray(Math.abs(this.value))), + false + ); + }; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } + function divMod1(a, b) { + // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, + shift, + carry, + borrow, + i, + l, + q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor( + (remainder[shift + b_l] * base + + remainder[shift + b_l - 1]) / + divisorMostSignificantDigit + ); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} + function divMod2(a, b) { + // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, + xlen, + highx, + highy, + check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, + q, + remainder, + divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } - if (list.length === 0) { - return Buffer.alloc(0) - } + function divModAny(self, v) { + var value, n = parseValue(v); + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [ + new SmallInteger(truncate(a / b)), + new SmallInteger(a % b) + ]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [ + new SmallInteger(quotient), + new SmallInteger(remainder) + ]; + } + return [ + new BigInteger(quotient, self.sign !== n.sign), + new SmallInteger(remainder) + ]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) + return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } + BigInteger.prototype.divmod = function(v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + SmallInteger.prototype.divmod = BigInteger.prototype.divmod; - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} + BigInteger.prototype.divide = function(v) { + return divModAny(this, v)[0]; + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = + BigInteger.prototype.divide; -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } + BigInteger.prototype.mod = function(v) { + return divModAny(this, v)[1]; + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = + BigInteger.prototype.mod; + + BigInteger.prototype.pow = function(v) { + var n = parseValue(v), a = this.value, b = n.value, value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) + throw new Error( + "The exponent " + n.toString() + " is too large." + ); + if (this.isSmall) { + if (isPrecise((value = Math.pow(a, b)))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & (1 === 1)) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + BigInteger.prototype.modPow = function(exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) + throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], base = this.mod(mod); + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength + BigInteger.prototype.compareAbs = function(v) { + var n = parseValue(v), a = this.value, b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function(v) { + var n = parseValue(v), a = Math.abs(this.value), b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; -function slowToString (encoding, start, end) { - var loweredCase = false + BigInteger.prototype.compare = function(v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), a = this.value, b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function(v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), a = this.value, b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + BigInteger.prototype.equals = function(v) { + return this.compare(v) === 0; + }; + SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = + BigInteger.prototype.equals; - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } + BigInteger.prototype.notEquals = function(v) { + return this.compare(v) !== 0; + }; + SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = + BigInteger.prototype.notEquals; - if (end === undefined || end > this.length) { - end = this.length - } + BigInteger.prototype.greater = function(v) { + return this.compare(v) > 0; + }; + SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = + BigInteger.prototype.greater; - if (end <= 0) { - return '' - } + BigInteger.prototype.lesser = function(v) { + return this.compare(v) < 0; + }; + SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = + BigInteger.prototype.lesser; - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 + BigInteger.prototype.greaterOrEquals = function(v) { + return this.compare(v) >= 0; + }; + SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = + BigInteger.prototype.greaterOrEquals; - if (end <= start) { - return '' - } + BigInteger.prototype.lesserOrEquals = function(v) { + return this.compare(v) <= 0; + }; + SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = + BigInteger.prototype.lesserOrEquals; - if (!encoding) encoding = 'utf8' + BigInteger.prototype.isEven = function() { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function() { + return (this.value & 1) === 0; + }; - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) + BigInteger.prototype.isOdd = function() { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function() { + return (this.value & 1) === 1; + }; - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + BigInteger.prototype.isPositive = function() { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function() { + return this.value > 0; + }; - case 'ascii': - return asciiSlice(this, start, end) + BigInteger.prototype.isNegative = function() { + return this.sign; + }; + SmallInteger.prototype.isNegative = function() { + return this.value < 0; + }; - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + BigInteger.prototype.isUnit = function() { + return false; + }; + SmallInteger.prototype.isUnit = function() { + return Math.abs(this.value) === 1; + }; - case 'base64': - return base64Slice(this, start, end) + BigInteger.prototype.isZero = function() { + return false; + }; + SmallInteger.prototype.isZero = function() { + return this.value === 0; + }; + BigInteger.prototype.isDivisibleBy = function(v) { + var n = parseValue(v); + var value = n.value; + if (value === 0) return false; + if (value === 1) return true; + if (value === 2) return this.isEven(); + return this.mod(n).equals(Integer[0]); + }; + SmallInteger.prototype.isDivisibleBy = + BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) + return false; + if (n.lesser(25)) return true; + // we don't know if it's prime: let the other functions figure it out + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) + BigInteger.prototype.isPrime = function() { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(), nPrev = n.prev(); + var a = [2, 3, 5, 7, 11, 13, 17, 19], b = nPrev, d, t, i, x; + while (b.isEven()) + b = b.divide(2); + for (i = 0; i < a.length; i++) { + x = bigInt(a[i]).modPow(b, n); + if (x.equals(Integer[1]) || x.equals(nPrev)) continue; + for ( + (t = true), (d = b); + t && d.lesser(nPrev); + d = d.multiply(2) + ) { + x = x.square().mod(n); + if (x.equals(nPrev)) t = false; + } + if (t) return false; + } + return true; + }; + SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function(iterations) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + // use the Fermat primality test + for (var i = 0; i < t; i++) { + var a = bigInt.randBetween(2, n.minus(2)); + if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite + } + return true; // large chance of being prime + }; + SmallInteger.prototype.isProbablePrime = + BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function(n) { + var t = bigInt.zero, + newT = bigInt.one, + r = parseValue(n), + newR = this.abs(), + q, + lastT, + lastR; + while (!newR.equals(bigInt.zero)) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.equals(1)) + throw new Error( + this.toString() + " and " + n.toString() + " are not co-prime" + ); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} + SmallInteger.prototype.modInv = BigInteger.prototype.modInv; -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} + BigInteger.prototype.next = function() { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function() { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} + BigInteger.prototype.prev = function() { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function() { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + var powersOfTwo = [1]; + while (powersOfTwo[powersOfTwo.length - 1] <= BASE) + powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, + highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return ( + ((typeof n === "number" || typeof n === "string") && + +Math.abs(n) <= BASE) || + (n instanceof BigInteger && n.value.length <= 1) + ); + } - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } + BigInteger.prototype.shiftLeft = function(n) { + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftRight(-n); + var result = this; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function(n) { + var remQuo; + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero()) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, yRem = ySign ? y.not() : y; + var xBits = [], yBits = []; + var xStop = false, yStop = false; + while (!xStop || !yStop) { + if (xRem.isZero()) { + // virtual sign extension for simulating two's complement + xStop = true; + xBits.push(xSign ? 1 : 0); + } else if (xSign) + xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers + else xBits.push(xRem.isEven() ? 0 : 1); + + if (yRem.isZero()) { + yStop = true; + yBits.push(ySign ? 1 : 0); + } else if (ySign) yBits.push(yRem.isEven() ? 1 : 0); + else yBits.push(yRem.isEven() ? 0 : 1); + + xRem = xRem.over(2); + yRem = yRem.over(2); + } + var result = []; + for (var i = 0; i < xBits.length; i++) + result.push(fn(xBits[i], yBits[i])); + var sum = bigInt(result.pop()) + .negate() + .times(bigInt(2).pow(result.length)); + while (result.length) { + sum = sum.add( + bigInt(result.pop()).times(bigInt(2).pow(result.length)) + ); + } + return sum; + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + BigInteger.prototype.not = function() { + return this.negate().prev(); + }; + SmallInteger.prototype.not = BigInteger.prototype.not; - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } + BigInteger.prototype.and = function(n) { + return bitwise(this, n, function(a, b) { + return a & b; + }); + }; + SmallInteger.prototype.and = BigInteger.prototype.and; - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 + BigInteger.prototype.or = function(n) { + return bitwise(this, n, function(a, b) { + return a | b; + }); + }; + SmallInteger.prototype.or = BigInteger.prototype.or; - if (this === target) return 0 + BigInteger.prototype.xor = function(n) { + return bitwise(this, n, function(a, b) { + return a ^ b; + }); + }; + SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, + LOBMASK_BI = ((BASE & -BASE) * (BASE & -BASE)) | LOBMASK_I; + function roughLOB(n) { + // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" + ? v | LOBMASK_I + : (v[0] + v[1] * BASE) | LOBMASK_BI; + return x & -x; + } - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = Math.min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; + b = a; + a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b) { + a = parseValue(a); + b = parseValue(b); + var low = min(a, b), high = max(a, b); + var range = high.subtract(low); + if (range.isSmall) + return low.add(Math.round(Math.random() * range)); + var length = range.value.length - 1; + var result = [], restricted = true; + for (var i = length; i >= 0; i--) { + var top = restricted ? range.value[i] : BASE; + var digit = truncate(Math.random() * top); + result.unshift(digit); + if (digit < top) restricted = false; + } + result = arrayToSmall(result); + return low.add( + typeof result === "number" + ? new SmallInteger(result) + : new BigInteger(result, false) + ); + } + var parseBase = function(text, base) { + var length = text.length; + if (2 <= base && base <= 36) { + if (length <= LOG_MAX_INT / Math.log(base)) { + return new SmallInteger(parseInt(text, base)); + } + } + base = parseValue(base); + var digits = []; + var i; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i].toLowerCase(), charCode = c.charCodeAt(0); + if (48 <= charCode && charCode <= 57) + digits.push(parseValue(c)); + else if (97 <= charCode && charCode <= 122) + digits.push(parseValue(c.charCodeAt(0) - 87)); + else if (c === "<") { + var start = i; + do { + i++; + } while (text[i] !== ">"); + digits.push(parseValue(text.slice(start + 1, i))); + } else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } + function stringify(digit) { + var v = digit.value; + if (typeof v === "number") v = [v]; + if (v.length === 1 && v[0] <= 35) { + return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]); + } + return "<" + v + ">"; + } + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return "0"; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return "0"; + if (n.isNegative()) return new Array(1 - n).join("10"); + return "1" + new Array(+n).join("01"); + } + var minusSign = ""; + if (n.isNegative() && base.isPositive()) { + minusSign = "-"; + n = n.abs(); + } + if (base.equals(1)) { + if (n.isZero()) return "0"; + return minusSign + new Array(+n + 1).join(1); + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(stringify(digit)); + } + out.push(stringify(left)); + return minusSign + out.reverse().join(""); + } - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } + BigInteger.prototype.toString = function(radix) { + if (radix === undefined) radix = 10; + if (radix !== 10) return toBase(this, radix); + var v = this.value, + l = v.length, + str = String(v[--l]), + zeros = "0000000", + digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + SmallInteger.prototype.toString = function(radix) { + if (radix === undefined) radix = 10; + if (radix != 10) return toBase(this, radix); + return String(this.value); + }; - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } + BigInteger.prototype.valueOf = function() { + return +this.toString(); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } + SmallInteger.prototype.valueOf = function() { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) return new SmallInteger(x); + throw "Invalid integer: " + v; + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) + throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) + throw new Error( + "Invalid integer: " + exp + " is not a valid exponent." + ); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = + text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) + throw new Error( + "Cannot include negative exponent part for integers" + ); + text += new Array(exp + 1).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } - throw new TypeError('val must be string, number or Buffer') -} + function parseNumberValue(v) { + if (isPrecise(v)) { + if (v !== truncate(v)) + throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = new SmallInteger(i); + if (i > 0) Integer[-i] = new SmallInteger(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function(x) { + return x instanceof BigInteger || x instanceof SmallInteger; + }; + Integer.randBetween = randBetween; + + Integer.fromArray = function(digits, base, isNegative) { + return parseBaseFromArray( + digits.map(parseValue), + parseValue(base || 10), + isNegative + ); + }; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } + return Integer; + })(); - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + // Node.js check + if ( + typeof module !== "undefined" && + module.hasOwnProperty("exports") + ) { + module.exports = bigInt; + } - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } + //amd check + if (typeof define === "function" && define.amd) { + define("big-integer", [], function() { + return bigInt; + }); + } + }, + {} + ], + 3: [function(require, module, exports) {}, {}], + 4: [ + function(require, module, exports) { + (function(global) { + "use strict"; + var buffer = require("buffer"); + var Buffer = buffer.Buffer; + var SlowBuffer = buffer.SlowBuffer; + var MAX_LEN = buffer.kMaxLength || 2147483647; + exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === "function") { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === "number") { + throw new TypeError("encoding must not be number"); + } + if (typeof size !== "number") { + throw new TypeError("size must be a number"); + } + if (size > MAX_LEN) { + throw new RangeError("size is too large"); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === "string") { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; + }; + exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === "function") { + return Buffer.allocUnsafe(size); + } + if (typeof size !== "number") { + throw new TypeError("size must be a number"); + } + if (size > MAX_LEN) { + throw new RangeError("size is too large"); + } + return new Buffer(size); + }; + exports.from = function from(value, encodingOrOffset, length) { + if ( + typeof Buffer.from === "function" && + (!global.Uint8Array || Uint8Array.from !== Buffer.from) + ) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === "string") { + return new Buffer(value, encodingOrOffset); + } + if ( + typeof ArrayBuffer !== "undefined" && + value instanceof ArrayBuffer + ) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === "undefined") { + offset = 0; + } + var len = length; + if (typeof len === "undefined") { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError("'offset' is out of bounds"); + } + if (len > value.byteLength - offset) { + throw new RangeError("'length' is out of bounds"); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if ( + Array.isArray(value) || + (typeof ArrayBuffer !== "undefined" && + value.buffer instanceof ArrayBuffer) || + "length" in value + ) { + return new Buffer(value); + } + if (value.type === "Buffer" && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } - return -1 -} + throw new TypeError( + "First argument must be a string, Buffer, " + + "ArrayBuffer, Array, or array-like object." + ); + }; + exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === "function") { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== "number") { + throw new TypeError("size must be a number"); + } + if (size >= MAX_LEN) { + throw new RangeError("size is too large"); + } + return new SlowBuffer(size); + }; + }.call( + this, + typeof global !== "undefined" + ? global + : typeof self !== "undefined" + ? self + : typeof window !== "undefined" ? window : {} + )); + }, + { buffer: 5 } + ], + 5: [ + function(require, module, exports) { + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + "use strict"; + var base64 = require("base64-js"); + var ieee754 = require("ieee754"); + + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + + if ( + !Buffer.TYPED_ARRAY_SUPPORT && + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "This browser lacks typed array (Uint8Array) support which is required by " + + "`buffer` v5.x. Use `buffer` v4.x if you require old browser support." + ); + } + + function typedArraySupport() { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + arr.__proto__ = { + __proto__: Uint8Array.prototype, + foo: function() { + return 42; + } + }; + return arr.foo() === 42; + } catch (e) { + return false; + } + } + + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError("Invalid typed array length"); + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length); + buf.__proto__ = Buffer.prototype; + return buf; + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer(arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new Error( + "If encoding is specified then the first argument must be a string" + ); + } + return allocUnsafe(arg); + } + return from(arg, encodingOrOffset, length); + } + + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + if ( + typeof Symbol !== "undefined" && + Symbol.species && + Buffer[Symbol.species] === Buffer + ) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }); + } + + Buffer.poolSize = 8192; // not used by this implementation + + function from(value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } + + if (value instanceof ArrayBuffer) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + + if (typeof value === "string") { + return fromString(value, encodingOrOffset); + } + + return fromObject(value); + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function(value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; + + // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be a number'); + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative'); + } + } -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === "string" + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill); + } + return createBuffer(size); + } -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function(size) { + return allocUnsafe(size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function(size) { + return allocUnsafe(size); + }; - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + function fromString(string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + var actual = buf.write(string, encoding); - if (!encoding) encoding = 'utf8' + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + return buf; + } - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + function fromArrayLike(array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; + } - case 'ascii': - return asciiWrite(this, string, offset, length) + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds"); + } - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds"); + } - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + var buf; + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype; + return buf; + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} + function fromObject(obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} + if (buf.length === 0) { + return buf; + } -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint + obj.copy(buf, 0, 0, len); + return buf; } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - res.push(codePoint) - i += bytesPerSequence - } + if (obj) { + if (isArrayBufferView(obj) || "length" in obj) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } - return decodeCodePointsArray(res) -} + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 + throw new TypeError( + "First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object." + ); + } -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } + function checked(length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError( + "Attempt to allocate Buffer larger than maximum " + + "size: 0x" + + K_MAX_LENGTH.toString(16) + + " bytes" + ); + } + return length | 0; + } - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} + function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length); + } -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) + Buffer.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true; + }; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} + Buffer.compare = function compare(a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError("Arguments must be Buffers"); + } -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) + if (a === b) return 0; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} + var x = a.length; + var y = b.length; -function hexSlice (buf, start, end) { - var len = buf.length + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } + Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError( + '"list" argument must be an Array of Buffers' + ); + } - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } + if (list.length === 0) { + return Buffer.alloc(0); + } - if (end < start) end = start + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!Buffer.isBuffer(buf)) { + throw new TypeError( + '"list" argument must be an Array of Buffers' + ); + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer; + }; - return newBuf -} + function byteLength(string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length; + } + if (isArrayBufferView(string) || string instanceof ArrayBuffer) { + return string.byteLength; + } + if (typeof string !== "string") { + string = "" + string; + } -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } + var len = string.length; + if (len === 0) return 0; + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + case undefined: + return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) return utf8ToBytes(string).length; // assume utf8 + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; - return val -} + function slowToString(encoding, start, end) { + var loweredCase = false; -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return ""; + } - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 + if (end === undefined || end > this.length) { + end = this.length; + } - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + if (end <= 0) { + return ""; + } - return val -} + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + if (end <= start) { + return ""; + } - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + if (!encoding) encoding = "utf8"; - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); - return offset + byteLength -} + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + case "ascii": + return asciiSlice(this, start, end); - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } + case "latin1": + case "binary": + return latin1Slice(this, start, end); - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} + case "base64": + return base64Slice(this, start, end); -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } + // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + Buffer.prototype._isBuffer = true; + + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; - return offset + byteLength -} + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + + Buffer.prototype.toString = function toString() { + var length = this.length; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + + Buffer.prototype.equals = function equals(b) { + if (!Buffer.isBuffer(b)) + throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + + Buffer.prototype.inspect = function inspect() { + var str = ""; + var max = exports.INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString("hex", 0, max).match(/.{2}/g).join(" "); + if (this.length > max) str += " ... "; + } + return ""; + }; + + Buffer.prototype.compare = function compare( + target, + start, + end, + thisStart, + thisEnd + ) { + if (!Buffer.isBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); + } - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + if ( + start < 0 || + end > target.length || + thisStart < 0 || + thisEnd > this.length + ) { + throw new RangeError("out of range index"); + } - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} + if (this === target) return 0; -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf( + buffer, + val, + byteOffset, + encoding, + dir + ) { + // Empty buffer means no match + if (buffer.length === 0) return -1; + + // Normalize byteOffset + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } - var len = end - start - var i + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1; + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } + // Normalize val + if (typeof val === "string") { + val = Buffer.from(val, encoding); + } - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 0xff; // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call( + buffer, + val, + byteOffset + ); + } else { + return Uint8Array.prototype.lastIndexOf.call( + buffer, + val, + byteOffset + ); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } + throw new TypeError("val must be string, number or Buffer"); + } - if (end <= start) { - return this - } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if ( + encoding === "ucs2" || + encoding === "ucs-2" || + encoding === "utf16le" || + encoding === "utf-16le" + ) { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } - if (!val) val = 0 + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if ( + read(arr, i) === + read(val, foundIndex === -1 ? 0 : i - foundIndex) + ) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) + return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } + return -1; + } - return this -} + Buffer.prototype.includes = function includes( + val, + byteOffset, + encoding + ) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + + Buffer.prototype.indexOf = function indexOf( + val, + byteOffset, + encoding + ) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf( + val, + byteOffset, + encoding + ) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } -// HELPER FUNCTIONS -// ================ + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError("Invalid hex string"); -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; + } -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } + function utf8Write(buf, string, offset, length) { + return blitBuffer( + utf8ToBytes(string, buf.length - offset), + buf, + offset, + length + ); + } - // valid lead - leadSurrogate = codePoint + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } - continue - } + function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); + } - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } + function ucs2Write(buf, string, offset, length) { + return blitBuffer( + utf16leToBytes(string, buf.length - offset), + buf, + offset, + length + ); + } - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } + Buffer.prototype.write = function write( + string, + offset, + length, + encoding + ) { + // Buffer#write(string) + if (offset === undefined) { + encoding = "utf8"; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = "utf8"; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } - return bytes -} + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } + if ( + (string.length > 0 && (length < 0 || offset < 0)) || + offset > this.length + ) { + throw new RangeError("Attempt to write outside buffer bounds"); + } - return byteArray -} + if (!encoding) encoding = "utf8"; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); + + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); + + case "ascii": + return asciiWrite(this, string, offset, length); + + case "latin1": + case "binary": + return latin1Write(this, string, offset, length); + + case "base64": + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} + Buffer.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) - -/***/ }), -/* 1 */ -/***/ (function(module, exports) { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xef + ? 4 + : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xc0) === 0x80) { + tempCodePoint = + ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f); + if (tempCodePoint > 0x7f) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ( + (secondByte & 0xc0) === 0x80 && + (thirdByte & 0xc0) === 0x80 + ) { + tempCodePoint = + ((firstByte & 0xf) << 0xc) | + ((secondByte & 0x3f) << 0x6) | + (thirdByte & 0x3f); + if ( + tempCodePoint > 0x7ff && + (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff) + ) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ( + (secondByte & 0xc0) === 0x80 && + (thirdByte & 0xc0) === 0x80 && + (fourthByte & 0xc0) === 0x80 + ) { + tempCodePoint = + ((firstByte & 0xf) << 0x12) | + ((secondByte & 0x3f) << 0xc) | + ((thirdByte & 0x3f) << 0x6) | + (fourthByte & 0x3f); + if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xfffd; + bytesPerSequence = 1; + } else if (codePoint > 0xffff) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + + res.push(codePoint); + i += bytesPerSequence; + } -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { + return decodeCodePointsArray(res); + } -"use strict"; -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } + // Decode in chunks to avoid "call stack size exceeded". + var res = ""; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH)) + ); + } + return res; + } -/**/ + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f); + } + return ret; + } -module.exports = Duplex; + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); -/**/ -var processNextTick = __webpack_require__(11); -/**/ + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } -/**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(1); -/**/ + function hexSlice(buf, start, end) { + var len = buf.length; -var Readable = __webpack_require__(20); -var Writable = __webpack_require__(13); + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; -util.inherits(Duplex, Readable); + var out = ""; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out; + } -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; -} + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ""; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - Readable.call(this, options); - Writable.call(this, options); + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } - if (options && options.readable === false) this.readable = false; + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } - if (options && options.writable === false) this.writable = false; + if (end < start) end = start; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype; + return newBuf; + }; - this.once('end', onend); -} + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError("offset is not uint"); + if (offset + ext > length) + throw new RangeError("Trying to access beyond buffer length"); + } -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + Buffer.prototype.readUIntLE = function readUIntLE( + offset, + byteLength, + noAssert + ) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); -} + return val; + }; + + Buffer.prototype.readUIntBE = function readUIntBE( + offset, + byteLength, + noAssert + ) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } -function onEndNT(self) { - self.end(); -} + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } + return val; + }; + + Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8); + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1]; + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return ( + (this[offset] | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + this[offset + 3] * 0x1000000 + ); + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return ( + this[offset] * 0x1000000 + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + ); + }; + + Buffer.prototype.readIntLE = function readIntLE( + offset, + byteLength, + noAssert + ) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val; + }; + + Buffer.prototype.readIntBE = function readIntBE( + offset, + byteLength, + noAssert + ) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val; + }; + + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; + }; + + Buffer.prototype.readInt16LE = function readInt16LE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; + }; + + Buffer.prototype.readInt16BE = function readInt16BE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; + }; + + Buffer.prototype.readInt32LE = function readInt32LE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return ( + this[offset] | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + ); + }; + + Buffer.prototype.readInt32BE = function readInt32BE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return ( + (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3] + ); + }; + + Buffer.prototype.readFloatLE = function readFloatLE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + + Buffer.prototype.readFloatBE = function readFloatBE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE( + offset, + noAssert + ) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) + throw new TypeError( + '"buffer" argument must be a Buffer instance' + ); + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + } + Buffer.prototype.writeUIntLE = function writeUIntLE( + value, + offset, + byteLength, + noAssert + ) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + var mul = 1; + var i = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } + return offset + byteLength; + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE( + value, + offset, + byteLength, + noAssert + ) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + return offset + byteLength; + }; + + Buffer.prototype.writeUInt8 = function writeUInt8( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeUInt16LE = function writeUInt16LE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeUInt32LE = function writeUInt32LE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + Buffer.prototype.writeIntLE = function writeIntLE( + value, + offset, + byteLength, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + return offset + byteLength; + }; + + Buffer.prototype.writeIntBE = function writeIntBE( + value, + offset, + byteLength, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {// prototype class for hash functions -function Hash (blockSize, finalSize) { - this._block = new Buffer(blockSize) - this._finalSize = finalSize - this._blockSize = blockSize - this._len = 0 - this._s = 0 -} - -Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8' - data = new Buffer(data, enc) - } - var l = this._len += data.length - var s = this._s || 0 - var f = 0 - var buffer = this._block + return offset + byteLength; + }; + + Buffer.prototype.writeInt8 = function writeInt8( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + return offset + 2; + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE( + value, + offset, + noAssert + ) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + return offset + 4; + }; + + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + if (offset < 0) throw new RangeError("Index out of range"); + } - while (s < l) { - var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) - var ch = (t - f) + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754( + buf, + value, + offset, + 4, + 3.4028234663852886e38, + -3.4028234663852886e38 + ); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } - for (var i = 0; i < ch; i++) { - buffer[(s % this._blockSize) + i] = data[i + f] - } + Buffer.prototype.writeFloatLE = function writeFloatLE( + value, + offset, + noAssert + ) { + return writeFloat(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE( + value, + offset, + noAssert + ) { + return writeFloat(this, value, offset, false, noAssert); + }; + + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754( + buf, + value, + offset, + 8, + 1.7976931348623157e308, + -1.7976931348623157e308 + ); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } - s += ch - f += ch + Buffer.prototype.writeDoubleLE = function writeDoubleLE( + value, + offset, + noAssert + ) { + return writeDouble(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE( + value, + offset, + noAssert + ) { + return writeDouble(this, value, offset, false, noAssert); + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy( + target, + targetStart, + start, + end + ) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) + throw new RangeError("sourceStart out of bounds"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - if ((s % this._blockSize) === 0) { - this._update(buffer) - } - } - this._s = s + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } - return this -} + return len; + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if ( + typeof encoding === "string" && + !Buffer.isEncoding(encoding) + ) { + throw new TypeError("Unknown encoding: " + encoding); + } + } else if (typeof val === "number") { + val = val & 255; + } -Hash.prototype.digest = function (enc) { - // Suppose the length of the message M, in bits, is l - var l = this._len * 8 + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } - // Append the bit 1 to the end of the message - this._block[this._len % this._blockSize] = 0x80 + if (end <= start) { + return this; + } - // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize - this._block.fill(0, this._len % this._blockSize + 1) + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - if (l % (this._blockSize * 8) >= this._finalSize * 8) { - this._update(this._block) - this._block.fill(0) - } + if (!val) val = 0; - // to this append the block which is equal to the number l written in binary - // TODO: handle case where l is > Math.pow(2, 29) - this._block.writeInt32BE(l, this._blockSize - 4) - - var hash = this._update(this._block) || this._hash() - - return enc ? hash.toString(enc) : hash -} - -Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') -} - -module.exports = Hash - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Stream; - -var EE = __webpack_require__(8).EventEmitter; -var inherits = __webpack_require__(1); - -inherits(Stream, EE); -Stream.Readable = __webpack_require__(39); -Stream.Writable = __webpack_require__(41); -Stream.Duplex = __webpack_require__(36); -Stream.Transform = __webpack_require__(40); -Stream.PassThrough = __webpack_require__(38); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } + var i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } - source.on('data', ondata); + return this; + }; - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } + // HELPER FUNCTIONS + // ================ - dest.on('drain', ondrain); + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } + function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, ""); + // Node converts strings with length < 2 to '' + if (str.length < 2) return ""; + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + function toHex(n) { + if (n < 16) return "0" + n.toString(16); + return n.toString(16); + } - dest.end(); - } + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xd7ff && codePoint < 0xe000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xdbff) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } + + // valid lead + leadSurrogate = codePoint; + + continue; + } + // 2 leads in a row + if (codePoint < 0xdc00) { + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + leadSurrogate = codePoint; + continue; + } - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + // valid surrogate pair + codePoint = + (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push( + (codePoint >> 0x6) | 0xc0, + (codePoint & 0x3f) | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push( + (codePoint >> 0xc) | 0xe0, + ((codePoint >> 0x6) & 0x3f) | 0x80, + (codePoint & 0x3f) | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push( + (codePoint >> 0x12) | 0xf0, + ((codePoint >> 0xc) & 0x3f) | 0x80, + ((codePoint >> 0x6) & 0x3f) | 0x80, + (codePoint & 0x3f) | 0x80 + ); + } else { + throw new Error("Invalid code point"); + } + } - if (typeof dest.destroy === 'function') dest.destroy(); - } + return bytes; + } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } + function asciiToBytes(str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xff); + } + return byteArray; + } - source.on('error', onerror); - dest.on('error', onerror); + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + return byteArray; + } - source.removeListener('end', onend); - source.removeListener('close', onclose); + function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); + } - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + return i; + } - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` + function isArrayBufferView(obj) { + return ( + typeof ArrayBuffer.isView === "function" && + ArrayBuffer.isView(obj) + ); + } - dest.removeListener('close', cleanup); - } + function numberIsNaN(obj) { + return obj !== obj; // eslint-disable-line no-self-compare + } + }, + { "base64-js": 1, ieee754: 14 } + ], + 6: [ + function(require, module, exports) { + (function(Buffer) { + var Transform = require("stream").Transform; + var inherits = require("inherits"); + var StringDecoder = require("string_decoder").StringDecoder; + module.exports = CipherBase; + inherits(CipherBase, Transform); + function CipherBase(hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === "string"; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + this._decoder = null; + this._encoding = null; + } + CipherBase.prototype.update = function(data, inputEnc, outputEnc) { + if (typeof data === "string") { + data = new Buffer(data, inputEnc); + } + var outData = this._update(data); + if (this.hashMode) { + return this; + } + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } + return outData; + }; - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); -} catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } + CipherBase.prototype.setAutoPadding = function() {}; - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } + CipherBase.prototype.getAuthTag = function() { + throw new Error("trying to get auth tag in unsupported state"); + }; - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } + CipherBase.prototype.setAuthTag = function() { + throw new Error("trying to set auth tag in unsupported state"); + }; - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } + CipherBase.prototype.setAAD = function() { + throw new Error("trying to set aad in unsupported state"); + }; - return this; -}; + CipherBase.prototype._transform = function(data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); + } + } catch (e) { + err = e; + } finally { + next(err); + } + }; + CipherBase.prototype._flush = function(done) { + var err; + try { + this.push(this._final()); + } catch (e) { + err = e; + } finally { + done(err); + } + }; + CipherBase.prototype._finalOrDigest = function(outputEnc) { + var outData = this._final() || new Buffer(""); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData; + }; + + CipherBase.prototype._toString = function(value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } + if (this._encoding !== enc) { + throw new Error("can't switch encodings"); + } + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } + return out; + }; + }.call(this, require("buffer").Buffer)); + }, + { buffer: 5, inherits: 15, stream: 45, string_decoder: 46 } + ], + 7: [ + function(require, module, exports) { + (function(Buffer) { + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + + function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === "[object Array]"; + } + exports.isArray = isArray; -EventEmitter.prototype.on = EventEmitter.prototype.addListener; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; - var fired = false; + function isNumber(arg) { + return typeof arg === "number"; + } + exports.isNumber = isNumber; - function g() { - this.removeListener(type, g); + function isString(arg) { + return typeof arg === "string"; + } + exports.isString = isString; - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports.isSymbol = isSymbol; - g.listener = listener; - this.on(type, g); + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; - return this; -}; + function isRegExp(re) { + return objectToString(re) === "[object RegExp]"; + } + exports.isRegExp = isRegExp; -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; + function isObject(arg) { + return typeof arg === "object" && arg !== null; + } + exports.isObject = isObject; - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + function isDate(d) { + return objectToString(d) === "[object Date]"; + } + exports.isDate = isDate; - if (!this._events || !this._events[type]) - return this; + function isError(e) { + return ( + objectToString(e) === "[object Error]" || e instanceof Error + ); + } + exports.isError = isError; - list = this._events[type]; - length = list.length; - position = -1; + function isFunction(arg) { + return typeof arg === "function"; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return ( + arg === null || + typeof arg === "boolean" || + typeof arg === "number" || + typeof arg === "string" || + typeof arg === "symbol" || // ES6 symbol + typeof arg === "undefined" + ); + } + exports.isPrimitive = isPrimitive; - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); + exports.isBuffer = Buffer.isBuffer; - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } + function objectToString(o) { + return Object.prototype.toString.call(o); + } + }.call(this, { isBuffer: require("../../is-buffer/index.js") })); + }, + { "../../is-buffer/index.js": 16 } + ], + 8: [ + function(require, module, exports) { + (function(Buffer) { + "use strict"; + var inherits = require("inherits"); + var md5 = require("./md5"); + var rmd160 = require("ripemd160"); + var sha = require("sha.js"); + + var Base = require("cipher-base"); + + function HashNoConstructor(hash) { + Base.call(this, "digest"); + + this._hash = hash; + this.buffers = []; + } - if (position < 0) - return this; + inherits(HashNoConstructor, Base); - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + HashNoConstructor.prototype._update = function(data) { + this.buffers.push(data); + }; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } + HashNoConstructor.prototype._final = function() { + var buf = Buffer.concat(this.buffers); + var r = this._hash(buf); + this.buffers = null; - return this; -}; + return r; + }; -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + function Hash(hash) { + Base.call(this, "digest"); - if (!this._events) - return this; + this._hash = hash; + } - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } + inherits(Hash, Base); - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } + Hash.prototype._update = function(data) { + this._hash.update(data); + }; - listeners = this._events[type]; + Hash.prototype._final = function() { + return this._hash.digest(); + }; - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {var pbkdf2 = __webpack_require__(33); -var Promise = __webpack_require__(18); - -function shouldUseNative() { - return !!(typeof window !== 'undefined' && window.crypto && window.crypto.subtle); -} - -function pbkdf2Native(password, salt, iterations, keylen, digest) { - var algorithms = { - 'sha1': 'SHA-1', - 'sha-1': 'SHA-1', - 'sha256': 'SHA-256', - 'sha-256': 'SHA-256', - 'sha512': 'SHA-512', - 'sha-512': 'SHA-512' - }; - return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']).then(function (key) { - var algo = { - name: 'PBKDF2', - salt: new Buffer(salt), - iterations: iterations, - hash: algorithms[digest.toLowerCase()] - }; - return window.crypto.subtle.deriveKey(algo, key, { - name: 'AES-CTR', - length: keylen * 8 - }, true, ['encrypt', 'decrypt']); - }).then(function (derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function (keyArray) { - return new Buffer(keyArray).toString('hex'); - }); - }); -} + module.exports = function createHash(alg) { + alg = alg.toLowerCase(); + if ("md5" === alg) return new HashNoConstructor(md5); + if ("rmd160" === alg || "ripemd160" === alg) + return new HashNoConstructor(rmd160); -function pbkdf2Browserified(password, salt, iterations, keylen, digest) { - return new Promise(function (resolve, reject) { - pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function (error, key) { - if (error) { - reject('error in pbkdf2'); - } else { - resolve(key.toString('hex')); + return new Hash(sha(alg)); + }; + }.call(this, require("buffer").Buffer)); + }, + { + "./md5": 10, + buffer: 5, + "cipher-base": 6, + inherits: 15, + ripemd160: 36, + "sha.js": 38 + } + ], + 9: [ + function(require, module, exports) { + (function(Buffer) { + "use strict"; + var intSize = 4; + var zeroBuffer = new Buffer(intSize); + zeroBuffer.fill(0); + var chrsz = 8; + + function toArray(buf, bigEndian) { + if (buf.length % intSize !== 0) { + var len = buf.length + (intSize - buf.length % intSize); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; } - }); - }); -} -module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) + function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; + } -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { + function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); + } + exports.hash = hash; + }.call(this, require("buffer").Buffer)); + }, + { buffer: 5 } + ], + 10: [ + function(require, module, exports) { + "use strict"; + /* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { + var helpers = require("./helpers"); -var buffer = __webpack_require__(0); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; -} -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - return new Buffer(size); -} -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); - } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); - } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); - } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); - } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); - } - } + /* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ + function core_md5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << (len % 32); + x[((len + 64) >>> 9 << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936); + d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844); + d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + } - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); -} -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); - } - return new SlowBuffer(size); -} + /* + * These functions implement the four basic operations the algorithm uses. + */ + function md5_cmn(q, a, b, x, s, t) { + return safe_add( + bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), + b + ); + } + function md5_ff(a, b, c, d, x, s, t) { + return md5_cmn((b & c) | (~b & d), a, b, x, s, t); + } + function md5_gg(a, b, c, d, x, s, t) { + return md5_cmn((b & d) | (c & ~d), a, b, x, s, t); + } + function md5_hh(a, b, c, d, x, s, t) { + return md5_cmn(b ^ c ^ d, a, b, x, s, t); + } + function md5_ii(a, b, c, d, x, s, t) { + return md5_cmn(c ^ (b | ~d), a, b, x, s, t); + } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) + /* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + function safe_add(x, y) { + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xffff); + } -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { + /* + * Bitwise rotate a 32-bit number to the left. + */ + function bit_rol(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); + } -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) { + module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); + }; + }, + { "./helpers": 9 } + ], + 11: [ + function(require, module, exports) { + (function(Buffer) { + "use strict"; + var createHash = require("create-hash/browser"); + var inherits = require("inherits"); + + var Transform = require("stream").Transform; + + var ZEROS = new Buffer(128); + ZEROS.fill(0); + + function Hmac(alg, key) { + Transform.call(this); + alg = alg.toLowerCase(); + if (typeof key === "string") { + key = new Buffer(key); + } + + var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64; + + this._alg = alg; + this._key = key; + + if (key.length > blocksize) { + key = createHash(alg).update(key).digest(); + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize); + } + + var ipad = (this._ipad = new Buffer(blocksize)); + var opad = (this._opad = new Buffer(blocksize)); + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5c; + } + + this._hash = createHash(alg).update(ipad); + } -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; -} else { - module.exports = process.nextTick; -} + inherits(Hmac, Transform); -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; - -var Duplex = __webpack_require__(2); - -/**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(1); -/**/ - -util.inherits(Transform, Duplex); - -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) stream.push(data); - - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} + Hmac.prototype.update = function(data, enc) { + this._hash.update(data, enc); -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); + return this; + }; - Duplex.call(this, options); + Hmac.prototype._transform = function(data, _, next) { + this._hash.update(data); - this._transformState = new TransformState(this); + next(); + }; - var stream = this; + Hmac.prototype._flush = function(next) { + this.push(this.digest()); - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + next(); + }; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + Hmac.prototype.digest = function(enc) { + var h = this._hash.digest(); - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + return createHash(this._alg) + .update(this._opad) + .update(h) + .digest(enc); + }; - if (typeof options.flush === 'function') this._flush = options.flush; - } + module.exports = function createHmac(alg, key) { + return new Hmac(alg, key); + }; + }.call(this, require("buffer").Buffer)); + }, + { buffer: 5, "create-hash/browser": 8, inherits: 15, stream: 45 } + ], + 12: [ + function(require, module, exports) { + (function(process, global) { + /*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version 4.1.0 + */ - // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; + (function(global, factory) { + typeof exports === "object" && typeof module !== "undefined" + ? (module.exports = factory()) + : typeof define === "function" && define.amd + ? define(factory) + : (global.ES6Promise = factory()); + })(this, function() { + "use strict"; + function objectOrFunction(x) { + return ( + typeof x === "function" || + (typeof x === "object" && x !== null) + ); + } + + function isFunction(x) { + return typeof x === "function"; + } + + var _isArray = undefined; + if (!Array.isArray) { + _isArray = function(x) { + return Object.prototype.toString.call(x) === "[object Array]"; + }; + } else { + _isArray = Array.isArray; + } + + var isArray = _isArray; + + var len = 0; + var vertxNext = undefined; + var customSchedulerFn = undefined; + + var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } + }; + + function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; + } + + function setAsap(asapFn) { + asap = asapFn; + } + + var browserWindow = typeof window !== "undefined" + ? window + : undefined; + var browserGlobal = browserWindow || {}; + var BrowserMutationObserver = + browserGlobal.MutationObserver || + browserGlobal.WebKitMutationObserver; + var isNode = + typeof self === "undefined" && + typeof process !== "undefined" && + {}.toString.call(process) === "[object process]"; + + // test for web worker but not in IE10 + var isWorker = + typeof Uint8ClampedArray !== "undefined" && + typeof importScripts !== "undefined" && + typeof MessageChannel !== "undefined"; + + // node + function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + return process.nextTick(flush); + }; + } + + // vertx + function useVertxTimer() { + if (typeof vertxNext !== "undefined") { + return function() { + vertxNext(flush); + }; + } -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; + return useSetTimeout(); + } + + function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(""); + observer.observe(node, { characterData: true }); + + return function() { + node.data = iterations = ++iterations % 2; + }; + } + + // web worker + function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function() { + return channel.port2.postMessage(0); + }; + } + + function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function() { + return globalSetTimeout(flush, 1); + }; + } + + var queue = new Array(1000); + function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; + len = 0; + } -function done(stream, er, data) { - if (er) return stream.emit('error', er); + function attemptVertx() { + try { + var r = require; + var vertx = r("vertx"); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } + } + + var scheduleFlush = undefined; + // Decide what async method to use to triggering processing of queued callbacks: + if (isNode) { + scheduleFlush = useNextTick(); + } else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); + } else if (isWorker) { + scheduleFlush = useMessageChannel(); + } else if ( + browserWindow === undefined && + typeof require === "function" + ) { + scheduleFlush = attemptVertx(); + } else { + scheduleFlush = useSetTimeout(); + } + + function then(onFulfillment, onRejection) { + var _arguments = arguments; + + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } - if (data !== null && data !== undefined) stream.push(data); + var _state = parent._state; + + if (_state) { + (function() { + var callback = _arguments[_state - 1]; + asap(function() { + return invokeCallback( + _state, + child, + callback, + parent._result + ); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + return child; + } - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + /** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); - return stream.push(null); -} + promise.then(function(value){ + // value === 1 + }); + ``` -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { + Instead of writing the above, your code now simply becomes the following: -"use strict"; -/* WEBPACK VAR INJECTION */(function(process, setImmediate) {// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. + ```javascript + let promise = Promise.resolve(1); + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ + function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if ( + object && + typeof object === "object" && + object.constructor === Constructor + ) { + return object; + } + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; + } -module.exports = Writable; + var PROMISE_ID = Math.random().toString(36).substring(16); -/**/ -var processNextTick = __webpack_require__(11); -/**/ + function noop() {} -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ + var PENDING = void 0; + var FULFILLED = 1; + var REJECTED = 2; -/**/ -var Duplex; -/**/ + var GET_THEN_ERROR = new ErrorObject(); -Writable.WritableState = WritableState; + function selfFulfillment() { + return new TypeError( + "You cannot resolve a promise with itself" + ); + } -/**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(1); -/**/ + function cannotReturnOwn() { + return new TypeError( + "A promises callback cannot return that same promise." + ); + } -/**/ -var internalUtil = { - deprecate: __webpack_require__(49) -}; -/**/ + function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } + } + + function tryThen( + then, + value, + fulfillmentHandler, + rejectionHandler + ) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } + } + + function handleForeignThenable(promise, thenable, then) { + asap(function(promise) { + var sealed = false; + var error = tryThen( + then, + thenable, + function(value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + _resolve(promise, value); + } else { + fulfill(promise, value); + } + }, + function(reason) { + if (sealed) { + return; + } + sealed = true; + + _reject(promise, reason); + }, + "Settle: " + (promise._label || " unknown promise") + ); + + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); + } + + function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + _reject(promise, thenable._result); + } else { + subscribe( + thenable, + undefined, + function(value) { + return _resolve(promise, value); + }, + function(reason) { + return _reject(promise, reason); + } + ); + } + } + + function handleMaybeThenable(promise, maybeThenable, then$$) { + if ( + maybeThenable.constructor === promise.constructor && + then$$ === then && + maybeThenable.constructor.resolve === resolve + ) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$ === GET_THEN_ERROR) { + _reject(promise, GET_THEN_ERROR.error); + GET_THEN_ERROR.error = null; + } else if (then$$ === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$)) { + handleForeignThenable(promise, maybeThenable, then$$); + } else { + fulfill(promise, maybeThenable); + } + } + } -/**/ -var Stream; -(function () { - try { - Stream = __webpack_require__(6); - } catch (_) {} finally { - if (!Stream) Stream = __webpack_require__(8).EventEmitter; - } -})(); -/**/ - -var Buffer = __webpack_require__(0).Buffer; -/**/ -var bufferShim = __webpack_require__(10); -/**/ - -util.inherits(Writable, Stream); + function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } + } -function nop() {} - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(2); - - options = options || {}; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - } catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || __webpack_require__(2); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } - this._writableState = new WritableState(options, this); + publish(promise); + } - // legacy. - this.writable = true; + function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } - if (options) { - if (typeof options.write === 'function') this._write = options.write; + promise._result = value; + promise._state = FULFILLED; - if (typeof options.writev === 'function') this._writev = options.writev; - } + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } + } - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - processNextTick(cb, er); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; - } - return valid; -} + function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + asap(publishRejection, promise); + } - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; - if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + parent._onerror = null; - if (typeof cb !== 'function') cb = nop; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } + if (length === 0 && parent._state) { + asap(publish, parent); + } + } - return ret; -}; + function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; -Writable.prototype.cork = function () { - var state = this._writableState; + if (subscribers.length === 0) { + return; + } - state.corked++; -}; + var child = undefined, + callback = undefined, + detail = promise._result; -Writable.prototype.uncork = function () { - var state = this._writableState; + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; - if (state.corked) { - state.corked--; + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = bufferShim.from(chunk, encoding); - } - return chunk; -} + promise._subscribers.length = 0; + } -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); + function ErrorObject() { + this.error = null; + } - if (Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + var TRY_CATCH_ERROR = new ErrorObject(); - state.length += len; + function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } + } + + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } + + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + _resolve(promise, value); + } else if (failed) { + _reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + _reject(promise, value); + } + } - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + function initializePromise(promise, resolver) { + try { + resolver( + function resolvePromise(value) { + _resolve(promise, value); + }, + function rejectPromise(reason) { + _reject(promise, reason); + } + ); + } catch (e) { + _reject(promise, e); + } + } + + var id = 0; + function nextId() { + return id++; + } + + function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; + } + + function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) processNextTick(cb, er);else cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + this._result = new Array(this.length); - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + _reject(this.promise, validationError()); + } + } - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + function validationError() { + return new Error("Array Methods must be provided an Array"); + } - if (entry === null) state.lastBufferedRequest = null; - } + Enumerator.prototype._enumerate = function() { + var length = this.length; + var _input = this._input; - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } + }; + + Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + + if (resolve$$ === resolve) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== "function") { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt( + new c(function(resolve$$) { + return resolve$$(entry); + }), + i + ); + } + } else { + this._willSettleAt(resolve$$(entry), i); + } + }; -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; -Writable.prototype._writev = null; + if (promise._state === PENDING) { + this._remaining--; -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + if (this._remaining === 0) { + fulfill(promise, this._result); + } + }; + + Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + subscribe( + promise, + undefined, + function(value) { + return enumerator._settledAt(FULFILLED, i, value); + }, + function(reason) { + return enumerator._settledAt(REJECTED, i, reason); + } + ); + }; + + /** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + Example: - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ + function all(entries) { + return new Enumerator(this, entries).promise; + } -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(17).setImmediate)) - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var Buffer = __webpack_require__(0).Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + /** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + Example: - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } + An example real-world use case is implementing timeouts: - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ + function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function(_, reject) { + return reject( + new TypeError("You must pass an array to race.") + ); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } + } - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + /** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` - return res; -}; + Instead of writing the above, your code now simply becomes the following: -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ + function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; + } + + function needsResolver() { + throw new TypeError( + "You must pass a resolver function as the first argument to the promise constructor" + ); + } + + function needsNew() { + throw new TypeError( + "Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function." + ); + } + + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { -var createHash = __webpack_require__(29); -var inherits = __webpack_require__(1) + Unlike callbacks, promises are great composable primitives. -var Transform = __webpack_require__(6).Transform + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON -var ZEROS = new Buffer(128) -ZEROS.fill(0) + return values; + }); + ``` -function Hmac(alg, key) { - Transform.call(this) - alg = alg.toLowerCase() - if (typeof key === 'string') { - key = new Buffer(key) - } + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ + function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== "function" && needsResolver(); + this instanceof Promise + ? initializePromise(this, resolver) + : needsNew(); + } + } + + Promise.all = all; + Promise.race = race; + Promise.resolve = resolve; + Promise.reject = reject; + Promise._setScheduler = setScheduler; + Promise._setAsap = setAsap; + Promise._asap = asap; + + Promise.prototype = { + constructor: Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + let result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + let author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: then, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + catch: function _catch(onRejection) { + return this.then(null, onRejection); + } + }; - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + function polyfill() { + var local = undefined; - this._alg = alg - this._key = key + if (typeof global !== "undefined") { + local = global; + } else if (typeof self !== "undefined") { + local = self; + } else { + try { + local = Function("return this")(); + } catch (e) { + throw new Error( + "polyfill failed because global object is unavailable in this environment" + ); + } + } - if (key.length > blocksize) { - key = createHash(alg).update(key).digest() + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call( + P.resolve() + ); + } catch (e) { + // silently ignored + } + + if (promiseToString === "[object Promise]" && !P.cast) { + return; + } + } - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } + local.Promise = Promise; + } - var ipad = this._ipad = new Buffer(blocksize) - var opad = this._opad = new Buffer(blocksize) + // Strange compat.. + Promise.polyfill = polyfill; + Promise.Promise = Promise; - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } + return Promise; + }); + }.call( + this, + require("_process"), + typeof global !== "undefined" + ? global + : typeof self !== "undefined" + ? self + : typeof window !== "undefined" ? window : {} + )); + }, + { _process: 22 } + ], + 13: [ + function(require, module, exports) { + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; + } + module.exports = EventEmitter; + + // Backwards-compat with node 0.10.x + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError("n must be a positive number"); + this._maxListeners = n; + return this; + }; + + EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === "error") { + if ( + !this._events.error || + (isObject(this._events.error) && !this._events.error.length) + ) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error( + 'Uncaught, unspecified "error" event. (' + er + ")" + ); + err.context = er; + throw err; + } + } + } - this._hash = createHash(alg).update(ipad) -} + handler = this._events[type]; + + if (isUndefined(handler)) return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } -inherits(Hmac, Transform) + return true; + }; + + EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError("listener must be a function"); + + if (!this._events) this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit( + "newListener", + type, + isFunction(listener.listener) ? listener.listener : listener + ); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error( + "(node) warning: possible EventEmitter memory " + + "leak detected. %d listeners added. " + + "Use emitter.setMaxListeners() to increase limit.", + this._events[type].length + ); + if (typeof console.trace === "function") { + // not supported in IE 10 + console.trace(); + } + } + } -Hmac.prototype.update = function (data, enc) { - this._hash.update(data, enc) + return this; + }; - return this -} + EventEmitter.prototype.on = EventEmitter.prototype.addListener; -Hmac.prototype._transform = function (data, _, next) { - this._hash.update(data) + EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError("listener must be a function"); - next() -} + var fired = false; -Hmac.prototype._flush = function (next) { - this.push(this.digest()) + function g() { + this.removeListener(type, g); - next() -} + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } -Hmac.prototype.digest = function (enc) { - var h = this._hash.digest() + g.listener = listener; + this.on(type, g); + + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError("listener must be a function"); + + if (!this._events || !this._events[type]) return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if ( + list === listener || + (isFunction(list.listener) && list.listener === listener) + ) { + delete this._events[type]; + if (this._events.removeListener) + this.emit("removeListener", type, listener); + } else if (isObject(list)) { + for (i = length; i-- > 0; ) { + if ( + list[i] === listener || + (list[i].listener && list[i].listener === listener) + ) { + position = i; + break; + } + } - return createHash(this._alg).update(this._opad).update(h).digest(enc) -} + if (position < 0) return this; -module.exports = function createHmac(alg, key) { - return new Hmac(alg, key) -} + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) + if (this._events.removeListener) + this.emit("removeListener", type, listener); + } -/***/ }), -/* 16 */ -/***/ (function(module, exports) { + return this; + }; -var toString = {}.toString; + EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + if (!this._events) return this; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) this._events = {}; + else if (this._events[type]) delete this._events[type]; + return this; + } -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === "removeListener") continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = {}; + return this; + } -var apply = Function.prototype.apply; + listeners = this._events[type]; -// DOM APIs, for completeness + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { - if (timeout) { - timeout.close(); - } -}; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; + return this; + }; -// setimmediate attaches itself to the global object -__webpack_require__(43); -exports.setImmediate = setImmediate; -exports.clearImmediate = clearImmediate; + EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) ret = []; + else if (isFunction(this._events[type])) ret = [this._events[type]]; + else ret = this._events[type].slice(); + return ret; + }; + EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { + if (isFunction(evlistener)) return 1; + else if (evlistener) return evlistener.length; + } + return 0; + }; -"use strict"; + EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); + }; + function isFunction(arg) { + return typeof arg === "function"; + } -module.exports = typeof Promise === 'function' ? Promise : __webpack_require__(35); + function isNumber(arg) { + return typeof arg === "number"; + } + function isObject(arg) { + return typeof arg === "object" && arg !== null; + } -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { + function isUndefined(arg) { + return arg === void 0; + } + }, + {} + ], + 14: [ + function(require, module, exports) { + exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for ( + ; + nBits > 0; + (e = e * 256 + buffer[offset + i]), (i += d), (nBits -= 8) + ) { + } -"use strict"; -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for ( + ; + nBits > 0; + (m = m * 256 + buffer[offset + i]), (i += d), (nBits -= 8) + ) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for ( + ; + mLen >= 8; + (buffer[offset + i] = m & 0xff), (i += d), (m /= 256), (mLen -= 8) + ) { + } -module.exports = PassThrough; + e = (e << mLen) | m; + eLen += mLen; + for ( + ; + eLen > 0; + (buffer[offset + i] = e & 0xff), (i += d), (e /= 256), (eLen -= 8) + ) { + } -var Transform = __webpack_require__(12); + buffer[offset + i - d] |= s * 128; + }; + }, + {} + ], + 15: [ + function(require, module, exports) { + if (typeof Object.create === "function") { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + }, + {} + ], + 16: [ + function(require, module, exports) { + /*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ -/**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(1); -/**/ + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + module.exports = function(obj) { + return ( + obj != null && + (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) + ); + }; + + function isBuffer(obj) { + return ( + !!obj.constructor && + typeof obj.constructor.isBuffer === "function" && + obj.constructor.isBuffer(obj) + ); + } -util.inherits(PassThrough, Transform); + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer(obj) { + return ( + typeof obj.readFloatLE === "function" && + typeof obj.slice === "function" && + isBuffer(obj.slice(0, 0)) + ); + } + }, + {} + ], + 17: [ + function(require, module, exports) { + var toString = {}.toString; + + module.exports = + Array.isArray || + function(arr) { + return toString.call(arr) == "[object Array]"; + }; + }, + {} + ], + 18: [ + function(require, module, exports) { + /** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; - Transform.call(this, options); -} + /** `Object#toString` result references. */ + var argsTag = "[object Arguments]", + funcTag = "[object Function]", + genTag = "[object GeneratorFunction]"; -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: + return func.call(thisArg); + case 1: + return func.call(thisArg, args[0]); + case 2: + return func.call(thisArg, args[0], args[1]); + case 3: + return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) { + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, result = Array(n); -module.exports = Readable; + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } -/**/ -var processNextTick = __webpack_require__(11); -/**/ + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } -/**/ -var isArray = __webpack_require__(16); -/**/ + /** Used for built-in method references. */ + var objectProto = Object.prototype; -/**/ -var Duplex; -/**/ + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; -Readable.ReadableState = ReadableState; + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; -/**/ -var EE = __webpack_require__(8).EventEmitter; + /** Built-in value references. */ + var propertyIsEnumerable = objectProto.propertyIsEnumerable; -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max; -/**/ -var Stream; -(function () { - try { - Stream = __webpack_require__(6); - } catch (_) {} finally { - if (!Stream) Stream = __webpack_require__(8).EventEmitter; - } -})(); -/**/ - -var Buffer = __webpack_require__(0).Buffer; -/**/ -var bufferShim = __webpack_require__(10); -/**/ - -/**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(1); -/**/ - -/**/ -var debugUtil = __webpack_require__(51); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = __webpack_require__(37); -var StringDecoder; - -util.inherits(Readable, Stream); - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } -} - -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(2); - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(14).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} + /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ + var nonEnumShadows = !propertyIsEnumerable.call( + { valueOf: 1 }, + "valueOf" + ); -function Readable(options) { - Duplex = Duplex || __webpack_require__(2); + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = isArray(value) || isArguments(value) + ? baseTimes(value.length, String) + : []; + + var length = result.length, skipIndexes = !!length; + + for (var key in value) { + if ( + (inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == "length" || isIndex(key, length))) + ) { + result.push(key); + } + } + return result; + } - if (!(this instanceof Readable)) return new Readable(options); + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if ( + !(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object)) + ) { + object[key] = value; + } + } - this._readableState = new ReadableState(options, this); + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != "constructor") { + result.push(key); + } + } + return result; + } - // legacy - this.readable = true; + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + start = nativeMax(start === undefined ? func.length - 1 : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; + } - if (options && typeof options.read === 'function') this._read = options.read; + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + object || (object = {}); - Stream.call(this); -} + var index = -1, length = props.length; -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; + while (++index < length) { + var key = props[index]; - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = bufferShim.from(chunk, encoding); - encoding = ''; - } - } + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + assignValue( + object, + key, + newValue === undefined ? source[key] : newValue + ); + } + return object; + } - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - } + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = assigner.length > 3 && + typeof customizer == "function" + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return ( + !!length && + (typeof value == "number" || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length) + ); + } - return needMoreData(state); -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(14).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if ( + type == "number" + ? isArrayLike(object) && isIndex(index, object.length) + : type == "string" && index in object + ) { + return eq(object[index], value); + } + return false; + } - n = howMuchToRead(n, state); + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = + (typeof Ctor == "function" && Ctor.prototype) || objectProto; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } + return value === proto; + } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return ( + isArrayLikeObject(value) && + hasOwnProperty.call(value, "callee") && + (!propertyIsEnumerable.call(value, "callee") || + objectToString.call(value) == argsTag) + ); + } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return ( + value != null && isLength(value.length) && !isFunction(value) + ); + } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ""; + return tag == funcTag || tag == genTag; + } - if (ret !== null) this.emit('data', ret); + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return ( + typeof value == "number" && + value > -1 && + value % 1 == 0 && + value <= MAX_SAFE_INTEGER + ); + } - return ret; -}; + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return !!value && (type == "object" || type == "function"); + } -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return !!value && typeof value == "object"; + } - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) + ? arrayLikeKeys(object) + : baseKeys(object); + } - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } + module.exports = assign; + }, + {} + ], + 19: [ + function(require, module, exports) { + (function(process, Buffer) { + var createHmac = require("create-hmac"); + var checkParameters = require("./precondition"); + + exports.pbkdf2 = function( + password, + salt, + iterations, + keylen, + digest, + callback + ) { + if (typeof digest === "function") { + callback = digest; + digest = undefined; + } + + checkParameters(iterations, keylen); + if (typeof callback !== "function") + throw new Error("No callback provided to pbkdf2"); + + setTimeout(function() { + callback( + null, + exports.pbkdf2Sync(password, salt, iterations, keylen, digest) + ); + }); + }; - function onend() { - debug('onend'); - dest.end(); - } + var defaultEncoding; + if (process.browser) { + defaultEncoding = "utf-8"; + } else { + var pVersionMajor = parseInt( + process.version.split(".")[0].slice(1), + 10 + ); - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + defaultEncoding = pVersionMajor >= 6 ? "utf-8" : "binary"; + } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + exports.pbkdf2Sync = function( + password, + salt, + iterations, + keylen, + digest + ) { + if (!Buffer.isBuffer(password)) + password = new Buffer(password, defaultEncoding); + if (!Buffer.isBuffer(salt)) + salt = new Buffer(salt, defaultEncoding); + + checkParameters(iterations, keylen); + + digest = digest || "sha1"; + + var hLen; + var l = 1; + var DK = new Buffer(keylen); + var block1 = new Buffer(salt.length + 4); + salt.copy(block1, 0, 0, salt.length); + + var r; + var T; + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length); + var U = createHmac(digest, password).update(block1).digest(); + + if (!hLen) { + hLen = U.length; + T = new Buffer(hLen); + l = Math.ceil(keylen / hLen); + r = keylen - (l - 1) * hLen; + } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } + U.copy(T, 0, 0, hLen); - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + for (var j = 1; j < iterations; j++) { + U = createHmac(digest, password).update(U).digest(); + for (var k = 0; k < hLen; k++) + T[k] ^= U[k]; + } - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + var destPos = (i - 1) * hLen; + var len = i === l ? r : hLen; + T.copy(DK, destPos, 0, len); + } - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } + return DK; + }; + }.call(this, require("_process"), require("buffer").Buffer)); + }, + { "./precondition": 20, _process: 22, buffer: 5, "create-hmac": 11 } + ], + 20: [ + function(require, module, exports) { + var MAX_ALLOC = Math.pow(2, 30) - 1; // default in iojs + module.exports = function(iterations, keylen) { + if (typeof iterations !== "number") { + throw new TypeError("Iterations not a number"); + } - // tell the dest that it's being piped to - dest.emit('pipe', src); + if (iterations < 0) { + throw new TypeError("Bad iterations"); + } - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + if (typeof keylen !== "number") { + throw new TypeError("Key length not a number"); + } - return dest; -}; - -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { + /* eslint no-self-compare: 0 */ + throw new TypeError("Bad key length"); + } + }; + }, + {} + ], + 21: [ + function(require, module, exports) { + (function(process) { + "use strict"; + if ( + !process.version || + process.version.indexOf("v0.") === 0 || + (process.version.indexOf("v1.") === 0 && + process.version.indexOf("v1.8.") !== 0) + ) { + module.exports = nextTick; + } else { + module.exports = process.nextTick; + } -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; + function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== "function") { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } + } + }.call(this, require("_process"))); + }, + { _process: 22 } + ], + 22: [ + function(require, module, exports) { + // shim for using process in browser + var process = (module.exports = {}); + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); + } + function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + if (typeof setTimeout === "function") { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === "function") { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + })(); + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ( + (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && + setTimeout + ) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ( + (cachedClearTimeout === defaultClearTimeout || + !cachedClearTimeout) && + clearTimeout + ) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + process.nextTick = function(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; - if (!dest) dest = state.pipes; + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function() { + this.fun.apply(null, this.array); + }; + process.title = "browser"; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ""; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function(name) { + return []; + }; + + process.binding = function(name) { + throw new Error("process.binding is not supported"); + }; + + process.cwd = function() { + return "/"; + }; + process.chdir = function(dir) { + throw new Error("process.chdir is not supported"); + }; + process.umask = function() { + return 0; + }; + }, + {} + ], + 23: [ + function(require, module, exports) { + module.exports = require("./lib/_stream_duplex.js"); + }, + { "./lib/_stream_duplex.js": 24 } + ], + 24: [ + function(require, module, exports) { + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. + + "use strict"; + /**/ + + var objectKeys = + Object.keys || + function(obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + } + return keys; + }; + /**/ - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } + module.exports = Duplex; - // slow case. multiple pipe destinations. + /**/ + var processNextTick = require("process-nextick-args"); + /**/ - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + /**/ + var util = require("core-util-is"); + util.inherits = require("inherits"); + /**/ - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this); - }return this; - } + var Readable = require("./_stream_readable"); + var Writable = require("./_stream_writable"); - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); - } - } - } + util.inherits(Duplex, Readable); - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; + } -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } -} + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } + Readable.call(this, options); + Writable.call(this, options); - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } + if (options && options.readable === false) this.readable = false; - self.push(null); - }); + if (options && options.writable === false) this.writable = false; - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + this.once("end", onend); + } - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); + } - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + function onEndNT(self) { + self.end(); + } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + }, + { + "./_stream_readable": 26, + "./_stream_writable": 28, + "core-util-is": 7, + inherits: 15, + "process-nextick-args": 21 + } + ], + 25: [ + function(require, module, exports) { + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = bufferShim.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} + "use strict"; + module.exports = PassThrough; -function endReadable(stream) { - var state = stream._readableState; + var Transform = require("./_stream_transform"); - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + /**/ + var util = require("core-util-is"); + util.inherits = require("inherits"); + /**/ - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} + util.inherits(PassThrough, Transform); -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) + Transform.call(this, options); + } -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + }, + { "./_stream_transform": 27, "core-util-is": 7, inherits: 15 } + ], + 26: [ + function(require, module, exports) { + (function(process) { + "use strict"; + module.exports = Readable; + + /**/ + var processNextTick = require("process-nextick-args"); + /**/ + + /**/ + var isArray = require("isarray"); + /**/ + + /**/ + var Duplex; + /**/ + + Readable.ReadableState = ReadableState; + + /**/ + var EE = require("events").EventEmitter; + + var EElistenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ + + /**/ + var Stream = require("./internal/streams/stream"); + /**/ + + var Buffer = require("buffer").Buffer; + /**/ + var bufferShim = require("buffer-shims"); + /**/ + + /**/ + var util = require("core-util-is"); + util.inherits = require("inherits"); + /**/ + + /**/ + var debugUtil = require("util"); + var debug = void 0; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function() {}; + } + /**/ + + var BufferList = require("./internal/streams/BufferList"); + var StringDecoder; + + util.inherits(Readable, Stream); + + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === "function") { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + } -/* WEBPACK VAR INJECTION */(function(Buffer) {/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + function ReadableState(options, stream) { + Duplex = Duplex || require("./_stream_duplex"); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = + this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || "utf8"; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require("string_decoder/").StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } -var inherits = __webpack_require__(1) -var Hash = __webpack_require__(4) - -var K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 -] - -var W = new Array(64) - -function Sha256 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha256, Hash) - -Sha256.prototype.init = function () { - this._a = 0x6a09e667 - this._b = 0xbb67ae85 - this._c = 0x3c6ef372 - this._d = 0xa54ff53a - this._e = 0x510e527f - this._f = 0x9b05688c - this._g = 0x1f83d9ab - this._h = 0x5be0cd19 - - return this -} - -function ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) -} - -function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) -} - -function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) -} - -function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) -} - -Sha256.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - var f = this._f | 0 - var g = this._g | 0 - var h = this._h | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 - var T2 = (sigma0(a) + maj(a, b, c)) | 0 - - h = g - g = f - f = e - e = (d + T1) | 0 - d = c - c = b - b = a - a = (T1 + T2) | 0 - } + function Readable(options) { + Duplex = Duplex || require("./_stream_duplex"); - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 - this._f = (f + this._f) | 0 - this._g = (g + this._g) | 0 - this._h = (h + this._h) | 0 -} - -Sha256.prototype._hash = function () { - var H = new Buffer(32) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - H.writeInt32BE(this._h, 28) - - return H -} - -module.exports = Sha256 - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {var inherits = __webpack_require__(1) -var Hash = __webpack_require__(4) - -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -] - -var W = new Array(160) - -function Sha512 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha512, Hash) - -Sha512.prototype.init = function () { - this._ah = 0x6a09e667 - this._bh = 0xbb67ae85 - this._ch = 0x3c6ef372 - this._dh = 0xa54ff53a - this._eh = 0x510e527f - this._fh = 0x9b05688c - this._gh = 0x1f83d9ab - this._hh = 0x5be0cd19 - - this._al = 0xf3bcc908 - this._bl = 0x84caa73b - this._cl = 0xfe94f82b - this._dl = 0x5f1d36f1 - this._el = 0xade682d1 - this._fl = 0x2b3e6c1f - this._gl = 0xfb41bd6b - this._hl = 0x137e2179 - - return this -} - -function Ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) -} - -function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) -} - -function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) -} - -function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) -} - -function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) -} - -function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) -} - -function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 -} - -Sha512.prototype._update = function (M) { - var W = this._w - - var ah = this._ah | 0 - var bh = this._bh | 0 - var ch = this._ch | 0 - var dh = this._dh | 0 - var eh = this._eh | 0 - var fh = this._fh | 0 - var gh = this._gh | 0 - var hh = this._hh | 0 - - var al = this._al | 0 - var bl = this._bl | 0 - var cl = this._cl | 0 - var dl = this._dl | 0 - var el = this._el | 0 - var fl = this._fl | 0 - var gl = this._gl | 0 - var hl = this._hl | 0 - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4) - W[i + 1] = M.readInt32BE(i * 4 + 4) - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2] - var xl = W[i - 15 * 2 + 1] - var gamma0 = Gamma0(xh, xl) - var gamma0l = Gamma0l(xl, xh) - - xh = W[i - 2 * 2] - xl = W[i - 2 * 2 + 1] - var gamma1 = Gamma1(xh, xl) - var gamma1l = Gamma1l(xl, xh) - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2] - var Wi7l = W[i - 7 * 2 + 1] - - var Wi16h = W[i - 16 * 2] - var Wi16l = W[i - 16 * 2 + 1] - - var Wil = (gamma0l + Wi7l) | 0 - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 - Wil = (Wil + gamma1l) | 0 - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 - Wil = (Wil + Wi16l) | 0 - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 - - W[i] = Wih - W[i + 1] = Wil - } + if (!(this instanceof Readable)) return new Readable(options); - for (var j = 0; j < 160; j += 2) { - Wih = W[j] - Wil = W[j + 1] - - var majh = maj(ah, bh, ch) - var majl = maj(al, bl, cl) - - var sigma0h = sigma0(ah, al) - var sigma0l = sigma0(al, ah) - var sigma1h = sigma1(eh, el) - var sigma1l = sigma1(el, eh) - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j] - var Kil = K[j + 1] - - var chh = Ch(eh, fh, gh) - var chl = Ch(el, fl, gl) - - var t1l = (hl + sigma1l) | 0 - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 - t1l = (t1l + chl) | 0 - t1h = (t1h + chh + getCarry(t1l, chl)) | 0 - t1l = (t1l + Kil) | 0 - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 - t1l = (t1l + Wil) | 0 - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0 - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el - el = (dl + t1l) | 0 - eh = (dh + t1h + getCarry(el, dl)) | 0 - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al - al = (t1l + t2l) | 0 - ah = (t1h + t2h + getCarry(al, t1l)) | 0 - } + this._readableState = new ReadableState(options, this); - this._al = (this._al + al) | 0 - this._bl = (this._bl + bl) | 0 - this._cl = (this._cl + cl) | 0 - this._dl = (this._dl + dl) | 0 - this._el = (this._el + el) | 0 - this._fl = (this._fl + fl) | 0 - this._gl = (this._gl + gl) | 0 - this._hl = (this._hl + hl) | 0 - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 -} - -Sha512.prototype._hash = function () { - var H = new Buffer(64) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } + // legacy + this.readable = true; - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - writeInt64BE(this._gh, this._gl, 48) - writeInt64BE(this._hh, this._hl, 56) - - return H -} - -module.exports = Sha512 - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {var pbkdf2 = __webpack_require__(9); -var createHMAC = __webpack_require__(15); -var Promise = __webpack_require__(18); - -module.exports = { - encryptLogin: encryptLogin, - renderPassword: renderPassword, - createFingerprint: createFingerprint, - _deriveEncryptedLogin: deriveEncryptedLogin, - _getPasswordTemplate: getPasswordTemplate, - _prettyPrint: prettyPrint, - _string2charCodes: string2charCodes, - _getCharType: getCharType, - _getPasswordChar: getPasswordChar, - _createHmac: createHmac -}; - -function encryptLogin(login, masterPassword, options) { - var _options = options !== undefined ? options : {}; - var iterations = _options.iterations || 8192; - var keylen = _options.keylen || 32; - return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); -} - -function renderPassword(encryptedLogin, site, passwordOptions) { - return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) { - var template = passwordOptions.template || getPasswordTemplate(passwordOptions); - return prettyPrint(derivedEncryptedLogin, template); - }); -} + if (options && typeof options.read === "function") + this._read = options.read; -function createHmac(encryptedLogin, salt) { - return new Promise(function (resolve) { - resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); - }); -} + Stream.call(this); + } -function deriveEncryptedLogin(encryptedLogin, site, options) { - var _options = options !== undefined ? options : {}; - var length = _options.length || 12; - var counter = _options.counter || 1; + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ""; + } + } - var salt = site + counter.toString(); - return createHmac(encryptedLogin, salt).then(function (derivedHash) { - return derivedHash.substring(0, length); - }); -} - -function getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's' - }; - var returnedTemplate = ''; - Object.keys(templates).forEach(function (template) { - if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { - returnedTemplate += templates[template]; - } - }); - return returnedTemplate; -} + return readableAddChunk(this, state, chunk, encoding, false); + }; -function prettyPrint(hash, template) { - var password = ''; + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, "", true); + }; - string2charCodes(hash).forEach(function (charCode, index) { - var charType = getCharType(template, index); - password += getPasswordChar(charType, charCode); - }); - return password; -} + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; -function string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; -} - -function getCharType(template, index) { - return template[index % template.length]; -} - -function getPasswordChar(charType, index) { - var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; -} - -function createFingerprint(str) { - return new Promise(function (resolve) { - resolve(createHMAC('sha256', new Buffer(str)).digest('hex')); - }); -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -var pbkdf2 = __webpack_require__(9); -var bigInt = __webpack_require__(27); - -module.exports = { - generatePassword: generatePassword, - _calcEntropy: calcEntropy, - _consumeEntropy: consumeEntropy, - _getSetOfCharacters: getSetOfCharacters, - _getConfiguredRules: getConfiguredRules, - _insertStringPseudoRandomly: insertStringPseudoRandomly, - _getOneCharPerRule: getOneCharPerRule, - _renderPassword: renderPassword -}; - -function generatePassword(site, login, masterPassword, passwordProfile) { - return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) { - return renderPassword(entropy, passwordProfile); - }); -} - -function calcEntropy(site, login, masterPassword, passwordProfile) { - var salt = site + login + passwordProfile.counter.toString(16); - return pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest); -} - -var characterSubsets = { - lowercase: 'abcdefghijklmnopqrstuvwxyz', - uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - numbers: '0123456789', - symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' -}; - -function getSetOfCharacters(rules) { - if (typeof rules === 'undefined') { - return characterSubsets.lowercase + characterSubsets.uppercase + characterSubsets.numbers + characterSubsets.symbols; - } - var setOfChars = ''; - rules.forEach(function (rule) { - setOfChars += characterSubsets[rule]; - }); - return setOfChars; -} + function readableAddChunk( + stream, + state, + chunk, + encoding, + addToFront + ) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit("error", er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || (chunk && chunk.length > 0)) { + if (state.ended && !addToFront) { + var e = new Error("stream.push() after EOF"); + stream.emit("error", e); + } else if (state.endEmitted && addToFront) { + var _e = new Error("stream.unshift() after end event"); + stream.emit("error", _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit("data", chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); -function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { - if (generatedPassword.length >= maxLength) { - return { value: generatedPassword, entropy: quotient }; - } - var longDivision = quotient.divmod(setOfCharacters.length); - generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); -} - -function insertStringPseudoRandomly(generatedPassword, entropy, string) { - for (var i = 0; i < string.length; i++) { - var longDivision = entropy.divmod(generatedPassword.length); - generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); - entropy = longDivision.quotient; - } - return generatedPassword; -} - -function getOneCharPerRule(entropy, rules) { - var oneCharPerRules = ''; - rules.forEach(function (rule) { - var password = consumeEntropy('', entropy, characterSubsets[rule], 1); - oneCharPerRules += password.value; - entropy = password.entropy; - }); - return { value: oneCharPerRules, entropy: entropy }; -} + if (state.needReadable) emitReadable(stream); + } + } -function getConfiguredRules(passwordProfile) { - return ['lowercase', 'uppercase', 'numbers', 'symbols'].filter(function (rule) { - return passwordProfile[rule]; - }); -} - -function renderPassword(entropy, passwordProfile) { - var rules = getConfiguredRules(passwordProfile); - var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, passwordProfile.length - rules.length); - var charactersToAdd = getOneCharPerRule(password.entropy, rules); - return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); -} - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* eslint-disable no-unused-vars */ -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; - -function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } - - return Object(val); -} - -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } - - return true; - } catch (e) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } -} - -module.exports = shouldUseNative() ? Object.assign : function (target, source) { - var from; - var to = toObject(target); - var symbols; - - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); - - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - - if (Object.getOwnPropertySymbols) { - symbols = Object.getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - - return to; -}; - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} + return needMoreData(state); + } -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) -} + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return ( + !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0) + ); + } -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) + // backwards compatibility. + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require("string_decoder/").StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; - arr = new Arr(len * 3 / 4 - placeHolders) + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || (state.length === 0 && state.ended)) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) + return state.buffer.head.data.length; + else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) + state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } - var L = 0 + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function(n) { + debug("read", n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if ( + n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended) + ) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug("need readable", doRead); + + // if we currently have less than the highWaterMark, then also read some + if ( + state.length === 0 || + state.length - n < state.highWaterMark + ) { + doRead = true; + debug("length less than watermark", doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit("data", ret); + + return ret; + }; - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } + function chunkInvalid(state, chunk) { + var er = null; + if ( + !Buffer.isBuffer(chunk) && + typeof chunk !== "string" && + chunk !== null && + chunk !== undefined && + !state.objectMode + ) { + er = new TypeError("Invalid non-string/buffer chunk"); + } + return er; + } - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; - return arr -} + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream); + else emitReadable_(stream); + } + } -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } + function emitReadable_(stream) { + debug("emit readable"); + stream.emit("readable"); + flow(stream); + } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } + } - parts.push(output) + function maybeReadMore_(stream, state) { + var len = state.length; + while ( + !state.reading && + !state.flowing && + !state.ended && + state.length < state.highWaterMark + ) { + debug("maybeReadMore read 0"); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else len = state.length; + } + state.readingMore = false; + } - return parts.join('') -} + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function(n) { + this.emit("error", new Error("_read() is not implemented")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + + var doEnd = + (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn); + else src.once("end", endFn); + + dest.on("unpipe", onunpipe); + function onunpipe(readable) { + debug("onunpipe"); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug("onend"); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + // cleanup event handlers once the pipe is broken + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", cleanup); + src.removeListener("data", ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if ( + state.awaitDrain && + (!dest._writableState || dest._writableState.needDrain) + ) + ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ( + ((state.pipesCount === 1 && state.pipes === dest) || + (state.pipesCount > 1 && + indexOf(state.pipes, dest) !== -1)) && + !cleanedUp + ) { + debug( + "false write response, pause", + src._readableState.awaitDrain + ); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) + dest.emit("error", er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, "error", onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + + function unpipe() { + debug("unpipe"); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit("pipe", src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug("pipe resume"); + src.resume(); + } + + return dest; + }; -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { + state.flowing = true; + flow(src); + } + }; + } -/* WEBPACK VAR INJECTION */(function(module) {var bigInt = (function (undefined) { - "use strict"; + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; - var BASE = 1e7, - LOG_BASE = 7, - MAX_INT = 9007199254740992, - MAX_INT_ARR = smallToArray(MAX_INT), - LOG_MAX_INT = Math.log(MAX_INT); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - function Integer(v, radix) { - if (typeof v === "undefined") return Integer[0]; - if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix); - return parseValue(v); - } + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - function BigInteger(value, sign) { - this.value = value; - this.sign = sign; - this.isSmall = false; - } - BigInteger.prototype = Object.create(Integer.prototype); + if (!dest) dest = state.pipes; - function SmallInteger(value) { - this.value = value; - this.sign = value < 0; - this.isSmall = true; - } - SmallInteger.prototype = Object.create(Integer.prototype); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit("unpipe", this); + return this; + } - function isPrecise(n) { - return -MAX_INT < n && n < MAX_INT; - } + // slow case. multiple pipe destinations. - function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes - if (n < 1e7) - return [n]; - if (n < 1e14) - return [n % 1e7, Math.floor(n / 1e7)]; - return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; - } + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - function arrayToSmall(arr) { // If BASE changes this function may need to change - trim(arr); - var length = arr.length; - if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { - switch (length) { - case 0: return 0; - case 1: return arr[0]; - case 2: return arr[0] + arr[1] * BASE; - default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; - } - } - return arr; - } + for (var i = 0; i < len; i++) { + dests[i].emit("unpipe", this); + } + return this; + } - function trim(v) { - var i = v.length; - while (v[--i] === 0); - v.length = i + 1; - } + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; - function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger - var x = new Array(length); - var i = -1; - while (++i < length) { - x[i] = 0; - } - return x; - } + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - function truncate(n) { - if (n > 0) return Math.floor(n); - return Math.ceil(n); - } + dest.emit("unpipe", this); - function add(a, b) { // assumes a and b are arrays with a.length >= b.length - var l_a = a.length, - l_b = b.length, - r = new Array(l_a), - carry = 0, - base = BASE, - sum, i; - for (i = 0; i < l_b; i++) { - sum = a[i] + b[i] + carry; - carry = sum >= base ? 1 : 0; - r[i] = sum - carry * base; - } - while (i < l_a) { - sum = a[i] + carry; - carry = sum === base ? 1 : 0; - r[i++] = sum - carry * base; - } - if (carry > 0) r.push(carry); - return r; - } + return this; + }; - function addAny(a, b) { - if (a.length >= b.length) return add(a, b); - return add(b, a); - } + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === "data") { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === "readable") { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } - function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT - var l = a.length, - r = new Array(l), - base = BASE, - sum, i; - for (i = 0; i < l; i++) { - sum = a[i] - base + carry; - carry = Math.floor(sum / base); - r[i] = sum - carry * base; - carry += 1; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; - BigInteger.prototype.add = function (v) { - var value, n = parseValue(v); - if (this.sign !== n.sign) { - return this.subtract(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) { - return new BigInteger(addSmall(a, Math.abs(b)), this.sign); - } - return new BigInteger(addAny(a, b), this.sign); - }; - BigInteger.prototype.plus = BigInteger.prototype.add; - - SmallInteger.prototype.add = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.subtract(n.negate()); - } - var b = n.value; - if (n.isSmall) { - if (isPrecise(a + b)) return new SmallInteger(a + b); - b = smallToArray(Math.abs(b)); - } - return new BigInteger(addSmall(b, Math.abs(a)), a < 0); - }; - SmallInteger.prototype.plus = SmallInteger.prototype.add; - - function subtract(a, b) { // assumes a and b are arrays with a >= b - var a_l = a.length, - b_l = b.length, - r = new Array(a_l), - borrow = 0, - base = BASE, - i, difference; - for (i = 0; i < b_l; i++) { - difference = a[i] - borrow - b[i]; - if (difference < 0) { - difference += base; - borrow = 1; - } else borrow = 0; - r[i] = difference; - } - for (i = b_l; i < a_l; i++) { - difference = a[i] - borrow; - if (difference < 0) difference += base; - else { - r[i++] = difference; - break; + function nReadingNextTick(self) { + debug("readable nexttick read 0"); + self.read(0); } - r[i] = difference; - } - for (; i < a_l; i++) { - r[i] = a[i]; - } - trim(r); - return r; - } - - function subtractAny(a, b, sign) { - var value, isSmall; - if (compareAbs(a, b) >= 0) { - value = subtract(a,b); - } else { - value = subtract(b, a); - sign = !sign; - } - value = arrayToSmall(value); - if (typeof value === "number") { - if (sign) value = -value; - return new SmallInteger(value); - } - return new BigInteger(value, sign); - } - function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT - var l = a.length, - r = new Array(l), - carry = -b, - base = BASE, - i, difference; - for (i = 0; i < l; i++) { - difference = a[i] + carry; - carry = Math.floor(difference / base); - difference %= base; - r[i] = difference < 0 ? difference + base : difference; - } - r = arrayToSmall(r); - if (typeof r === "number") { - if (sign) r = -r; - return new SmallInteger(r); - } return new BigInteger(r, sign); - } + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = true; + resume(this, state); + } + return this; + }; - BigInteger.prototype.subtract = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.add(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) - return subtractSmall(a, Math.abs(b), this.sign); - return subtractAny(a, b, this.sign); - }; - BigInteger.prototype.minus = BigInteger.prototype.subtract; - - SmallInteger.prototype.subtract = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.add(n.negate()); - } - var b = n.value; - if (n.isSmall) { - return new SmallInteger(a - b); - } - return subtractSmall(b, Math.abs(a), a >= 0); - }; - SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - - BigInteger.prototype.negate = function () { - return new BigInteger(this.value, !this.sign); - }; - SmallInteger.prototype.negate = function () { - var sign = this.sign; - var small = new SmallInteger(-this.value); - small.sign = !sign; - return small; - }; - - BigInteger.prototype.abs = function () { - return new BigInteger(this.value, false); - }; - SmallInteger.prototype.abs = function () { - return new SmallInteger(Math.abs(this.value)); - }; - - function multiplyLong(a, b) { - var a_l = a.length, - b_l = b.length, - l = a_l + b_l, - r = createArray(l), - base = BASE, - product, carry, i, a_i, b_j; - for (i = 0; i < a_l; ++i) { - a_i = a[i]; - for (var j = 0; j < b_l; ++j) { - b_j = b[j]; - product = a_i * b_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } } - } - trim(r); - return r; - } - - function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE - var l = a.length, - r = new Array(l), - base = BASE, - carry = 0, - product, i; - for (i = 0; i < l; i++) { - product = a[i] * b + carry; - carry = Math.floor(product / base); - r[i] = product - carry * base; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - function shiftLeft(x, n) { - var r = []; - while (n-- > 0) r.push(0); - return r.concat(x); - } + function resume_(stream, state) { + if (!state.reading) { + debug("resume read 0"); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit("resume"); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } - function multiplyKaratsuba(x, y) { - var n = Math.max(x.length, y.length); + Readable.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + return this; + }; - if (n <= 30) return multiplyLong(x, y); - n = Math.ceil(n / 2); + function flow(stream) { + var state = stream._readableState; + debug("flow", state.flowing); + while (state.flowing && stream.read() !== null) { + } + } - var b = x.slice(n), - a = x.slice(0, n), - d = y.slice(n), - c = y.slice(0, n); + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - var ac = multiplyKaratsuba(a, c), - bd = multiplyKaratsuba(b, d), - abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + self.push(null); + }); - var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); - trim(product); - return product; - } + stream.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) chunk = state.decoder.write(chunk); - // The following function is derived from a surface fit of a graph plotting the performance difference - // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. - function useKaratsuba(l1, l2) { - return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; - } + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) return; - BigInteger.prototype.multiply = function (v) { - var value, n = parseValue(v), - a = this.value, b = n.value, - sign = this.sign !== n.sign, - abs; - if (n.isSmall) { - if (b === 0) return Integer[0]; - if (b === 1) return this; - if (b === -1) return this.negate(); - abs = Math.abs(b); - if (abs < BASE) { - return new BigInteger(multiplySmall(a, abs), sign); - } - b = smallToArray(abs); - } - if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes - return new BigInteger(multiplyKaratsuba(a, b), sign); - return new BigInteger(multiplyLong(a, b), sign); - }; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === "function") { + this[i] = (function(method) { + return function() { + return stream[method].apply(stream, arguments); + }; + })(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on( + kProxyEvents[n], + self.emit.bind(self, kProxyEvents[n]) + ); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + debug("wrapped _read", n); + if (paused) { + paused = false; + stream.resume(); + } + }; - BigInteger.prototype.times = BigInteger.prototype.multiply; + return self; + }; - function multiplySmallAndArray(a, b, sign) { // a >= 0 - if (a < BASE) { - return new BigInteger(multiplySmall(b, a), sign); - } - return new BigInteger(multiplyLong(b, smallToArray(a)), sign); - } - SmallInteger.prototype._multiplyBySmall = function (a) { - if (isPrecise(a.value * this.value)) { - return new SmallInteger(a.value * this.value); + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join(""); + else if (state.buffer.length === 1) + ret = state.buffer.head.data; + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; } - return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); - }; - BigInteger.prototype._multiplyBySmall = function (a) { - if (a.value === 0) return Integer[0]; - if (a.value === 1) return this; - if (a.value === -1) return this.negate(); - return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); - }; - SmallInteger.prototype.multiply = function (v) { - return parseValue(v)._multiplyBySmall(this); - }; - SmallInteger.prototype.times = SmallInteger.prototype.multiply; - - function square(a) { - var l = a.length, - r = createArray(l + l), - base = BASE, - product, carry, i, a_i, a_j; - for (i = 0; i < l; i++) { - a_i = a[i]; - for (var j = 0; j < l; j++) { - a_j = a[j]; - product = a_i * a_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings + ? copyFromBufferString(n, list) + : copyFromBuffer(n, list); + } + return ret; } - } - trim(r); - return r; - } - BigInteger.prototype.square = function () { - return new BigInteger(square(this.value), false); - }; - - SmallInteger.prototype.square = function () { - var value = this.value * this.value; - if (isPrecise(value)) return new SmallInteger(value); - return new BigInteger(square(smallToArray(Math.abs(this.value))), false); - }; - - function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. - var a_l = a.length, - b_l = b.length, - base = BASE, - result = createArray(b.length), - divisorMostSignificantDigit = b[b_l - 1], - // normalization - lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), - remainder = multiplySmall(a, lambda), - divisor = multiplySmall(b, lambda), - quotientDigit, shift, carry, borrow, i, l, q; - if (remainder.length <= a_l) remainder.push(0); - divisor.push(0); - divisorMostSignificantDigit = divisor[b_l - 1]; - for (shift = a_l - b_l; shift >= 0; shift--) { - quotientDigit = base - 1; - if (remainder[shift + b_l] !== divisorMostSignificantDigit) { - quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); - } - // quotientDigit <= base - 1 - carry = 0; - borrow = 0; - l = divisor.length; - for (i = 0; i < l; i++) { - carry += quotientDigit * divisor[i]; - q = Math.floor(carry / base); - borrow += remainder[shift + i] - (carry - q * base); - carry = q; - if (borrow < 0) { - remainder[shift + i] = borrow + base; - borrow = -1; - } else { - remainder[shift + i] = borrow; - borrow = 0; + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while ((p = p.next)) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next; + else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; } + ++c; + } + list.length -= c; + return ret; } - while (borrow !== 0) { - quotientDigit -= 1; - carry = 0; - for (i = 0; i < l; i++) { - carry += remainder[shift + i] - base + divisor[i]; - if (carry < 0) { - remainder[shift + i] = carry + base; - carry = 0; - } else { - remainder[shift + i] = carry; - carry = 1; - } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = bufferShim.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while ((p = p.next)) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next; + else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; } - borrow += carry; + ++c; + } + list.length -= c; + return ret; } - result[shift] = quotientDigit; - } - // denormalization - remainder = divModSmall(remainder, lambda)[0]; - return [arrayToSmall(result), arrayToSmall(remainder)]; - } - function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ - // Performs faster than divMod1 on larger input sizes. - var a_l = a.length, - b_l = b.length, - result = [], - part = [], - base = BASE, - guess, xlen, highx, highy, check; - while (a_l) { - part.unshift(a[--a_l]); - if (compareAbs(part, b) < 0) { - result.push(0); - continue; + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } } - xlen = part.length; - highx = part[xlen - 1] * base + part[xlen - 2]; - highy = b[b_l - 1] * base + b[b_l - 2]; - if (xlen > b_l) { - highx = (highx + 1) * base; - } - guess = Math.ceil(highx / highy); - do { - check = multiplySmall(b, guess); - if (compareAbs(check, part) <= 0) break; - guess--; - } while (guess); - result.push(guess); - part = subtract(part, check); - } - result.reverse(); - return [arrayToSmall(result), arrayToSmall(part)]; - } - function divModSmall(value, lambda) { - var length = value.length, - quotient = createArray(length), - base = BASE, - i, q, remainder, divisor; - remainder = 0; - for (i = length - 1; i >= 0; --i) { - divisor = remainder * base + value[i]; - q = truncate(divisor / lambda); - remainder = divisor - q * lambda; - quotient[i] = q | 0; - } - return [quotient, remainder | 0]; - } + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit("end"); + } + } - function divModAny(self, v) { - var value, n = parseValue(v); - var a = self.value, b = n.value; - var quotient; - if (b === 0) throw new Error("Cannot divide by zero"); - if (self.isSmall) { - if (n.isSmall) { - return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } - return [Integer[0], self]; - } - if (n.isSmall) { - if (b === 1) return [self, Integer[0]]; - if (b == -1) return [self.negate(), Integer[0]]; - var abs = Math.abs(b); - if (abs < BASE) { - value = divModSmall(a, abs); - quotient = arrayToSmall(value[0]); - var remainder = value[1]; - if (self.sign) remainder = -remainder; - if (typeof quotient === "number") { - if (self.sign !== n.sign) quotient = -quotient; - return [new SmallInteger(quotient), new SmallInteger(remainder)]; - } - return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } - b = smallToArray(abs); + }.call(this, require("_process"))); + }, + { + "./_stream_duplex": 24, + "./internal/streams/BufferList": 29, + "./internal/streams/stream": 30, + _process: 22, + buffer: 5, + "buffer-shims": 4, + "core-util-is": 7, + events: 13, + inherits: 15, + isarray: 17, + "process-nextick-args": 21, + "string_decoder/": 31, + util: 3 } - var comparison = compareAbs(a, b); - if (comparison === -1) return [Integer[0], self]; - if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; - - // divMod1 is faster on smaller input sizes - if (a.length + b.length <= 200) - value = divMod1(a, b); - else value = divMod2(a, b); - - quotient = value[0]; - var qSign = self.sign !== n.sign, - mod = value[1], - mSign = self.sign; - if (typeof quotient === "number") { - if (qSign) quotient = -quotient; - quotient = new SmallInteger(quotient); - } else quotient = new BigInteger(quotient, qSign); - if (typeof mod === "number") { - if (mSign) mod = -mod; - mod = new SmallInteger(mod); - } else mod = new BigInteger(mod, mSign); - return [quotient, mod]; - } + ], + 27: [ + function(require, module, exports) { + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + "use strict"; + module.exports = Transform; + + var Duplex = require("./_stream_duplex"); + + /**/ + var util = require("core-util-is"); + util.inherits = require("inherits"); + /**/ + + util.inherits(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - BigInteger.prototype.divmod = function (v) { - var result = divModAny(this, v); - return { - quotient: result[0], - remainder: result[1] - }; - }; - SmallInteger.prototype.divmod = BigInteger.prototype.divmod; - - BigInteger.prototype.divide = function (v) { - return divModAny(this, v)[0]; - }; - SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; - - BigInteger.prototype.mod = function (v) { - return divModAny(this, v)[1]; - }; - SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; - - BigInteger.prototype.pow = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value, - value, x, y; - if (b === 0) return Integer[1]; - if (a === 0) return Integer[0]; - if (a === 1) return Integer[1]; - if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.sign) { - return Integer[0]; - } - if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); - if (this.isSmall) { - if (isPrecise(value = Math.pow(a, b))) - return new SmallInteger(truncate(value)); - } - x = this; - y = Integer[1]; - while (true) { - if (b & 1 === 1) { - y = y.times(x); - --b; - } - if (b === 0) break; - b /= 2; - x = x.square(); - } - return y; - }; - SmallInteger.prototype.pow = BigInteger.prototype.pow; - - BigInteger.prototype.modPow = function (exp, mod) { - exp = parseValue(exp); - mod = parseValue(mod); - if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); - var r = Integer[1], - base = this.mod(mod); - while (exp.isPositive()) { - if (base.isZero()) return Integer[0]; - if (exp.isOdd()) r = r.multiply(base).mod(mod); - exp = exp.divide(2); - base = base.square().mod(mod); - } - return r; - }; - SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } - function compareAbs(a, b) { - if (a.length !== b.length) { - return a.length > b.length ? 1 : -1; - } - for (var i = a.length - 1; i >= 0; i--) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; - } + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - BigInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) return 1; - return compareAbs(a, b); - }; - SmallInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = Math.abs(this.value), - b = n.value; - if (n.isSmall) { - b = Math.abs(b); - return a === b ? 0 : a > b ? 1 : -1; - } - return -1; - }; + var cb = ts.writecb; - BigInteger.prototype.compare = function (v) { - // See discussion about comparison with Infinity: - // https://github.com/peterolson/BigInteger.js/issues/61 - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } + if (!cb) + return stream.emit( + "error", + new Error("no writecb in Transform class") + ); - var n = parseValue(v), - a = this.value, - b = n.value; - if (this.sign !== n.sign) { - return n.sign ? 1 : -1; - } - if (n.isSmall) { - return this.sign ? -1 : 1; - } - return compareAbs(a, b) * (this.sign ? -1 : 1); - }; - BigInteger.prototype.compareTo = BigInteger.prototype.compare; + ts.writechunk = null; + ts.writecb = null; - SmallInteger.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } + if (data !== null && data !== undefined) stream.push(data); - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) { - return a == b ? 0 : a > b ? 1 : -1; - } - if (a < 0 !== n.sign) { - return a < 0 ? -1 : 1; - } - return a < 0 ? 1 : -1; - }; - SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; - - BigInteger.prototype.equals = function (v) { - return this.compare(v) === 0; - }; - SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; - - BigInteger.prototype.notEquals = function (v) { - return this.compare(v) !== 0; - }; - SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; - - BigInteger.prototype.greater = function (v) { - return this.compare(v) > 0; - }; - SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; - - BigInteger.prototype.lesser = function (v) { - return this.compare(v) < 0; - }; - SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; - - BigInteger.prototype.greaterOrEquals = function (v) { - return this.compare(v) >= 0; - }; - SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; - - BigInteger.prototype.lesserOrEquals = function (v) { - return this.compare(v) <= 0; - }; - SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; - - BigInteger.prototype.isEven = function () { - return (this.value[0] & 1) === 0; - }; - SmallInteger.prototype.isEven = function () { - return (this.value & 1) === 0; - }; - - BigInteger.prototype.isOdd = function () { - return (this.value[0] & 1) === 1; - }; - SmallInteger.prototype.isOdd = function () { - return (this.value & 1) === 1; - }; - - BigInteger.prototype.isPositive = function () { - return !this.sign; - }; - SmallInteger.prototype.isPositive = function () { - return this.value > 0; - }; - - BigInteger.prototype.isNegative = function () { - return this.sign; - }; - SmallInteger.prototype.isNegative = function () { - return this.value < 0; - }; - - BigInteger.prototype.isUnit = function () { - return false; - }; - SmallInteger.prototype.isUnit = function () { - return Math.abs(this.value) === 1; - }; - - BigInteger.prototype.isZero = function () { - return false; - }; - SmallInteger.prototype.isZero = function () { - return this.value === 0; - }; - BigInteger.prototype.isDivisibleBy = function (v) { - var n = parseValue(v); - var value = n.value; - if (value === 0) return false; - if (value === 1) return true; - if (value === 2) return this.isEven(); - return this.mod(n).equals(Integer[0]); - }; - SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; - - function isBasicPrime(v) { - var n = v.abs(); - if (n.isUnit()) return false; - if (n.equals(2) || n.equals(3) || n.equals(5)) return true; - if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; - if (n.lesser(25)) return true; - // we don't know if it's prime: let the other functions figure it out - } + cb(er); - BigInteger.prototype.isPrime = function () { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(), - nPrev = n.prev(); - var a = [2, 3, 5, 7, 11, 13, 17, 19], - b = nPrev, - d, t, i, x; - while (b.isEven()) b = b.divide(2); - for (i = 0; i < a.length; i++) { - x = bigInt(a[i]).modPow(b, n); - if (x.equals(Integer[1]) || x.equals(nPrev)) continue; - for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) { - x = x.square().mod(n); - if (x.equals(nPrev)) t = false; - } - if (t) return false; - } - return true; - }; - SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; - - BigInteger.prototype.isProbablePrime = function (iterations) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var t = iterations === undefined ? 5 : iterations; - // use the Fermat primality test - for (var i = 0; i < t; i++) { - var a = bigInt.randBetween(2, n.minus(2)); - if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite - } - return true; // large chance of being prime - }; - SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; - - BigInteger.prototype.modInv = function (n) { - var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; - while (!newR.equals(bigInt.zero)) { - q = r.divide(newR); - lastT = t; - lastR = r; - t = newT; - r = newR; - newT = lastT.subtract(q.multiply(newT)); - newR = lastR.subtract(q.multiply(newR)); - } - if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); - if (t.compare(0) === -1) { - t = t.add(n); - } - return t; - } - SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } - BigInteger.prototype.next = function () { - var value = this.value; - if (this.sign) { - return subtractSmall(value, 1, this.sign); - } - return new BigInteger(addSmall(value, 1), this.sign); - }; - SmallInteger.prototype.next = function () { - var value = this.value; - if (value + 1 < MAX_INT) return new SmallInteger(value + 1); - return new BigInteger(MAX_INT_ARR, false); - }; - - BigInteger.prototype.prev = function () { - var value = this.value; - if (this.sign) { - return new BigInteger(addSmall(value, 1), true); - } - return subtractSmall(value, 1, this.sign); - }; - SmallInteger.prototype.prev = function () { - var value = this.value; - if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); - return new BigInteger(MAX_INT_ARR, true); - }; - - var powersOfTwo = [1]; - while (powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); - var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; - - function shift_isSmall(n) { - return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) || - (n instanceof BigInteger && n.value.length <= 1); - } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - BigInteger.prototype.shiftLeft = function (n) { - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - n = +n; - if (n < 0) return this.shiftRight(-n); - var result = this; - while (n >= powers2Length) { - result = result.multiply(highestPower2); - n -= powers2Length - 1; - } - return result.multiply(powersOfTwo[n]); - }; - SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; - - BigInteger.prototype.shiftRight = function (n) { - var remQuo; - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - n = +n; - if (n < 0) return this.shiftLeft(-n); - var result = this; - while (n >= powers2Length) { - if (result.isZero()) return result; - remQuo = divModAny(result, highestPower2); - result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - n -= powers2Length - 1; - } - remQuo = divModAny(result, powersOfTwo[n]); - return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - }; - SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; - - function bitwise(x, y, fn) { - y = parseValue(y); - var xSign = x.isNegative(), ySign = y.isNegative(); - var xRem = xSign ? x.not() : x, - yRem = ySign ? y.not() : y; - var xBits = [], yBits = []; - var xStop = false, yStop = false; - while (!xStop || !yStop) { - if (xRem.isZero()) { // virtual sign extension for simulating two's complement - xStop = true; - xBits.push(xSign ? 1 : 0); - } - else if (xSign) xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers - else xBits.push(xRem.isEven() ? 0 : 1); - - if (yRem.isZero()) { - yStop = true; - yBits.push(ySign ? 1 : 0); - } - else if (ySign) yBits.push(yRem.isEven() ? 1 : 0); - else yBits.push(yRem.isEven() ? 0 : 1); - - xRem = xRem.over(2); - yRem = yRem.over(2); - } - var result = []; - for (var i = 0; i < xBits.length; i++) result.push(fn(xBits[i], yBits[i])); - var sum = bigInt(result.pop()).negate().times(bigInt(2).pow(result.length)); - while (result.length) { - sum = sum.add(bigInt(result.pop()).times(bigInt(2).pow(result.length))); - } - return sum; - } + Duplex.call(this, options); - BigInteger.prototype.not = function () { - return this.negate().prev(); - }; - SmallInteger.prototype.not = BigInteger.prototype.not; - - BigInteger.prototype.and = function (n) { - return bitwise(this, n, function (a, b) { return a & b; }); - }; - SmallInteger.prototype.and = BigInteger.prototype.and; - - BigInteger.prototype.or = function (n) { - return bitwise(this, n, function (a, b) { return a | b; }); - }; - SmallInteger.prototype.or = BigInteger.prototype.or; - - BigInteger.prototype.xor = function (n) { - return bitwise(this, n, function (a, b) { return a ^ b; }); - }; - SmallInteger.prototype.xor = BigInteger.prototype.xor; - - var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; - function roughLOB(n) { // get lowestOneBit (rough) - // SmallInteger: return Min(lowestOneBit(n), 1 << 30) - // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] - var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI; - return x & -x; - } + this._transformState = new TransformState(this); - function max(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.greater(b) ? a : b; - } - function min(a,b) { - a = parseValue(a); - b = parseValue(b); - return a.lesser(b) ? a : b; - } - function gcd(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - if (a.equals(b)) return a; - if (a.isZero()) return b; - if (b.isZero()) return a; - var c = Integer[1], d, t; - while (a.isEven() && b.isEven()) { - d = Math.min(roughLOB(a), roughLOB(b)); - a = a.divide(d); - b = b.divide(d); - c = c.multiply(d); - } - while (a.isEven()) { - a = a.divide(roughLOB(a)); - } - do { - while (b.isEven()) { - b = b.divide(roughLOB(b)); - } - if (a.greater(b)) { - t = b; b = a; a = t; - } - b = b.subtract(a); - } while (!b.isZero()); - return c.isUnit() ? a : a.multiply(c); - } - function lcm(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - return a.divide(gcd(a, b)).multiply(b); - } - function randBetween(a, b) { - a = parseValue(a); - b = parseValue(b); - var low = min(a, b), high = max(a, b); - var range = high.subtract(low); - if (range.isSmall) return low.add(Math.round(Math.random() * range)); - var length = range.value.length - 1; - var result = [], restricted = true; - for (var i = length; i >= 0; i--) { - var top = restricted ? range.value[i] : BASE; - var digit = truncate(Math.random() * top); - result.unshift(digit); - if (digit < top) restricted = false; - } - result = arrayToSmall(result); - return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false)); - } - var parseBase = function (text, base) { - var val = Integer[0], pow = Integer[1], - length = text.length; - if (2 <= base && base <= 36) { - if (length <= LOG_MAX_INT / Math.log(base)) { - return new SmallInteger(parseInt(text, base)); - } - } - base = parseValue(base); - var digits = []; - var i; - var isNegative = text[0] === "-"; - for (i = isNegative ? 1 : 0; i < text.length; i++) { - var c = text[i].toLowerCase(), - charCode = c.charCodeAt(0); - if (48 <= charCode && charCode <= 57) digits.push(parseValue(c)); - else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87)); - else if (c === "<") { - var start = i; - do { i++; } while (text[i] !== ">"); - digits.push(parseValue(text.slice(start + 1, i))); - } - else throw new Error(c + " is not a valid character"); - } - digits.reverse(); - for (i = 0; i < digits.length; i++) { - val = val.add(digits[i].times(pow)); - pow = pow.times(base); - } - return isNegative ? val.negate() : val; - }; - - function stringify(digit) { - var v = digit.value; - if (typeof v === "number") v = [v]; - if (v.length === 1 && v[0] <= 35) { - return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]); - } - return "<" + v + ">"; - } - function toBase(n, base) { - base = bigInt(base); - if (base.isZero()) { - if (n.isZero()) return "0"; - throw new Error("Cannot convert nonzero numbers to base 0."); - } - if (base.equals(-1)) { - if (n.isZero()) return "0"; - if (n.isNegative()) return new Array(1 - n).join("10"); - return "1" + new Array(+n).join("01"); - } - var minusSign = ""; - if (n.isNegative() && base.isPositive()) { - minusSign = "-"; - n = n.abs(); - } - if (base.equals(1)) { - if (n.isZero()) return "0"; - return minusSign + new Array(+n + 1).join(1); - } - var out = []; - var left = n, divmod; - while (left.isNegative() || left.compareAbs(base) >= 0) { - divmod = left.divmod(base); - left = divmod.quotient; - var digit = divmod.remainder; - if (digit.isNegative()) { - digit = base.minus(digit).abs(); - left = left.next(); - } - out.push(stringify(digit)); - } - out.push(stringify(left)); - return minusSign + out.reverse().join(""); - } + var stream = this; - BigInteger.prototype.toString = function (radix) { - if (radix === undefined) radix = 10; - if (radix !== 10) return toBase(this, radix); - var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; - while (--l >= 0) { - digit = String(v[l]); - str += zeros.slice(digit.length) + digit; - } - var sign = this.sign ? "-" : ""; - return sign + str; - }; - SmallInteger.prototype.toString = function (radix) { - if (radix === undefined) radix = 10; - if (radix != 10) return toBase(this, radix); - return String(this.value); - }; - - BigInteger.prototype.valueOf = function () { - return +this.toString(); - }; - BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; - - SmallInteger.prototype.valueOf = function () { - return this.value; - }; - SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - - function parseStringValue(v) { - if (isPrecise(+v)) { - var x = +v; - if (x === truncate(x)) - return new SmallInteger(x); - throw "Invalid integer: " + v; - } - var sign = v[0] === "-"; - if (sign) v = v.slice(1); - var split = v.split(/e/i); - if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); - if (split.length === 2) { - var exp = split[1]; - if (exp[0] === "+") exp = exp.slice(1); - exp = +exp; - if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); - var text = split[0]; - var decimalPlace = text.indexOf("."); - if (decimalPlace >= 0) { - exp -= text.length - decimalPlace - 1; - text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); - } - if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); - text += (new Array(exp + 1)).join("0"); - v = text; - } - var isValid = /^([0-9][0-9]*)$/.test(v); - if (!isValid) throw new Error("Invalid integer: " + v); - var r = [], max = v.length, l = LOG_BASE, min = max - l; - while (max > 0) { - r.push(+v.slice(min, max)); - min -= l; - if (min < 0) min = 0; - max -= l; - } - trim(r); - return new BigInteger(r, sign); - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - function parseNumberValue(v) { - if (isPrecise(v)) { - if (v !== truncate(v)) throw new Error(v + " is not an integer."); - return new SmallInteger(v); - } - return parseStringValue(v.toString()); - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - function parseValue(v) { - if (typeof v === "number") { - return parseNumberValue(v); - } - if (typeof v === "string") { - return parseStringValue(v); - } - return v; - } - // Pre-define numbers in range [-999,999] - for (var i = 0; i < 1000; i++) { - Integer[i] = new SmallInteger(i); - if (i > 0) Integer[-i] = new SmallInteger(-i); - } - // Backwards compatibility - Integer.one = Integer[1]; - Integer.zero = Integer[0]; - Integer.minusOne = Integer[-1]; - Integer.max = max; - Integer.min = min; - Integer.gcd = gcd; - Integer.lcm = lcm; - Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; }; - Integer.randBetween = randBetween; - return Integer; -})(); - -// Node.js check -if (typeof module !== "undefined" && module.hasOwnProperty("exports")) { - module.exports = bigInt; -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(50)(module))) - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {var Transform = __webpack_require__(6).Transform -var inherits = __webpack_require__(1) -var StringDecoder = __webpack_require__(14).StringDecoder -module.exports = CipherBase -inherits(CipherBase, Transform) -function CipherBase (hashMode) { - Transform.call(this) - this.hashMode = typeof hashMode === 'string' - if (this.hashMode) { - this[hashMode] = this._finalOrDigest - } else { - this.final = this._finalOrDigest - } - this._decoder = null - this._encoding = null -} -CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = new Buffer(data, inputEnc) - } - var outData = this._update(data) - if (this.hashMode) { - return this - } - if (outputEnc) { - outData = this._toString(outData, outputEnc) - } - return outData -} + if (options) { + if (typeof options.transform === "function") + this._transform = options.transform; -CipherBase.prototype.setAutoPadding = function () {} + if (typeof options.flush === "function") + this._flush = options.flush; + } -CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') -} + // When the writable side finishes, then flush out anything remaining. + this.once("prefinish", function() { + if (typeof this._flush === "function") + this._flush(function(er, data) { + done(stream, er, data); + }); + else done(stream); + }); + } -CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') -} + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error("_transform() is not implemented"); + }; + + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if ( + ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark + ) + this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform( + ts.writechunk, + ts.writeencoding, + ts.afterTransform + ); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; -CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') -} + function done(stream, er, data) { + if (er) return stream.emit("error", er); -CipherBase.prototype._transform = function (data, _, next) { - var err - try { - if (this.hashMode) { - this._update(data) - } else { - this.push(this._update(data)) - } - } catch (e) { - err = e - } finally { - next(err) - } -} -CipherBase.prototype._flush = function (done) { - var err - try { - this.push(this._final()) - } catch (e) { - err = e - } finally { - done(err) - } -} -CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this._final() || new Buffer('') - if (outputEnc) { - outData = this._toString(outData, outputEnc, true) - } - return outData -} + if (data !== null && data !== undefined) stream.push(data); -CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc) - this._encoding = enc - } - if (this._encoding !== enc) { - throw new Error('can\'t switch encodings') - } - var out = this._decoder.write(value) - if (fin) { - out += this._decoder.end() - } - return out -} + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) + if (ws.length) + throw new Error("Calling transform done when ws.length != 0"); -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { + if (ts.transforming) + throw new Error("Calling transform done when still transforming"); -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { -var inherits = __webpack_require__(1) -var md5 = __webpack_require__(31) -var rmd160 = __webpack_require__(42) -var sha = __webpack_require__(44) + return stream.push(null); + } + }, + { "./_stream_duplex": 24, "core-util-is": 7, inherits: 15 } + ], + 28: [ + function(require, module, exports) { + (function(process) { + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + "use strict"; + module.exports = Writable; + + /**/ + var processNextTick = require("process-nextick-args"); + /**/ + + /**/ + var asyncWrite = !process.browser && + ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 + ? setImmediate + : processNextTick; + /**/ + + /**/ + var Duplex; + /**/ + + Writable.WritableState = WritableState; + + /**/ + var util = require("core-util-is"); + util.inherits = require("inherits"); + /**/ + + /**/ + var internalUtil = { + deprecate: require("util-deprecate") + }; + /**/ -var Base = __webpack_require__(28) + /**/ + var Stream = require("./internal/streams/stream"); + /**/ -function HashNoConstructor(hash) { - Base.call(this, 'digest') + var Buffer = require("buffer").Buffer; + /**/ + var bufferShim = require("buffer-shims"); + /**/ - this._hash = hash - this.buffers = [] -} + util.inherits(Writable, Stream); -inherits(HashNoConstructor, Base) + function nop() {} -HashNoConstructor.prototype._update = function (data) { - this.buffers.push(data) -} + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } -HashNoConstructor.prototype._final = function () { - var buf = Buffer.concat(this.buffers) - var r = this._hash(buf) - this.buffers = null + function WritableState(options, stream) { + Duplex = Duplex || require("./_stream_duplex"); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = + this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || "utf8"; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } - return r -} + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; -function Hash(hash) { - Base.call(this, 'digest') + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer " + + "instead.") + }); + } catch (_) {} + })(); + + // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + var realHasInstance; + if ( + typeof Symbol === "function" && + Symbol.hasInstance && + typeof Function.prototype[Symbol.hasInstance] === "function" + ) { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function(object) { + if (realHasInstance.call(this, object)) return true; + + return ( + object && object._writableState instanceof WritableState + ); + } + }); + } else { + realHasInstance = function(object) { + return object instanceof this; + }; + } - this._hash = hash -} + function Writable(options) { + Duplex = Duplex || require("./_stream_duplex"); -inherits(Hash, Base) + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. -Hash.prototype._update = function (data) { - this._hash.update(data) -} + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if ( + !realHasInstance.call(Writable, this) && + !(this instanceof Duplex) + ) { + return new Writable(options); + } -Hash.prototype._final = function () { - return this._hash.digest() -} + this._writableState = new WritableState(options, this); -module.exports = function createHash (alg) { - alg = alg.toLowerCase() - if ('md5' === alg) return new HashNoConstructor(md5) - if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160) + // legacy. + this.writable = true; - return new Hash(sha(alg)) -} + if (options) { + if (typeof options.write === "function") + this._write = options.write; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) + if (typeof options.writev === "function") + this._writev = options.writev; + } -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { + Stream.call(this); + } -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { -var intSize = 4; -var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); -var chrsz = 8; + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit("error", new Error("Cannot pipe, not readable")); + }; -function toArray(buf, bigEndian) { - if ((buf.length % intSize) !== 0) { - var len = buf.length + (intSize - (buf.length % intSize)); - buf = Buffer.concat([buf, zeroBuffer], len); - } + function writeAfterEnd(stream, cb) { + var er = new Error("write after end"); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit("error", er); + processNextTick(cb, er); + } - var arr = []; - var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; - for (var i = 0; i < buf.length; i += intSize) { - arr.push(fn.call(buf, i)); - } - return arr; -} - -function toBuffer(arr, size, bigEndian) { - var buf = new Buffer(size); - var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; - for (var i = 0; i < arr.length; i++) { - fn.call(buf, arr[i], i * 4, true); - } - return buf; -} + // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError("May not write null values to stream"); + } else if ( + typeof chunk !== "string" && + chunk !== undefined && + !state.objectMode + ) { + er = new TypeError("Invalid non-string/buffer chunk"); + } + if (er) { + stream.emit("error", er); + processNextTick(cb, er); + valid = false; + } + return valid; + } -function hash(buf, fn, hashSize, bigEndian) { - if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); - var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); - return toBuffer(arr, hashSize, bigEndian); -} -exports.hash = hash; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = Buffer.isBuffer(chunk); -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } -"use strict"; + if (isBuf) encoding = "buffer"; + else if (!encoding) encoding = state.defaultEncoding; -/* - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ + if (typeof cb !== "function") cb = nop; -var helpers = __webpack_require__(30); + if (state.ended) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } -/* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ -function core_md5(x, len) -{ - /* append padding */ - x[len >> 5] |= 0x80 << ((len) % 32); - x[(((len + 64) >>> 9) << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for(var i = 0; i < x.length; i += 16) - { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); - d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); - c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); - b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); - a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); - d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); - c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); - b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); - a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); - d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); - c = md5_ff(c, d, a, b, x[i+10], 17, -42063); - b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); - a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); - d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); - c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); - b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); - - a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); - d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); - c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); - b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); - a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); - d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); - c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); - b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); - a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); - d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); - c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); - b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); - a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); - d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); - c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); - b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); - - a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); - d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); - c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); - b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); - a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); - d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); - c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); - b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); - a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); - d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); - c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); - b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); - a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); - d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); - c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); - b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); - - a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); - d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); - c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); - b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); - a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); - d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); - c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); - b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); - a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); - d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); - c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); - b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); - a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); - d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); - c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); - b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); - - a = safe_add(a, olda); - b = safe_add(b, oldb); - c = safe_add(c, oldc); - d = safe_add(d, oldd); - } - return Array(a, b, c, d); + return ret; + }; -} + Writable.prototype.cork = function() { + var state = this._writableState; -/* - * These functions implement the four basic operations the algorithm uses. - */ -function md5_cmn(q, a, b, x, s, t) -{ - return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); -} -function md5_ff(a, b, c, d, x, s, t) -{ - return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); -} -function md5_gg(a, b, c, d, x, s, t) -{ - return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); -} -function md5_hh(a, b, c, d, x, s, t) -{ - return md5_cmn(b ^ c ^ d, a, b, x, s, t); -} -function md5_ii(a, b, c, d, x, s, t) -{ - return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add(x, y) -{ - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -} - -/* - * Bitwise rotate a 32-bit number to the left. - */ -function bit_rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); -} - -module.exports = function md5(buf) { - return helpers.hash(buf, core_md5, 16); -}; - -/***/ }), -/* 32 */ -/***/ (function(module, exports) { - -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } + state.corked++; + }; - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } + Writable.prototype.uncork = function() { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if ( + !state.writing && + !state.corked && + !state.finished && + !state.bufferProcessing && + state.bufferedRequest + ) + clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding( + encoding + ) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === "string") + encoding = encoding.toLowerCase(); + if ( + !([ + "hex", + "utf8", + "utf-8", + "ascii", + "binary", + "base64", + "ucs2", + "ucs-2", + "utf16le", + "utf-16le", + "raw" + ].indexOf((encoding + "").toLowerCase()) > -1) + ) + throw new TypeError("Unknown encoding: " + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + function decodeChunk(state, chunk, encoding) { + if ( + !state.objectMode && + state.decodeStrings !== false && + typeof chunk === "string" + ) { + chunk = bufferShim.from(chunk, encoding); + } + return chunk; + } - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) encoding = "buffer"; + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - buffer[offset + i - d] |= s * 128 -} + return ret; + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite); + else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er); + else cb(er); -/* WEBPACK VAR INJECTION */(function(process, Buffer) {var createHmac = __webpack_require__(15) -var checkParameters = __webpack_require__(34) + stream._writableState.errorEmitted = true; + stream.emit("error", er); + } -exports.pbkdf2 = function (password, salt, iterations, keylen, digest, callback) { - if (typeof digest === 'function') { - callback = digest - digest = undefined - } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - checkParameters(iterations, keylen) - if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if ( + !finished && + !state.corked && + !state.bufferProcessing && + state.bufferedRequest + ) { + clearBuffer(stream, state); + } - setTimeout(function () { - callback(null, exports.pbkdf2Sync(password, salt, iterations, keylen, digest)) - }) -} + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } -var defaultEncoding -if (process.browser) { - defaultEncoding = 'utf-8' -} else { - var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } - defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' -} + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit("drain"); + } + } -exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { - if (!Buffer.isBuffer(password)) password = new Buffer(password, defaultEncoding) - if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, defaultEncoding) + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - checkParameters(iterations, keylen) + doWrite( + stream, + state, + true, + state.length, + buffer, + "", + holder.finish + ); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } - digest = digest || 'sha1' + if (entry === null) state.lastBufferedRequest = null; + } - var hLen - var l = 1 - var DK = new Buffer(keylen) - var block1 = new Buffer(salt.length + 4) - salt.copy(block1, 0, 0, salt.length) + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - var r - var T + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error("_write() is not implemented")); + }; - for (var i = 1; i <= l; i++) { - block1.writeUInt32BE(i, salt.length) - var U = createHmac(digest, password).update(block1).digest() + Writable.prototype._writev = null; - if (!hLen) { - hLen = U.length - T = new Buffer(hLen) - l = Math.ceil(keylen / hLen) - r = keylen - (l - 1) * hLen - } + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - U.copy(T, 0, 0, hLen) + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } - for (var j = 1; j < iterations; j++) { - U = createHmac(digest, password).update(U).digest() - for (var k = 0; k < hLen; k++) T[k] ^= U[k] - } + if (chunk !== null && chunk !== undefined) + this.write(chunk, encoding); - var destPos = (i - 1) * hLen - var len = (i === l ? r : hLen) - T.copy(DK, destPos, 0, len) - } + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - return DK -} + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); + }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(0).Buffer)) + function needFinish(state) { + return ( + state.ending && + state.length === 0 && + state.bufferedRequest === null && + !state.finished && + !state.writing + ); + } -/***/ }), -/* 34 */ -/***/ (function(module, exports) { + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit("prefinish"); + } + } -var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs -module.exports = function (iterations, keylen) { - if (typeof iterations !== 'number') { - throw new TypeError('Iterations not a number') - } + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit("finish"); + } else { + prefinish(stream, state); + } + } + return need; + } - if (iterations < 0) { - throw new TypeError('Bad iterations') - } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb); + else stream.once("finish", cb); + } + state.ended = true; + stream.writable = false; + } - if (typeof keylen !== 'number') { - throw new TypeError('Key length not a number') - } + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function(err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + }.call(this, require("_process"))); + }, + { + "./_stream_duplex": 24, + "./internal/streams/stream": 30, + _process: 22, + buffer: 5, + "buffer-shims": 4, + "core-util-is": 7, + inherits: 15, + "process-nextick-args": 21, + "util-deprecate": 47 + } + ], + 29: [ + function(require, module, exports) { + "use strict"; + var Buffer = require("buffer").Buffer; + /**/ + var bufferShim = require("buffer-shims"); + /**/ + + module.exports = BufferList; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } - if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ - throw new TypeError('Bad key length') - } -} - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global, setImmediate) { - -var PENDING = 'pending'; -var SETTLED = 'settled'; -var FULFILLED = 'fulfilled'; -var REJECTED = 'rejected'; -var NOOP = function () {}; -var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function'; - -var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; -var asyncQueue = []; -var asyncTimer; - -function asyncFlush() { - // run promise callbacks - for (var i = 0; i < asyncQueue.length; i++) { - asyncQueue[i][0](asyncQueue[i][1]); - } - - // reset async asyncQueue - asyncQueue = []; - asyncTimer = false; -} - -function asyncCall(callback, arg) { - asyncQueue.push([callback, arg]); - - if (!asyncTimer) { - asyncTimer = true; - asyncSetTimer(asyncFlush, 0); - } -} - -function invokeResolver(resolver, promise) { - function resolvePromise(value) { - resolve(promise, value); - } - - function rejectPromise(reason) { - reject(promise, reason); - } - - try { - resolver(resolvePromise, rejectPromise); - } catch (e) { - rejectPromise(e); - } -} - -function invokeCallback(subscriber) { - var owner = subscriber.owner; - var settled = owner._state; - var value = owner._data; - var callback = subscriber[settled]; - var promise = subscriber.then; - - if (typeof callback === 'function') { - settled = FULFILLED; - try { - value = callback(value); - } catch (e) { - reject(promise, e); - } - } - - if (!handleThenable(promise, value)) { - if (settled === FULFILLED) { - resolve(promise, value); - } - - if (settled === REJECTED) { - reject(promise, value); - } - } -} - -function handleThenable(promise, value) { - var resolved; - - try { - if (promise === value) { - throw new TypeError('A promises callback cannot return that same promise.'); - } - - if (value && (typeof value === 'function' || typeof value === 'object')) { - // then should be retrieved only once - var then = value.then; - - if (typeof then === 'function') { - then.call(value, function (val) { - if (!resolved) { - resolved = true; - - if (value === val) { - fulfill(promise, val); - } else { - resolve(promise, val); - } - } - }, function (reason) { - if (!resolved) { - resolved = true; - - reject(promise, reason); - } - }); - - return true; - } - } - } catch (e) { - if (!resolved) { - reject(promise, e); - } - - return true; - } - - return false; -} - -function resolve(promise, value) { - if (promise === value || !handleThenable(promise, value)) { - fulfill(promise, value); - } -} - -function fulfill(promise, value) { - if (promise._state === PENDING) { - promise._state = SETTLED; - promise._data = value; - - asyncCall(publishFulfillment, promise); - } -} - -function reject(promise, reason) { - if (promise._state === PENDING) { - promise._state = SETTLED; - promise._data = reason; - - asyncCall(publishRejection, promise); - } -} - -function publish(promise) { - promise._then = promise._then.forEach(invokeCallback); -} - -function publishFulfillment(promise) { - promise._state = FULFILLED; - publish(promise); -} - -function publishRejection(promise) { - promise._state = REJECTED; - publish(promise); - if (!promise._handled && isNode) { - global.process.emit('unhandledRejection', promise._data, promise); - } -} - -function notifyRejectionHandled(promise) { - global.process.emit('rejectionHandled', promise); -} - -/** - * @class - */ -function Promise(resolver) { - if (typeof resolver !== 'function') { - throw new TypeError('Promise resolver ' + resolver + ' is not a function'); - } - - if (this instanceof Promise === false) { - throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); - } - - this._then = []; - - invokeResolver(resolver, this); -} - -Promise.prototype = { - constructor: Promise, - - _state: PENDING, - _then: null, - _data: undefined, - _handled: false, - - then: function (onFulfillment, onRejection) { - var subscriber = { - owner: this, - then: new this.constructor(NOOP), - fulfilled: onFulfillment, - rejected: onRejection - }; - - if ((onRejection || onFulfillment) && !this._handled) { - this._handled = true; - if (this._state === REJECTED && isNode) { - asyncCall(notifyRejectionHandled, this); - } - } - - if (this._state === FULFILLED || this._state === REJECTED) { - // already resolved, call callback async - asyncCall(invokeCallback, subscriber); - } else { - // subscribe - this._then.push(subscriber); - } - - return subscriber.then; - }, - - catch: function (onRejection) { - return this.then(null, onRejection); - } -}; - -Promise.all = function (promises) { - if (!Array.isArray(promises)) { - throw new TypeError('You must pass an array to Promise.all().'); - } - - return new Promise(function (resolve, reject) { - var results = []; - var remaining = 0; - - function resolver(index) { - remaining++; - return function (value) { - results[index] = value; - if (!--remaining) { - resolve(results); - } - }; - } - - for (var i = 0, promise; i < promises.length; i++) { - promise = promises[i]; - - if (promise && typeof promise.then === 'function') { - promise.then(resolver(i), reject); - } else { - results[i] = promise; - } - } - - if (!remaining) { - resolve(results); - } - }); -}; - -Promise.race = function (promises) { - if (!Array.isArray(promises)) { - throw new TypeError('You must pass an array to Promise.race().'); - } - - return new Promise(function (resolve, reject) { - for (var i = 0, promise; i < promises.length; i++) { - promise = promises[i]; - - if (promise && typeof promise.then === 'function') { - promise.then(resolve, reject); - } else { - resolve(promise); - } - } - }); -}; - -Promise.resolve = function (value) { - if (value && typeof value === 'object' && value.constructor === Promise) { - return value; - } - - return new Promise(function (resolve) { - resolve(value); - }); -}; - -Promise.reject = function (reason) { - return new Promise(function (resolve, reject) { - reject(reason); - }); -}; - -module.exports = Promise; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(17).setImmediate)) - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(2) - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Buffer = __webpack_require__(0).Buffer; -/**/ -var bufferShim = __webpack_require__(10); -/**/ - -module.exports = BufferList; - -function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; -} - -BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; -}; - -BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; -}; - -BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; -}; - -BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; -}; - -BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; -}; - -BufferList.prototype.concat = function (n) { - if (this.length === 0) return bufferShim.alloc(0); - if (this.length === 1) return this.head.data; - var ret = bufferShim.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; -}; + BufferList.prototype.push = function(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while ((p = p.next)) { + ret += s + p.data; + } + return ret; + }; + + BufferList.prototype.concat = function(n) { + if (this.length === 0) return bufferShim.alloc(0); + if (this.length === 1) return this.head.data; + var ret = bufferShim.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + }, + { buffer: 5, "buffer-shims": 4 } + ], + 30: [ + function(require, module, exports) { + module.exports = require("events").EventEmitter; + }, + { events: 13 } + ], + 31: [ + function(require, module, exports) { + "use strict"; + var Buffer = require("buffer").Buffer; + var bufferShim = require("buffer-shims"); + + var isEncoding = + Buffer.isEncoding || + function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { + function _normalizeEncoding(enc) { + if (!enc) return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) return; // undefined + enc = ("" + enc).toLowerCase(); + retried = true; + } + } + } -module.exports = __webpack_require__(19) + // Do not cache `Buffer.isEncoding` when checking encoding names as some + // modules monkey-patch it to support additional encodings + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if ( + typeof nenc !== "string" && + (Buffer.isEncoding === isEncoding || !isEncoding(enc)) + ) + throw new Error("Unknown encoding: " + enc); + return nenc || enc; + } + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + exports.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = bufferShim.allocUnsafe(nb); + } -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) return ""; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ""; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) + return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ""; + }; + + StringDecoder.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy( + this.lastChar, + this.lastTotal - this.lastNeed, + 0, + this.lastNeed + ); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy( + this.lastChar, + this.lastTotal - this.lastNeed, + 0, + buf.length + ); + this.lastNeed -= buf.length; + }; + + // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a + // continuation byte. + function utf8CheckByte(byte) { + if (byte <= 0x7f) return 0; + else if (byte >> 5 === 0x06) return 2; + else if (byte >> 4 === 0x0e) return 3; + else if (byte >> 3 === 0x1e) return 4; + return -1; + } -/* WEBPACK VAR INJECTION */(function(process) {var Stream = (function (){ - try { - return __webpack_require__(6); // hack to fix a circular dependency issue when used with browserify - } catch(_){} -}()); -exports = module.exports = __webpack_require__(20); -exports.Stream = Stream || exports; -exports.Readable = exports; -exports.Writable = __webpack_require__(13); -exports.Duplex = __webpack_require__(2); -exports.Transform = __webpack_require__(12); -exports.PassThrough = __webpack_require__(19); + // Checks at most 3 bytes at the end of a Buffer in order to detect an + // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) + // needed to complete the UTF-8 character (if applicable) are returned. + function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0; + else self.lastNeed = nb - 3; + } + return nb; + } + return 0; + } -if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; -} + // Validates as many continuation bytes for a multi-byte UTF-8 character as + // needed or are available. If we see a non-continuation byte where we expect + // one, we "replace" the validated continuation bytes we've seen so far with + // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding + // behavior. The continuation byte check is included three times in the case + // where all of the continuation bytes for a character exist in the same buffer. + // It is also done this way as a slight performance increase instead of using a + // loop. + function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xc0) !== 0x80) { + self.lastNeed = 0; + return "\ufffd".repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xc0) !== 0x80) { + self.lastNeed = 1; + return "\ufffd".repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xc0) !== 0x80) { + self.lastNeed = 2; + return "\ufffd".repeat(p + 2); + } + } + } + } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) + // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { + // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a + // partial character, the character's bytes are buffered until the required + // number of bytes are available. + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString("utf8", i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i, end); + } -module.exports = __webpack_require__(12) + // For UTF-8, a replacement character for each buffered byte of a (partial) + // character needs to be added to the output. + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) + return r + "\ufffd".repeat(this.lastTotal - this.lastNeed); + return r; + } + // UTF-16LE typically needs two bytes per character, but even if we have an even + // number of bytes available, we need to check if we end on a leading/high + // surrogate. In that case, we need to wait for the next two bytes in order to + // decode the last character properly. + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString("utf16le", i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xd800 && c <= 0xdbff) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i, buf.length - 1); + } -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { + // For UTF-16LE we do not explicitly append special replacement characters if we + // end on a partial character, we simply let v8 handle that. + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); + } + return r; + } -module.exports = __webpack_require__(13) + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString("base64", i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i, buf.length - n); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) + return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } -/* WEBPACK VAR INJECTION */(function(Buffer) {/* + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + }, + { buffer: 5, "buffer-shims": 4 } + ], + 32: [ + function(require, module, exports) { + module.exports = require("./readable").PassThrough; + }, + { "./readable": 33 } + ], + 33: [ + function(require, module, exports) { + exports = module.exports = require("./lib/_stream_readable.js"); + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = require("./lib/_stream_writable.js"); + exports.Duplex = require("./lib/_stream_duplex.js"); + exports.Transform = require("./lib/_stream_transform.js"); + exports.PassThrough = require("./lib/_stream_passthrough.js"); + }, + { + "./lib/_stream_duplex.js": 24, + "./lib/_stream_passthrough.js": 25, + "./lib/_stream_readable.js": 26, + "./lib/_stream_transform.js": 27, + "./lib/_stream_writable.js": 28 + } + ], + 34: [ + function(require, module, exports) { + module.exports = require("./readable").Transform; + }, + { "./readable": 33 } + ], + 35: [ + function(require, module, exports) { + module.exports = require("./lib/_stream_writable.js"); + }, + { "./lib/_stream_writable.js": 28 } + ], + 36: [ + function(require, module, exports) { + (function(Buffer) { + /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ -/** @preserve + /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -8191,755 +9466,1965 @@ Redistribution and use in source and binary forms, with or without modification, THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -// constants table -var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -] - -var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -] - -var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -] - -var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -] - -var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] -var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] - -function bytesToWords (bytes) { - var words = [] - for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { - words[b >>> 5] |= bytes[i] << (24 - b % 32) - } - return words -} + // constants table + var zl = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 7, + 4, + 13, + 1, + 10, + 6, + 15, + 3, + 12, + 0, + 9, + 5, + 2, + 14, + 11, + 8, + 3, + 10, + 14, + 4, + 9, + 15, + 8, + 1, + 2, + 7, + 0, + 6, + 13, + 11, + 5, + 12, + 1, + 9, + 11, + 10, + 0, + 8, + 12, + 4, + 13, + 3, + 7, + 15, + 14, + 5, + 6, + 2, + 4, + 0, + 5, + 9, + 7, + 12, + 2, + 10, + 14, + 1, + 3, + 8, + 11, + 6, + 15, + 13 + ]; + + var zr = [ + 5, + 14, + 7, + 0, + 9, + 2, + 11, + 4, + 13, + 6, + 15, + 8, + 1, + 10, + 3, + 12, + 6, + 11, + 3, + 7, + 0, + 13, + 5, + 10, + 14, + 15, + 8, + 12, + 4, + 9, + 1, + 2, + 15, + 5, + 1, + 3, + 7, + 14, + 6, + 9, + 11, + 8, + 12, + 2, + 10, + 0, + 4, + 13, + 8, + 6, + 4, + 1, + 3, + 11, + 15, + 0, + 5, + 12, + 2, + 13, + 9, + 7, + 10, + 14, + 12, + 15, + 10, + 4, + 1, + 5, + 8, + 7, + 6, + 2, + 13, + 14, + 0, + 3, + 9, + 11 + ]; + + var sl = [ + 11, + 14, + 15, + 12, + 5, + 8, + 7, + 9, + 11, + 13, + 14, + 15, + 6, + 7, + 9, + 8, + 7, + 6, + 8, + 13, + 11, + 9, + 7, + 15, + 7, + 12, + 15, + 9, + 11, + 7, + 13, + 12, + 11, + 13, + 6, + 7, + 14, + 9, + 13, + 15, + 14, + 8, + 13, + 6, + 5, + 12, + 7, + 5, + 11, + 12, + 14, + 15, + 14, + 15, + 9, + 8, + 9, + 14, + 5, + 6, + 8, + 6, + 5, + 12, + 9, + 15, + 5, + 11, + 6, + 8, + 13, + 12, + 5, + 12, + 13, + 14, + 11, + 8, + 5, + 6 + ]; + + var sr = [ + 8, + 9, + 9, + 11, + 13, + 15, + 15, + 5, + 7, + 7, + 8, + 11, + 14, + 14, + 12, + 6, + 9, + 13, + 15, + 7, + 12, + 8, + 9, + 11, + 7, + 7, + 12, + 7, + 6, + 15, + 13, + 11, + 9, + 7, + 15, + 11, + 8, + 6, + 6, + 14, + 12, + 13, + 5, + 14, + 13, + 13, + 7, + 5, + 15, + 5, + 8, + 11, + 14, + 14, + 6, + 14, + 6, + 9, + 12, + 9, + 12, + 5, + 15, + 8, + 8, + 5, + 12, + 9, + 12, + 5, + 14, + 6, + 8, + 13, + 6, + 5, + 15, + 13, + 11, + 11 + ]; + + var hl = [ + 0x00000000, + 0x5a827999, + 0x6ed9eba1, + 0x8f1bbcdc, + 0xa953fd4e + ]; + var hr = [ + 0x50a28be6, + 0x5c4dd124, + 0x6d703ef3, + 0x7a6d76e9, + 0x00000000 + ]; + + function bytesToWords(bytes) { + var words = []; + for (var i = 0, b = 0; i < bytes.length; i++, (b += 8)) { + words[b >>> 5] |= bytes[i] << (24 - b % 32); + } + return words; + } -function wordsToBytes (words) { - var bytes = [] - for (var b = 0; b < words.length * 32; b += 8) { - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) - } - return bytes -} - -function processBlock (H, M, offset) { - // swap endian - for (var i = 0; i < 16; i++) { - var offset_i = offset + i - var M_offset_i = M[offset_i] - - // Swap - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ) - } + function wordsToBytes(words) { + var bytes = []; + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xff); + } + return bytes; + } - // Working variables - var al, bl, cl, dl, el - var ar, br, cr, dr, er - - ar = al = H[0] - br = bl = H[1] - cr = cl = H[2] - dr = dl = H[3] - er = el = H[4] - - // computation - var t - for (i = 0; i < 80; i += 1) { - t = (al + M[offset + zl[i]]) | 0 - if (i < 16) { - t += f1(bl, cl, dl) + hl[0] - } else if (i < 32) { - t += f2(bl, cl, dl) + hl[1] - } else if (i < 48) { - t += f3(bl, cl, dl) + hl[2] - } else if (i < 64) { - t += f4(bl, cl, dl) + hl[3] - } else {// if (i<80) { - t += f5(bl, cl, dl) + hl[4] - } - t = t | 0 - t = rotl(t, sl[i]) - t = (t + el) | 0 - al = el - el = dl - dl = rotl(cl, 10) - cl = bl - bl = t - - t = (ar + M[offset + zr[i]]) | 0 - if (i < 16) { - t += f5(br, cr, dr) + hr[0] - } else if (i < 32) { - t += f4(br, cr, dr) + hr[1] - } else if (i < 48) { - t += f3(br, cr, dr) + hr[2] - } else if (i < 64) { - t += f2(br, cr, dr) + hr[3] - } else {// if (i<80) { - t += f1(br, cr, dr) + hr[4] - } + function processBlock(H, M, offset) { + // swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00); + } + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + + // computation + var t; + for (i = 0; i < 80; i += 1) { + t = (al + M[offset + zl[i]]) | 0; + if (i < 16) { + t += f1(bl, cl, dl) + hl[0]; + } else if (i < 32) { + t += f2(bl, cl, dl) + hl[1]; + } else if (i < 48) { + t += f3(bl, cl, dl) + hl[2]; + } else if (i < 64) { + t += f4(bl, cl, dl) + hl[3]; + } else { + // if (i<80) { + t += f5(bl, cl, dl) + hl[4]; + } + t = t | 0; + t = rotl(t, sl[i]); + t = (t + el) | 0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset + zr[i]]) | 0; + if (i < 16) { + t += f5(br, cr, dr) + hr[0]; + } else if (i < 32) { + t += f4(br, cr, dr) + hr[1]; + } else if (i < 48) { + t += f3(br, cr, dr) + hr[2]; + } else if (i < 64) { + t += f2(br, cr, dr) + hr[3]; + } else { + // if (i<80) { + t += f1(br, cr, dr) + hr[4]; + } - t = t | 0 - t = rotl(t, sr[i]) - t = (t + er) | 0 - ar = er - er = dr - dr = rotl(cr, 10) - cr = br - br = t - } + t = t | 0; + t = rotl(t, sr[i]); + t = (t + er) | 0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + + // intermediate hash value + t = (H[1] + cl + dr) | 0; + H[1] = (H[2] + dl + er) | 0; + H[2] = (H[3] + el + ar) | 0; + H[3] = (H[4] + al + br) | 0; + H[4] = (H[0] + bl + cr) | 0; + H[0] = t; + } - // intermediate hash value - t = (H[1] + cl + dr) | 0 - H[1] = (H[2] + dl + er) | 0 - H[2] = (H[3] + el + ar) | 0 - H[3] = (H[4] + al + br) | 0 - H[4] = (H[0] + bl + cr) | 0 - H[0] = t -} + function f1(x, y, z) { + return x ^ y ^ z; + } -function f1 (x, y, z) { - return ((x) ^ (y) ^ (z)) -} + function f2(x, y, z) { + return (x & y) | (~x & z); + } -function f2 (x, y, z) { - return (((x) & (y)) | ((~x) & (z))) -} + function f3(x, y, z) { + return (x | ~y) ^ z; + } -function f3 (x, y, z) { - return (((x) | (~(y))) ^ (z)) -} + function f4(x, y, z) { + return (x & z) | (y & ~z); + } -function f4 (x, y, z) { - return (((x) & (z)) | ((y) & (~(z)))) -} + function f5(x, y, z) { + return x ^ (y | ~z); + } -function f5 (x, y, z) { - return ((x) ^ ((y) | (~(z)))) -} + function rotl(x, n) { + return (x << n) | (x >>> (32 - n)); + } -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} + function ripemd160(message) { + var H = [ + 0x67452301, + 0xefcdab89, + 0x98badcfe, + 0x10325476, + 0xc3d2e1f0 + ]; + + if (typeof message === "string") { + message = new Buffer(message, "utf8"); + } + + var m = bytesToWords(message); + + var nBitsLeft = message.length * 8; + var nBitsTotal = message.length * 8; + + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + m[((nBitsLeft + 64) >>> 9 << 4) + 14] = + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00); + + for (var i = 0; i < m.length; i += 16) { + processBlock(H, m, i); + } + + // swap endian + for (i = 0; i < 5; i++) { + // shortcut + var H_i = H[i]; + + // Swap + H[i] = + (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + var digestbytes = wordsToBytes(H); + return new Buffer(digestbytes); + } -function ripemd160 (message) { - var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] + module.exports = ripemd160; + }.call(this, require("buffer").Buffer)); + }, + { buffer: 5 } + ], + 37: [ + function(require, module, exports) { + (function(Buffer) { + // prototype class for hash functions + function Hash(blockSize, finalSize) { + this._block = new Buffer(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + this._s = 0; + } - if (typeof message === 'string') { - message = new Buffer(message, 'utf8') - } + Hash.prototype.update = function(data, enc) { + if (typeof data === "string") { + enc = enc || "utf8"; + data = new Buffer(data, enc); + } + + var l = (this._len += data.length); + var s = this._s || 0; + var f = 0; + var buffer = this._block; + + while (s < l) { + var t = Math.min( + data.length, + f + this._blockSize - s % this._blockSize + ); + var ch = t - f; + + for (var i = 0; i < ch; i++) { + buffer[s % this._blockSize + i] = data[i + f]; + } - var m = bytesToWords(message) + s += ch; + f += ch; - var nBitsLeft = message.length * 8 - var nBitsTotal = message.length * 8 + if (s % this._blockSize === 0) { + this._update(buffer); + } + } + this._s = s; - // Add padding - m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) - m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | - (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) - ) + return this; + }; - for (var i = 0; i < m.length; i += 16) { - processBlock(H, m, i) - } + Hash.prototype.digest = function(enc) { + // Suppose the length of the message M, in bits, is l + var l = this._len * 8; - // swap endian - for (i = 0; i < 5; i++) { - // shortcut - var H_i = H[i] + // Append the bit 1 to the end of the message + this._block[this._len % this._blockSize] = 0x80; - // Swap - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00) - } + // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize + this._block.fill(0, this._len % this._blockSize + 1); - var digestbytes = wordsToBytes(H) - return new Buffer(digestbytes) -} + if (l % (this._blockSize * 8) >= this._finalSize * 8) { + this._update(this._block); + this._block.fill(0); + } -module.exports = ripemd160 + // to this append the block which is equal to the number l written in binary + // TODO: handle case where l is > Math.pow(2, 29) + this._block.writeInt32BE(l, this._blockSize - 4); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) + var hash = this._update(this._block) || this._hash(); -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { + return enc ? hash.toString(enc) : hash; + }; -/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { - "use strict"; + Hash.prototype._update = function() { + throw new Error("_update must be implemented by subclass"); + }; - if (global.setImmediate) { - return; - } + module.exports = Hash; + }.call(this, require("buffer").Buffer)); + }, + { buffer: 5 } + ], + 38: [ + function(require, module, exports) { + var exports = (module.exports = function SHA(algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports[algorithm]; + if (!Algorithm) + throw new Error( + algorithm + " is not supported (we accept pull requests)" + ); + + return new Algorithm(); + }); + + exports.sha = require("./sha"); + exports.sha1 = require("./sha1"); + exports.sha224 = require("./sha224"); + exports.sha256 = require("./sha256"); + exports.sha384 = require("./sha384"); + exports.sha512 = require("./sha512"); + }, + { + "./sha": 39, + "./sha1": 40, + "./sha224": 41, + "./sha256": 42, + "./sha384": 43, + "./sha512": 44 + } + ], + 39: [ + function(require, module, exports) { + (function(Buffer) { + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - var nextHandle = 1; // Spec says greater than zero - var tasksByHandle = {}; - var currentlyRunningATask = false; - var doc = global.document; - var registerImmediate; + var inherits = require("inherits"); + var Hash = require("./hash"); - function setImmediate(callback) { - // Callback can either be a function or a string - if (typeof callback !== "function") { - callback = new Function("" + callback); - } - // Copy function arguments - var args = new Array(arguments.length - 1); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 1]; - } - // Store and register the task - var task = { callback: callback, args: args }; - tasksByHandle[nextHandle] = task; - registerImmediate(nextHandle); - return nextHandle++; - } + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]; - function clearImmediate(handle) { - delete tasksByHandle[handle]; - } + var W = new Array(80); - function run(task) { - var callback = task.callback; - var args = task.args; - switch (args.length) { - case 0: - callback(); - break; - case 1: - callback(args[0]); - break; - case 2: - callback(args[0], args[1]); - break; - case 3: - callback(args[0], args[1], args[2]); - break; - default: - callback.apply(undefined, args); - break; - } - } + function Sha() { + this.init(); + this._w = W; - function runIfPresent(handle) { - // From the spec: "Wait until any invocations of this algorithm started before this one have completed." - // So if we're currently running a task, we'll need to delay this invocation. - if (currentlyRunningATask) { - // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a - // "too much recursion" error. - setTimeout(runIfPresent, 0, handle); - } else { - var task = tasksByHandle[handle]; - if (task) { - currentlyRunningATask = true; - try { - run(task); - } finally { - clearImmediate(handle); - currentlyRunningATask = false; - } + Hash.call(this, 64, 56); } - } - } - function installNextTickImplementation() { - registerImmediate = function(handle) { - process.nextTick(function () { runIfPresent(handle); }); - }; - } + inherits(Sha, Hash); - function canUsePostMessage() { - // The test against `importScripts` prevents this implementation from being installed inside a web worker, - // where `global.postMessage` means something completely different and can't be used for this purpose. - if (global.postMessage && !global.importScripts) { - var postMessageIsAsynchronous = true; - var oldOnMessage = global.onmessage; - global.onmessage = function() { - postMessageIsAsynchronous = false; - }; - global.postMessage("", "*"); - global.onmessage = oldOnMessage; - return postMessageIsAsynchronous; - } - } + Sha.prototype.init = function() { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - function installPostMessageImplementation() { - // Installs an event handler on `global` for the `message` event: see - // * https://developer.mozilla.org/en/DOM/window.postMessage - // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + return this; + }; - var messagePrefix = "setImmediate$" + Math.random() + "$"; - var onGlobalMessage = function(event) { - if (event.source === global && - typeof event.data === "string" && - event.data.indexOf(messagePrefix) === 0) { - runIfPresent(+event.data.slice(messagePrefix.length)); + function rotl5(num) { + return (num << 5) | (num >>> 27); } - }; - if (global.addEventListener) { - global.addEventListener("message", onGlobalMessage, false); - } else { - global.attachEvent("onmessage", onGlobalMessage); - } + function rotl30(num) { + return (num << 30) | (num >>> 2); + } - registerImmediate = function(handle) { - global.postMessage(messagePrefix + handle, "*"); - }; - } + function ft(s, b, c, d) { + if (s === 0) return (b & c) | (~b & d); + if (s === 2) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; + } - function installMessageChannelImplementation() { - var channel = new MessageChannel(); - channel.port1.onmessage = function(event) { - var handle = event.data; - runIfPresent(handle); - }; + Sha.prototype._update = function(M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) + W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) + W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0; + + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - registerImmediate = function(handle) { - channel.port2.postMessage(handle); - }; - } + Sha.prototype._hash = function() { + var H = new Buffer(20); - function installReadyStateChangeImplementation() { - var html = doc.documentElement; - registerImmediate = function(handle) { - // Create a + + + + + diff --git a/example/lesspass.html b/example/lesspass.html deleted file mode 100644 index 25320c5..0000000 --- a/example/lesspass.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - diff --git a/package.json b/package.json index 9bae031..271bee0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "6.0.0", + "version": "6.1.0", "description": "LessPass node module used to generate LessPass passwords", "keywords": [ "crypto", @@ -17,35 +17,38 @@ "module": "src/lesspass.js", "repository": "lesspass/core", "scripts": { - "precommit": "npm test", - "prepush": "npm test", - "dev": "webpack", - "build": "rimraf dist && npm run build:min", - "build:min": "cross-env NODE_ENV=production webpack -p", - "prepublish": "npm run build", - "test": "mocha tests/*", - "test:node": "npm run build && cd tests && node node.js && cd ..", - "test:browser": "npm run build && karma start tests/karma.config.js" + "precommit": "npm test && lint-staged", + "prettier": "prettier --write \"{src,test}/**/*.js\"", + "clean": "rm -rf dist && mkdir dist && npm prune", + "build": "npm run clean && browserify --standalone LessPass src/lesspass.js > dist/lesspass.js", + "test": "npm run test:unit && npm run test:browser", + "test:unit": "mocha test --recursive", + "test:browser": "npm run build && karma start test/karma.conf.js" }, "dependencies": { - "big-integer": "^1.6.17", + "big-integer": "^1.6.22", + "buffer": "^5.0.6", "create-hmac": "^1.1.4", - "object-assign": "^4.1.0", - "pbkdf2": "^3.0.9", - "pinkie-promise": "^2.0.1" + "es6-promise": "^4.1.0", + "lodash.assign": "^4.2.0", + "pbkdf2": "^3.0.9" }, "devDependencies": { - "babel-core": "^6.22.1", - "babel-loader": "^6.2.10", - "chai": "^3.5.0", - "cross-env": "^3.1.4", - "husky": "^0.13.2", - "karma": "^1.3.0", - "karma-chai": "^0.1.0", - "karma-firefox-launcher": "^1.0.0", + "browserify": "^14.3.0", + "husky": "^0.13.3", + "karma": "^1.6.0", + "karma-browserify": "^5.1.1", + "karma-chrome-launcher": "^2.0.0", + "karma-firefox-launcher": "^1.0.1", "karma-mocha": "^1.3.0", - "mocha": "^3.1.2", - "rimraf": "^2.5.4", - "webpack": "^2.2.1" + "lint-staged": "^3.4.1", + "mocha": "^3.3.0", + "prettier": "^1.2.2" + }, + "lint-staged": { + "*.js": [ + "prettier --write \"src/**/*.js\"", + "git add" + ] } } diff --git a/src/lesspass.js b/src/lesspass.js index 86a377d..6aea642 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -1,62 +1,19 @@ -var v1 = require('./v1'); -var v2 = require('./v2'); -var pbkdf2 = require('./pbkdf2'); -var objectAssign = require('object-assign'); +var v1 = require("./v1"); +var v2 = require("./v2"); +var createHMAC = require("create-hmac"); +var Buffer = require("buffer/").Buffer; +var Promise = require("es6-promise").Promise; module.exports = { - encryptLogin: v1.encryptLogin, - renderPassword: v1.renderPassword, - createFingerprint: v1.createFingerprint, - _deriveEncryptedLogin: v1._deriveEncryptedLogin, - _getPasswordTemplate: v1._getPasswordTemplate, - _prettyPrint: v1._prettyPrint, - _string2charCodes: v1._string2charCodes, - _getCharType: v1._getCharType, - _getPasswordChar: v1._getPasswordChar, - _createHmac: v1._createHmac, - - generatePassword: generatePassword, - _calcEntropy: v2._calcEntropy, - _consumeEntropy: v2._consumeEntropy, - _getSetOfCharacters: v2._getSetOfCharacters, - _getConfiguredRules: v2._getConfiguredRules, - _insertStringPseudoRandomly: v2._insertStringPseudoRandomly, - _getOneCharPerRule: v2._getOneCharPerRule, - _renderPassword: v2._renderPassword, - - pbkdf2: pbkdf2 -}; - -var defaultPasswordProfile = { - version: 2, - lowercase: true, - numbers: true, - uppercase: true, - symbols: true, - keylen: 32, - digest: 'sha256', - length: 16, - counter: 1, - iterations: 100000 -}; - -function generatePassword(site, login, masterPassword, passwordProfile) { - var _passwordProfile = objectAssign({}, defaultPasswordProfile, passwordProfile); - if (_passwordProfile.version === 1) { - var options = { - counter: _passwordProfile.counter, - length: _passwordProfile.length, - lowercase: _passwordProfile.lowercase, - uppercase: _passwordProfile.uppercase, - numbers: _passwordProfile.numbers, - symbols: _passwordProfile.symbols - }; - return v1.encryptLogin(login, masterPassword) - .then(function(encryptedLogin) { - return v1.renderPassword(encryptedLogin, site, options).then(function(generatedPassword) { - return generatedPassword - }); - }); + generatePassword: function(site, login, masterPassword, options) { + if (typeof options !== "undefined" && options.version === 1) { + return v1.generatePassword(site, login, masterPassword, options); + } + return v2.generatePassword(site, login, masterPassword, options); + }, + createFingerprint: function(str) { + return new Promise(function(resolve) { + resolve(createHMAC("sha256", new Buffer(str)).digest("hex")); + }); } - return v2.generatePassword(site, login, masterPassword, _passwordProfile); -} +}; diff --git a/src/pbkdf2.js b/src/pbkdf2.js index 560b826..cba6f7f 100644 --- a/src/pbkdf2.js +++ b/src/pbkdf2.js @@ -1,51 +1,64 @@ -var pbkdf2 = require('pbkdf2'); -var Promise = require('pinkie-promise'); - +var pbkdf2 = require("pbkdf2"); +var Buffer = require("buffer/").Buffer; +var Promise = require("es6-promise").Promise; function shouldUseNative() { - return !!(typeof window !== 'undefined' && window.crypto && window.crypto.subtle); + return !!(typeof window !== "undefined" && + window.crypto && + window.crypto.subtle); } -function pbkdf2Native(password, salt, iterations, keylen, digest) { +function pbkdf2WebCrypto(password, salt, iterations, keylen, digest) { var algorithms = { - 'sha1': 'SHA-1', - 'sha-1': 'SHA-1', - 'sha256': 'SHA-256', - 'sha-256': 'SHA-256', - 'sha512': 'SHA-512', - 'sha-512': 'SHA-512', + sha1: "SHA-1", + "sha-1": "SHA-1", + sha256: "SHA-256", + "sha-256": "SHA-256", + sha512: "SHA-512", + "sha-512": "SHA-512" }; - return window.crypto.subtle.importKey('raw', new Buffer(password), 'PBKDF2', false, ['deriveKey']) + return window.crypto.subtle + .importKey("raw", new Buffer(password), "PBKDF2", false, ["deriveKey"]) .then(function(key) { var algo = { - name: 'PBKDF2', + name: "PBKDF2", salt: new Buffer(salt), iterations: iterations, - hash: algorithms[digest.toLowerCase()], + hash: algorithms[digest.toLowerCase()] }; - return window.crypto.subtle.deriveKey(algo, key, { - name: 'AES-CTR', - length: keylen * 8 - }, true, ['encrypt', 'decrypt']); + return window.crypto.subtle.deriveKey( + algo, + key, + { + name: "AES-CTR", + length: keylen * 8 + }, + true, + ["encrypt", "decrypt"] + ); }) .then(function(derivedKey) { - return window.crypto.subtle.exportKey('raw', derivedKey).then(function(keyArray) { - return new Buffer(keyArray).toString('hex'); - }); + return window.crypto.subtle + .exportKey("raw", derivedKey) + .then(function(keyArray) { + return new Buffer(keyArray).toString("hex"); + }); }); } function pbkdf2Browserified(password, salt, iterations, keylen, digest) { return new Promise(function(resolve, reject) { - pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function(error, key) { + pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function( + error, + key + ) { if (error) { - reject('error in pbkdf2'); + reject("error in pbkdf2"); } else { - resolve(key.toString('hex')); + resolve(key.toString("hex")); } }); }); } - -module.exports = shouldUseNative() ? pbkdf2Native : pbkdf2Browserified; +module.exports = shouldUseNative() ? pbkdf2WebCrypto : pbkdf2Browserified; diff --git a/src/v1.js b/src/v1.js index 6901581..93fe1bb 100644 --- a/src/v1.js +++ b/src/v1.js @@ -1,39 +1,68 @@ -var pbkdf2 = require('./pbkdf2'); -var createHMAC = require('create-hmac'); -var Promise = require('pinkie-promise'); - +var pbkdf2 = require("./pbkdf2"); +var assign = require("lodash.assign"); +var createHMAC = require("create-hmac"); module.exports = { - encryptLogin: encryptLogin, - renderPassword: renderPassword, - createFingerprint: createFingerprint, + generatePassword: generatePassword, + _renderPassword: renderPassword, + _createHmac: createHmac, _deriveEncryptedLogin: deriveEncryptedLogin, _getPasswordTemplate: getPasswordTemplate, _prettyPrint: prettyPrint, _string2charCodes: string2charCodes, _getCharType: getCharType, - _getPasswordChar: getPasswordChar, - _createHmac: createHmac, + _getPasswordChar: getPasswordChar }; +var defaultOptions = { + version: 1, + lowercase: true, + numbers: true, + uppercase: true, + symbols: true, + keylen: 32, + digest: "sha256", + length: 12, + counter: 1, + iterations: 8192 +}; -function encryptLogin(login, masterPassword, options) { - var _options = options !== undefined ? options : {}; - var iterations = _options.iterations || 8192; - var keylen = _options.keylen || 32; - return pbkdf2(masterPassword, login, iterations, keylen, 'sha256'); +function generatePassword(site, login, masterPassword, options) { + var _options = assign({}, defaultOptions, options); + return pbkdf2( + masterPassword, + login, + _options.iterations, + _options.keylen, + "sha256" + ).then(function(encryptedLogin) { + return renderPassword(encryptedLogin, site, _options).then(function( + generatedPassword + ) { + return generatedPassword; + }); + }); } function renderPassword(encryptedLogin, site, passwordOptions) { - return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function(derivedEncryptedLogin) { - var template = passwordOptions.template || getPasswordTemplate(passwordOptions); + return deriveEncryptedLogin( + encryptedLogin, + site, + passwordOptions + ).then(function(derivedEncryptedLogin) { + var template = + passwordOptions.template || getPasswordTemplate(passwordOptions); return prettyPrint(derivedEncryptedLogin, template); }); } function createHmac(encryptedLogin, salt) { return new Promise(function(resolve) { - resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex')); + resolve( + createHMAC("sha256", new Buffer(encryptedLogin)) + .update(salt) + .digest("hex") + ); }); } @@ -50,22 +79,22 @@ function deriveEncryptedLogin(encryptedLogin, site, options) { function getPasswordTemplate(passwordTypes) { var templates = { - lowercase: 'vc', - uppercase: 'VC', - numbers: 'n', - symbols: 's', + lowercase: "vc", + uppercase: "VC", + numbers: "n", + symbols: "s" }; - var returnedTemplate = ''; + var returnedTemplate = ""; Object.keys(templates).forEach(function(template) { if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { - returnedTemplate += templates[template] + returnedTemplate += templates[template]; } }); return returnedTemplate; } function prettyPrint(hash, template) { - var password = ''; + var password = ""; string2charCodes(hash).forEach(function(charCode, index) { var charType = getCharType(template, index); @@ -88,22 +117,16 @@ function getCharType(template, index) { function getPasswordChar(charType, index) { var passwordsChars = { - V: 'AEIOUY', - C: 'BCDFGHJKLMNPQRSTVWXZ', - v: 'aeiouy', - c: 'bcdfghjklmnpqrstvwxz', - A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ', - a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz', - n: '0123456789', - s: '@&%?,=[]_:-+*$#!\'^~;()/.', - x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.' + V: "AEIOUY", + C: "BCDFGHJKLMNPQRSTVWXZ", + v: "aeiouy", + c: "bcdfghjklmnpqrstvwxz", + A: "AEIOUYBCDFGHJKLMNPQRSTVWXZ", + a: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz", + n: "0123456789", + s: "@&%?,=[]_:-+*$#!'^~;()/.", + x: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!'^~;()/." }; var passwordChar = passwordsChars[charType]; return passwordChar[index % passwordChar.length]; } - -function createFingerprint(str) { - return new Promise(function(resolve) { - resolve(createHMAC('sha256', new Buffer(str)).digest('hex')) - }); -} diff --git a/src/v2.js b/src/v2.js index 3c6995f..63c6665 100644 --- a/src/v2.js +++ b/src/v2.js @@ -1,5 +1,6 @@ -var pbkdf2 = require('./pbkdf2'); +var pbkdf2 = require("./pbkdf2"); var bigInt = require("big-integer"); +var assign = require("lodash.assign"); module.exports = { generatePassword: generatePassword, @@ -12,65 +13,107 @@ module.exports = { _renderPassword: renderPassword }; -function generatePassword(site, login, masterPassword, passwordProfile) { - return calcEntropy(site, login, masterPassword, passwordProfile).then(function(entropy) { - return renderPassword(entropy, passwordProfile); +var defaultOptions = { + version: 2, + lowercase: true, + numbers: true, + uppercase: true, + symbols: true, + keylen: 32, + digest: "sha256", + length: 16, + counter: 1, + iterations: 100000 +}; + +function generatePassword(site, login, masterPassword, options) { + var _options = assign({}, defaultOptions, options); + return calcEntropy(site, login, masterPassword, _options).then(function( + entropy + ) { + return renderPassword(entropy, _options); }); } function calcEntropy(site, login, masterPassword, passwordProfile) { var salt = site + login + passwordProfile.counter.toString(16); - return pbkdf2(masterPassword, salt, passwordProfile.iterations, passwordProfile.keylen, passwordProfile.digest); + return pbkdf2( + masterPassword, + salt, + passwordProfile.iterations, + passwordProfile.keylen, + passwordProfile.digest + ); } var characterSubsets = { - lowercase: 'abcdefghijklmnopqrstuvwxyz', - uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', - numbers: '0123456789', - symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' + lowercase: "abcdefghijklmnopqrstuvwxyz", + uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + numbers: "0123456789", + symbols: "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" }; function getSetOfCharacters(rules) { - if (typeof rules === 'undefined') { - return characterSubsets.lowercase + characterSubsets.uppercase + characterSubsets.numbers + characterSubsets.symbols; + if (typeof rules === "undefined") { + return ( + characterSubsets.lowercase + + characterSubsets.uppercase + + characterSubsets.numbers + + characterSubsets.symbols + ); } - var setOfChars = ''; + var setOfChars = ""; rules.forEach(function(rule) { setOfChars += characterSubsets[rule]; }); return setOfChars; } -function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) { +function consumeEntropy( + generatedPassword, + quotient, + setOfCharacters, + maxLength +) { if (generatedPassword.length >= maxLength) { - return {value: generatedPassword, entropy: quotient}; + return { value: generatedPassword, entropy: quotient }; } var longDivision = quotient.divmod(setOfCharacters.length); generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength); + return consumeEntropy( + generatedPassword, + longDivision.quotient, + setOfCharacters, + maxLength + ); } function insertStringPseudoRandomly(generatedPassword, entropy, string) { for (var i = 0; i < string.length; i++) { var longDivision = entropy.divmod(generatedPassword.length); - generatedPassword = generatedPassword.slice(0, longDivision.remainder) + string[i] + generatedPassword.slice(longDivision.remainder); + generatedPassword = + generatedPassword.slice(0, longDivision.remainder) + + string[i] + + generatedPassword.slice(longDivision.remainder); entropy = longDivision.quotient; } return generatedPassword; } function getOneCharPerRule(entropy, rules) { - var oneCharPerRules = ''; + var oneCharPerRules = ""; rules.forEach(function(rule) { - var password = consumeEntropy('', entropy, characterSubsets[rule], 1); + var password = consumeEntropy("", entropy, characterSubsets[rule], 1); oneCharPerRules += password.value; entropy = password.entropy; }); - return {value: oneCharPerRules, entropy: entropy}; + return { value: oneCharPerRules, entropy: entropy }; } function getConfiguredRules(passwordProfile) { - return ['lowercase', 'uppercase', 'numbers', 'symbols'].filter(function(rule) { + return ["lowercase", "uppercase", "numbers", "symbols"].filter(function( + rule + ) { return passwordProfile[rule]; }); } @@ -78,7 +121,16 @@ function getConfiguredRules(passwordProfile) { function renderPassword(entropy, passwordProfile) { var rules = getConfiguredRules(passwordProfile); var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy('', bigInt(entropy, 16), setOfCharacters, passwordProfile.length - rules.length); + var password = consumeEntropy( + "", + bigInt(entropy, 16), + setOfCharacters, + passwordProfile.length - rules.length + ); var charactersToAdd = getOneCharPerRule(password.entropy, rules); - return insertStringPseudoRandomly(password.value, charactersToAdd.entropy, charactersToAdd.value); + return insertStringPseudoRandomly( + password.value, + charactersToAdd.entropy, + charactersToAdd.value + ); } diff --git a/test/api.tests.js b/test/api.tests.js new file mode 100644 index 0000000..cab8e1c --- /dev/null +++ b/test/api.tests.js @@ -0,0 +1,388 @@ +var assert = require("assert"); +var LessPass = require("../src/lesspass"); + +describe("api", function() { + describe("v1", function() { + it("generatedPassword", function() { + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("izIS5@ozYM2?", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("azYS7,olOL2]", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 14, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("azYS7,olOL2]iz", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: false, + numbers: false, + symbols: false, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("azyseqololat", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: false, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("AZ3[EQ7@OL2]", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: false, + uppercase: false, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("4?3[7,7@7@2]", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: false, + uppercase: false, + numbers: false, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("[?=[&,:@:@[]", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("azYS7uwAW8at", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: false, + symbols: false, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("azYSeqOLolAT", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 2, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("obYT2=olOV9=", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "lesspass"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("erOC1%imIW3,", generatedPassword); + }); + }); + it("generatedPassword", function() { + var site = "lesspass.com"; + var login = "contact@lesspass.com"; + var masterPassword = "password2"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 12, + counter: 1, + version: 1 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("uvUM5_ucUP5=", generatedPassword); + }); + }); + }); + describe("v2", function() { + it("generatedPassword", function() { + this.timeout(10000); + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + length: 16, + counter: 1, + version: 2 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("WHLpUL)e00[iHR+w", generatedPassword); + }); + }); + it("generatedPassword", function() { + this.timeout(10000); + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: true, + symbols: false, + length: 14, + counter: 2, + version: 2 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("MBAsB7b1Prt8Sl", generatedPassword); + }); + }); + it("generatedPassword", function() { + this.timeout(10000); + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var options = { + lowercase: false, + uppercase: false, + numbers: true, + symbols: false, + length: 6, + counter: 3, + version: 2 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("117843", generatedPassword); + }); + }); + it("generatedPassword", function() { + this.timeout(10000); + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var options = { + lowercase: true, + uppercase: true, + numbers: false, + symbols: true, + length: 14, + counter: 1, + version: 2 + }; + return LessPass.generatePassword( + site, + login, + masterPassword, + options + ).then(function(generatedPassword) { + assert.equal("sB>{qF}wN%/-fm", generatedPassword); + }); + }); + it("generatedPassword", function() { + this.timeout(10000); + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + return LessPass.generatePassword( + site, + login, + masterPassword + ).then(function(generatedPassword) { + assert.equal("WHLpUL)e00[iHR+w", generatedPassword); + }); + }); + }); + describe("fingerprint", function() { + it("createFingerprint", function() { + return LessPass.createFingerprint("password").then(function(fingerprint) { + assert.equal( + "e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e", + fingerprint + ); + }); + }); + }); +}); diff --git a/test/karma.conf.js b/test/karma.conf.js new file mode 100644 index 0000000..7acd89a --- /dev/null +++ b/test/karma.conf.js @@ -0,0 +1,19 @@ +module.exports = function(config) { + config.set({ + basePath: "..", + frameworks: ["browserify", "mocha"], + files: ["dist/lesspass.js", "test/**/*.js"], + exclude: [], + preprocessors: { + "test/**/*.js": ["browserify"] + }, + reporters: ["progress"], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: false, + browsers: ["Firefox", "Chrome"], + singleRun: true, + concurrency: Infinity + }); +}; diff --git a/test/pbkdf2.tests.js b/test/pbkdf2.tests.js new file mode 100644 index 0000000..217a28e --- /dev/null +++ b/test/pbkdf2.tests.js @@ -0,0 +1,227 @@ +var assert = require("assert"); +var pbkdf2 = require("../src/pbkdf2"); + +describe("pbkdf2", function() { + it("secret, salt, 2 iterations, 32 keylen, sha256 hash", function() { + return pbkdf2("secret", "salt", 2, 32, "sha256").then(function(key) { + assert.equal( + "f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569", + key + ); + }); + }); + it("use pbkdf2 with 8192 iterations and sha256", function() { + return pbkdf2( + "password", + "test@example.org", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472", + key + ); + }); + }); + it("customize number of iterations", function() { + return pbkdf2( + "password", + "test@example.org", + 4096, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f", + key + ); + }); + }); + it("customize key length", function() { + return pbkdf2( + "password", + "test@example.org", + 8192, + 16, + "sha256" + ).then(function(key) { + assert.equal("d8af5f918db6b65b1db3d3984e5a400e", key); + }); + }); + it("customize iterations and key length", function() { + return pbkdf2( + "password", + "test@example.org", + 4096, + 16, + "sha256" + ).then(function(key) { + assert.equal("0a91208545e3aa4935d3a22984ca097a", key); + }); + }); + it("utf8 parameter", function() { + return pbkdf2( + "♥ LessPass ♥", + "test@example.org", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651", + key + ); + }); + }); + it("auto generated test 0", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 1", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 2", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 3", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 4", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 5", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 6", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 7", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 8", function() { + return pbkdf2( + "password", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0", + key + ); + }); + }); + it("auto generated test 9", function() { + return pbkdf2("password", "lesspass", 8192, 32, "sha256").then(function( + key + ) { + assert.equal( + "7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116", + key + ); + }); + }); + it("auto generated test 10", function() { + return pbkdf2( + "password2", + "contact@lesspass.com", + 8192, + 32, + "sha256" + ).then(function(key) { + assert.equal( + "ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4", + key + ); + }); + }); +}); diff --git a/test/v1/deriveEncryptedLogin.tests.js b/test/v1/deriveEncryptedLogin.tests.js new file mode 100644 index 0000000..79904e3 --- /dev/null +++ b/test/v1/deriveEncryptedLogin.tests.js @@ -0,0 +1,110 @@ +var assert = require("assert"); +var v1 = require("../../src/v1"); + +describe("deriveEncryptedLogin", function() { + it("should createHmac", function() { + var encryptedLogin = + "9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88"; + var salt = "lesspass.com1"; + return v1._createHmac(encryptedLogin, salt).then(function(hmac) { + assert.equal( + "be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed", + hmac + ); + }); + }); + it("should derive encrypted login with default options 1", function() { + const encryptedLogin = + "90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d"; + const site = "lesspass.com"; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site) + .then(function(generatedPassword) { + assert.equal("ecd16aefc7e5", generatedPassword); + }); + }); + it("should derive encrypted login with default options 2", function() { + const encryptedLogin = + "90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d"; + const site = "lesspass.com"; + const option = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site, option) + .then(function(generatedPassword) { + assert.equal("ecd16aefc7e5", generatedPassword); + }); + }); + it("should derive encrypted login with defined length", function() { + var encryptedLogin = + "d79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed"; + var site = "lesspass.com"; + var option = { + counter: 1, + length: 10 + }; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site, option) + .then(function(generatedPassword) { + assert.equal(10, generatedPassword.length); + }); + }); + it("should return two different passwords if site different 1", function() { + const encryptedLogin = + "f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9"; + const site = "google.com"; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site) + .then(function(derivedEncryptedLogin) { + assert.equal("a957c3a459ec", derivedEncryptedLogin); + }); + }); + it("should return two different passwords if site different 2", function() { + const encryptedLogin = + "f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9"; + const site = "facebook.com"; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site) + .then(function(derivedEncryptedLogin) { + assert.equal("d9f3a918c34b", derivedEncryptedLogin); + }); + }); + it("should return two different passwords if counter different 1", function() { + const encryptedLogin = + "dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd"; + const site = "lesspass.com"; + const option = { counter: 1 }; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site, option) + .then(function(derivedEncryptedLogins) { + assert.equal("bb2e0b34036d", derivedEncryptedLogins); + }); + }); + it("should return two different passwords if counter different 2", function() { + const encryptedLogin = + "dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd"; + const site = "lesspass.com"; + const option2 = { counter: 2 }; + return v1 + ._deriveEncryptedLogin(encryptedLogin, site, option2) + .then(function(derivedEncryptedLogins) { + assert.equal("67fe8c05a248", derivedEncryptedLogins); + }); + }); + it("should derive encrypted login with sha 256", function() { + const encryptedLogin = + "9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88"; + const site = "lesspass.com"; + v1 + ._deriveEncryptedLogin(encryptedLogin, site) + .then(function(encryptedLogin) { + assert.equal("be00f942fc8a", encryptedLogin); + }); + }); +}); diff --git a/test/v1/getPasswordTemplate.tests.js b/test/v1/getPasswordTemplate.tests.js new file mode 100644 index 0000000..0fc43f2 --- /dev/null +++ b/test/v1/getPasswordTemplate.tests.js @@ -0,0 +1,82 @@ +var assert = require("assert"); +var v1 = require("../../src/v1"); + +describe("getPasswordTemplate", function() { + it("should get default template", function() { + assert.equal( + "vcVCns", + v1._getPasswordTemplate({ + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }) + ); + }); + it("should get lowercase template", function() { + assert.equal( + "vc", + v1._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: false, + symbols: false + }) + ); + }); + it("should get uppercase template", function() { + assert.equal( + "VC", + v1._getPasswordTemplate({ + lowercase: false, + uppercase: true, + numbers: false, + symbols: false + }) + ); + }); + it("should get numbers template", function() { + assert.equal( + "n", + v1._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: true, + symbols: false + }) + ); + }); + it("should get symbols template", function() { + assert.equal( + "s", + v1._getPasswordTemplate({ + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + }) + ); + }); + it("should concatenate template if two password settings", function() { + assert.equal( + "vcVC", + v1._getPasswordTemplate({ + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + }) + ); + assert.equal( + "vcns", + v1._getPasswordTemplate({ + lowercase: true, + uppercase: false, + numbers: true, + symbols: true + }) + ); + }); +}); diff --git a/test/v1/prettyPrint.js b/test/v1/prettyPrint.js new file mode 100644 index 0000000..43b484f --- /dev/null +++ b/test/v1/prettyPrint.js @@ -0,0 +1,39 @@ +var assert = require("assert"); +var v1 = require("../../src/v1"); + +describe("prettyPrint", function() { + it("should print different password if templates different", function() { + var encryptedLogin = + "78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32"; + assert.notEqual( + v1._prettyPrint(encryptedLogin, "cv"), + v1._prettyPrint(encryptedLogin, "vc") + ); + }); + it("must return a string of the same length as the input", function() { + var hash = + "f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d"; + assert.equal(hash.length, v1._prettyPrint(hash, "cv").length); + }); + it("should return char inside a string based on modulo of the index", function() { + var template = "cv"; + assert.equal("c", v1._getCharType(template, 0)); + assert.equal("v", v1._getCharType(template, 1)); + assert.equal("c", v1._getCharType(template, 10)); + }); + it("should convert a string into an array of char code", function() { + var charCodes = v1._string2charCodes("ab40f6ee71"); + assert.equal(97, charCodes[0]); + assert.equal(98, charCodes[1]); + assert.equal(10, charCodes.length); + }); + it("should get password char based on its type and index", function() { + var typeVowel = "V"; + assert.equal("A", v1._getPasswordChar(typeVowel, 0)); + }); + it("should modulo if overflow", function() { + var typeVowel = "V"; + assert.equal("E", v1._getPasswordChar(typeVowel, 1)); + assert.equal("E", v1._getPasswordChar(typeVowel, 7)); + }); +}); diff --git a/test/v1/renderPassword.tests.js b/test/v1/renderPassword.tests.js new file mode 100644 index 0000000..c897de6 --- /dev/null +++ b/test/v1/renderPassword.tests.js @@ -0,0 +1,281 @@ +var assert = require("assert"); +var v1 = require("../../src/v1"); + +describe("renderPassword", function() { + it("renderPassword", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("azYS7,olOL2]", generatedPassword); + }); + }); + it("renderPassword with a custom template", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: "n" + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + var i = generatedPassword.length; + while (i--) { + assert("0123456789".indexOf(generatedPassword[i]) !== -1); + } + }); + }); + it("renderPassword with a custom template too short", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: "CvcnCVsn" + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("Sor4WU:8Wad5", generatedPassword); + }); + }); + it("renderPassword with a custom template too long", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 6, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true, + template: "CvcnCVsn" + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("Sor4WU", generatedPassword); + }); + }); + it("renderPassword auto generated 0", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("azYS7,olOL2]", generatedPassword); + }); + }); + it("renderPassword auto generated 1", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 14, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("azYS7,olOL2]iz", generatedPassword); + }); + }); + it("renderPassword auto generated 2", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: false, + numbers: false, + symbols: false + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("azyseqololat", generatedPassword); + }); + }); + it("renderPassword auto generated 3", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: false, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("AZ3[EQ7@OL2]", generatedPassword); + }); + }); + it("renderPassword auto generated 4", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("4?3[7,7@7@2]", generatedPassword); + }); + }); + it("renderPassword auto generated 5", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: false, + uppercase: false, + numbers: false, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("[?=[&,:@:@[]", generatedPassword); + }); + }); + it("renderPassword auto generated 6", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: false + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("azYS7uwAW8at", generatedPassword); + }); + }); + it("renderPassword auto generated 7", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: false, + symbols: false + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("azYSeqOLolAT", generatedPassword); + }); + }); + it("renderPassword auto generated 8", function() { + var site = "lesspass.com"; + var encryptedLogin = + "63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0"; + var passwordOptions = { + counter: 2, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("obYT2=olOV9=", generatedPassword); + }); + }); + it("renderPassword auto generated 9", function() { + var site = "lesspass.com"; + var encryptedLogin = + "7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("erOC1%imIW3,", generatedPassword); + }); + }); + it("renderPassword auto generated 10", function() { + var site = "lesspass.com"; + var encryptedLogin = + "ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4"; + var passwordOptions = { + counter: 1, + length: 12, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + return v1 + ._renderPassword(encryptedLogin, site, passwordOptions) + .then(function(generatedPassword) { + assert.equal("uvUM5_ucUP5=", generatedPassword); + }); + }); +}); diff --git a/test/v2/entropy.tests.js b/test/v2/entropy.tests.js new file mode 100644 index 0000000..7b2551c --- /dev/null +++ b/test/v2/entropy.tests.js @@ -0,0 +1,79 @@ +var assert = require("assert"); +var v2 = require("../../src/v2"); +var bigInt = require("big-integer"); + +describe("entropy", function() { + it("calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)", function() { + this.timeout(10000); + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var passwordProfile = { + iterations: 100000, + keylen: 32, + digest: "sha256", + counter: 1 + }; + return v2 + ._calcEntropy(site, login, masterPassword, passwordProfile) + .then(function(entropy) { + assert.equal( + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e", + entropy + ); + }); + }); + it("calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)", function() { + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var passwordProfile = { + iterations: 8192, + keylen: 16, + digest: "sha512", + counter: 1 + }; + return v2 + ._calcEntropy(site, login, masterPassword, passwordProfile) + .then(function(entropy) { + assert.equal("fff211c16a4e776b3574c6a5c91fd252", entropy); + }); + }); + it("calc entropy different if counter different 1", function() { + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var passwordProfile1 = { + iterations: 1, + keylen: 16, + digest: "sha256", + counter: 1 + }; + return v2 + ._calcEntropy(site, login, masterPassword, passwordProfile1) + .then(function(entropy) { + assert.equal("d3ec1e988dd0b3640c7491cd2c2a88b5", entropy); + }); + }); + it("calc entropy different if counter different 2", function() { + var site = "example.org"; + var login = "contact@example.org"; + var masterPassword = "password"; + var passwordProfile2 = { + iterations: 1, + keylen: 16, + digest: "sha256", + counter: 2 + }; + return v2 + ._calcEntropy(site, login, masterPassword, passwordProfile2) + .then(function(entropy) { + assert.equal("ddfb1136260f930c21f6d72f6eddbd40", entropy); + }); + }); + it("consume entropy", function() { + var password = v2._consumeEntropy("", bigInt(4 * 4 + 2), "abcd", 2); + assert.equal("ca", password.value); + assert.equal(1, password.entropy); + }); +}); diff --git a/test/v2/renderPassword.tests.js b/test/v2/renderPassword.tests.js new file mode 100644 index 0000000..3bc1ca9 --- /dev/null +++ b/test/v2/renderPassword.tests.js @@ -0,0 +1,99 @@ +var assert = require("assert"); +var v2 = require("../../src/v2"); +var bigInt = require("big-integer"); + +describe("LessPass v2", function() { + var defaultPasswordProfile = { + length: 16, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + it("render password use remainder of long division beetween entropy and set of chars length as an index", function() { + var entropy = + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; + assert.equal("W", v2._renderPassword(entropy, defaultPasswordProfile)[0]); + }); + it("render password use quotient as second entropy recursively", function() { + var entropy = + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; + assert.equal("H", v2._renderPassword(entropy, defaultPasswordProfile)[1]); + }); + it("render password has default length of 16", function() { + var entropy = + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; + assert.equal( + 16, + v2._renderPassword(entropy, defaultPasswordProfile).length + ); + }); + it("render password can specify length", function() { + var entropy = + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; + var passwordProfile = { + length: 20, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + assert.equal(20, v2._renderPassword(entropy, passwordProfile).length); + }); + it("include one char per set of characters", function() { + var password = v2._insertStringPseudoRandomly( + "123456", + bigInt(7 * 6 + 2), + "uT" + ); + assert.equal("T12u3456", password); + }); + it("render password return at least one char in every characters set", function() { + var entropy = + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; + var passwordProfile = { + length: 6, + lowercase: true, + uppercase: true, + numbers: true, + symbols: true + }; + var generatedPassword = v2._renderPassword(entropy, passwordProfile); + var passwordLength = generatedPassword.length; + var lowercaseOk = false; + var uppercaseOk = false; + var numbersOk = false; + var symbolsOk = false; + while (passwordLength--) { + if ( + "abcdefghijklmnopqrstuvwxyz".indexOf( + generatedPassword[passwordLength] + ) !== -1 + ) { + lowercaseOk = true; + } + if ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( + generatedPassword[passwordLength] + ) !== -1 + ) { + uppercaseOk = true; + } + if ("0123456789".indexOf(generatedPassword[passwordLength]) !== -1) { + numbersOk = true; + } + if ( + "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".indexOf( + generatedPassword[passwordLength] + ) !== -1 + ) { + symbolsOk = true; + } + } + assert.equal(6, generatedPassword.length); + assert( + lowercaseOk && uppercaseOk && numbersOk && symbolsOk, + "there is no at least one char in every characters set" + ); + }); +}); diff --git a/test/v2/setOfCharacters.tests.js b/test/v2/setOfCharacters.tests.js new file mode 100644 index 0000000..cf1c7ec --- /dev/null +++ b/test/v2/setOfCharacters.tests.js @@ -0,0 +1,78 @@ +var assert = require("assert"); +var v2 = require("../../src/v2"); +var bigInt = require("big-integer"); + +describe("set of characters", function() { + it("get default set of characters", function() { + var setOfCharacters = v2._getSetOfCharacters(); + assert.equal( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + setOfCharacters + ); + assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); + }); + it("get default set of characters concat rules in order", function() { + var setOfCharacters = v2._getSetOfCharacters([ + "lowercase", + "uppercase", + "numbers" + ]); + assert.equal( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", + setOfCharacters + ); + assert.equal(26 * 2 + 10, setOfCharacters.length); + }); + it("get set of characters only lowercase", function() { + var setOfCharacters = v2._getSetOfCharacters(["lowercase"]); + assert.equal("abcdefghijklmnopqrstuvwxyz", setOfCharacters); + assert.equal(26, setOfCharacters.length); + }); + it("get set of characters only uppercase", function() { + var setOfCharacters = v2._getSetOfCharacters(["uppercase"]); + assert.equal("ABCDEFGHIJKLMNOPQRSTUVWXYZ", setOfCharacters); + assert.equal(26, setOfCharacters.length); + }); + it("get set of characters only numbers", function() { + var setOfCharacters = v2._getSetOfCharacters(["numbers"]); + assert.equal("0123456789", setOfCharacters); + assert.equal(10, setOfCharacters.length); + }); + it("get set of characters only symbols", function() { + var setOfCharacters = v2._getSetOfCharacters(["symbols"]); + assert.equal("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", setOfCharacters); + assert.equal(32, setOfCharacters.length); + }); + it("generate one char per rules", function() { + var oneCharPerSetOfCharacters = v2._getOneCharPerRule(bigInt(26 * 26), [ + "lowercase", + "uppercase" + ]); + assert.equal("aA", oneCharPerSetOfCharacters.value); + assert.equal(2, oneCharPerSetOfCharacters.value.length); + assert.equal(1, oneCharPerSetOfCharacters.entropy); + }); + it("configured rules", function() { + assert.deepEqual( + ["uppercase"], + v2._getConfiguredRules({ uppercase: true }) + ); + assert.deepEqual( + ["lowercase", "uppercase"], + v2._getConfiguredRules({ uppercase: true, lowercase: true }) + ); + assert.deepEqual( + ["lowercase"], + v2._getConfiguredRules({ lowercase: true, symbols: false }) + ); + assert.deepEqual( + ["lowercase", "uppercase", "numbers", "symbols"], + v2._getConfiguredRules({ + lowercase: true, + uppercase: true, + symbols: true, + numbers: true + }) + ); + }); +}); diff --git a/tests/helper.js b/tests/helper.js deleted file mode 100644 index fd1e536..0000000 --- a/tests/helper.js +++ /dev/null @@ -1,4 +0,0 @@ -// globals -global.chai = require('chai'); -global.LessPass = require('../src/lesspass'); -global.bigInt = require("big-integer"); \ No newline at end of file diff --git a/tests/karma.config.js b/tests/karma.config.js deleted file mode 100644 index d64f908..0000000 --- a/tests/karma.config.js +++ /dev/null @@ -1,26 +0,0 @@ -module.exports = function(config) { - var configuration = { - basePath: '..', - frameworks: ['mocha', 'chai'], - files: [ - 'node_modules/big-integer/BigInteger.min.js', - 'dist/lesspass.js', - 'tests/**/*.js' - ], - exclude: [ - 'tests/node.js', - 'tests/helper.js', - 'tests/karma.webcrypto.config.js', - ], - preprocessors: {}, - reporters: ['progress'], - port: 9876, - colors: true, - logLevel: config.LOG_INFO, - autoWatch: true, - browsers: ['Firefox'], - singleRun: true, - concurrency: Infinity - }; - config.set(configuration) -}; diff --git a/tests/node.js b/tests/node.js deleted file mode 100644 index cba9e73..0000000 --- a/tests/node.js +++ /dev/null @@ -1,23 +0,0 @@ -const LessPass = require('../src/lesspass'); -const assert = require('assert'); - -const site = 'lesspass.com'; -const login = 'contact@lesspass.com'; -const masterPassword = 'password'; -const passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 16, - counter: 1, - version: 2 -}; -LessPass.generatePassword(site, login, masterPassword, passwordProfile) - .then(function(generatedPassword) { - assert.equal(generatedPassword, '\\g-A1-.OHEwrXjT#'); - console.log('generated password ok'); - }) - .catch(function(e) { - console.log(e); - }); diff --git a/tests/pbkdf2.tests.js b/tests/pbkdf2.tests.js deleted file mode 100644 index c2f9dbf..0000000 --- a/tests/pbkdf2.tests.js +++ /dev/null @@ -1,16 +0,0 @@ -var assert = chai.assert; - -describe('LessPass', function() { - describe('pbkdf2', function() { - it('should secret, salt, 2, 32, sha256', function() { - return LessPass.pbkdf2('secret', 'salt', 2, 32, 'sha256').then(function(key) { - assert.equal('f92f45f9df4c2aeabae1ed3c16f7b64660c1f8e377fa9b4699b23c2c3a29f569', key); - }) - }); - }); -}); - - - - - diff --git a/tests/v1/api.tests.js b/tests/v1/api.tests.js deleted file mode 100644 index 648955e..0000000 --- a/tests/v1/api.tests.js +++ /dev/null @@ -1,545 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v1', function() { - describe('encryptLogin', function() { - it('should use pbkdf2 with 8192 iterations and sha256', function(done) { - LessPass.encryptLogin('test@example.org', 'password').then(function(encryptedLogin) { - assert.equal('d8af5f918db6b65b1db3d3984e5a400e39e1dbb19462220e4431de283809f472', encryptedLogin); - done(); - }); - }); - it('should allow to customize number of iterations', function(done) { - LessPass.encryptLogin('test@example.org', 'password', {iterations: 4096}).then(function(encryptedLogin) { - assert.equal('0a91208545e3aa4935d3a22984ca097a7669259a04d261ac16361bdc1a2e960f', encryptedLogin); - done(); - }); - }); - it('should allow to customize key length', function(done) { - LessPass.encryptLogin('test@example.org', 'password', {keylen: 16}).then(function(encryptedLogin) { - assert.equal('d8af5f918db6b65b1db3d3984e5a400e', encryptedLogin); - done(); - }); - }); - it('should allow to customize iterations and key length', function(done) { - LessPass.encryptLogin('test@example.org', 'password', { - iterations: 4096, - keylen: 16 - }).then(function(encryptedLogin) { - assert.equal('0a91208545e3aa4935d3a22984ca097a', encryptedLogin); - done(); - }); - }); - it('should allow utf8 parameter', function() { - return LessPass.encryptLogin('test@example.org', '♥ LessPass ♥').then(function(encryptedLogin) { - assert.equal('997fe81d3d0db236e039c75efdb487f17a902fdf94f9dacaa9884329c85d9651', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 0', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 1', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 2', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 3', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 4', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 5', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 6', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 7', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 8', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password').then(function(encryptedLogin) { - assert.equal('63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 9', function() { - return LessPass.encryptLogin('lesspass', 'password').then(function(encryptedLogin) { - assert.equal('7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116', encryptedLogin); - }); - }); - it('encryptLogin auto generated test 10', function() { - return LessPass.encryptLogin('contact@lesspass.com', 'password2').then(function(encryptedLogin) { - assert.equal('ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4', encryptedLogin); - }); - }); - }); - - describe('renderPassword', function() { - it('render password', function(done) { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - done(); - }) - }); - it('render password with a custom template', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'n' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - var i = generatedPassword.length; - while (i--) { - assert('0123456789'.indexOf(generatedPassword[i]) !== -1) - } - }) - }); - it('render password with a custom template too short', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'CvcnCVsn' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('Sor4WU:8Wad5', generatedPassword); - }) - }); - it('render password with a custom template too long', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 6, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - template: 'CvcnCVsn' - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('Sor4WU', generatedPassword); - }) - }); - it('render password auto generated test 0', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - }) - }); - it('render password auto generated test 1', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 14, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('azYS7,olOL2]iz', generatedPassword); - }) - }); - it('render password auto generated test 2', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: false, - numbers: false, - symbols: false, - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('azyseqololat', generatedPassword); - }) - }); - it('render password auto generated test 3', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: false, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('AZ3[EQ7@OL2]', generatedPassword); - }) - }); - it('render password auto generated test 4', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('4?3[7,7@7@2]', generatedPassword); - }) - }); - it('render password auto generated test 5', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: false, - uppercase: false, - numbers: false, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('[?=[&,:@:@[]', generatedPassword); - }) - }); - it('render password auto generated test 6', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: false - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('azYS7uwAW8at', generatedPassword); - }) - }); - it('render password auto generated test 7', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: false, - symbols: false - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('azYSeqOLolAT', generatedPassword); - }) - }); - it('render password auto generated test 8', function() { - var site = 'lesspass.com'; - var encryptedLogin = '63d850713d0b2f7f2c4396fe93f4ac0c6bc7485f9e7473c4b8c4a33ec12199c0'; - var passwordOptions = { - counter: 2, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('obYT2=olOV9=', generatedPassword); - }) - }); - it('render password auto generated test 9', function() { - var site = 'lesspass.com'; - var encryptedLogin = '7d05ee25597dcc3ac16d082aa910e7707f75be620ed8db5bef7245e2a8579116'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('erOC1%imIW3,', generatedPassword); - }) - }); - it('render password auto generated test 10', function() { - var site = 'lesspass.com'; - var encryptedLogin = 'ce853092fc54fe88c281e38df97bd5826d64e6bee315dc94939cbba8930df0e4'; - var passwordOptions = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - return LessPass.renderPassword(encryptedLogin, site, passwordOptions).then(function(generatedPassword) { - assert.equal('uvUM5_ucUP5=', generatedPassword); - }) - }); - - - }); - describe('fingerprint', function() { - it('createFingerprint', function() { - return LessPass.createFingerprint('password').then(function(fingerprint) { - assert.equal('e56a207acd1e6714735487c199c6f095844b7cc8e5971d86c003a7b6f36ef51e', fingerprint); - }) - }); - }); - - describe('generatePassword', function() { - it('generate password', function() { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('izIS5@ozYM2?', generatedPassword); - }); - }); - it('generate password auto generated test 0', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('azYS7,olOL2]', generatedPassword); - }); - }); - it('generate password auto generated test 1', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 14, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('azYS7,olOL2]iz', generatedPassword); - }); - }); - it('generate password auto generated test 2', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: false, - numbers: false, - symbols: false, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('azyseqololat', generatedPassword); - }); - }); - it('generate password auto generated test 3', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('AZ3[EQ7@OL2]', generatedPassword); - }); - }); - it('generate password auto generated test 4', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: false, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('4?3[7,7@7@2]', generatedPassword); - }); - }); - it('generate password auto generated test 5', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: false, - numbers: false, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('[?=[&,:@:@[]', generatedPassword); - }); - }); - it('generate password auto generated test 6', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: false, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('azYS7uwAW8at', generatedPassword); - }); - }); - it('generate password auto generated test 7', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: false, - symbols: false, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('azYSeqOLolAT', generatedPassword); - }); - }); - it('generate password auto generated test 8', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 2, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('obYT2=olOV9=', generatedPassword); - }); - }); - it('generate password auto generated test 9', function() { - var site = 'lesspass.com'; - var login = 'lesspass'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('erOC1%imIW3,', generatedPassword); - }); - }); - it('generate password auto generated test 10', function() { - var site = 'lesspass.com'; - var login = 'contact@lesspass.com'; - var masterPassword = 'password2'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 12, - counter: 1, - version: 1, - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('uvUM5_ucUP5=', generatedPassword); - }); - }); - }); -}); - diff --git a/tests/v1/deriveEncryptedLogin.tests.js b/tests/v1/deriveEncryptedLogin.tests.js deleted file mode 100644 index ca5045f..0000000 --- a/tests/v1/deriveEncryptedLogin.tests.js +++ /dev/null @@ -1,84 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v1', function() { - describe('deriveEncryptedLogin', function() { - it('should createHmac', function() { - var encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - var salt = 'lesspass.com1'; - return LessPass._createHmac(encryptedLogin, salt).then(function(hmac) { - assert.equal('be00f942fc8aa67d8e76fc2456862b9d66d166ebfdd3dc2f0116e278209532ed', hmac); - }); - }); - it('should derive encrypted login with default options 1', function() { - const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(generatedPassword) { - assert.equal('ecd16aefc7e5', generatedPassword); - }); - }); - it('should derive encrypted login with default options 2', function() { - const encryptedLogin = '90cff82b8847525370a8f29a59ecf45db62c719a535788ad0df58d32304e925d'; - const site = 'lesspass.com'; - const option = { - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - }; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function(generatedPassword) { - assert.equal('ecd16aefc7e5', generatedPassword); - }); - }); - it('should derive encrypted login with defined length', function() { - var encryptedLogin = 'd79d8482f708122288af7b259393a58fe05840f4555cc935cdd3f062b9aa75ed'; - var site = 'lesspass.com'; - var option = { - counter: 1, - length: 10, - }; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function(generatedPassword) { - assert.equal(10, generatedPassword.length); - }); - }); - it('should return two different passwords if site different 1', function() { - const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'google.com'; - return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(derivedEncryptedLogin) { - assert.equal('a957c3a459ec', derivedEncryptedLogin) - }); - }); - it('should return two different passwords if site different 2', function() { - const encryptedLogin = 'f4fd3885fb70085f2285c3382e2d9adb4c2553285fc45dd896791aa5e79070a9'; - const site = 'facebook.com'; - return LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(derivedEncryptedLogin) { - assert.equal('d9f3a918c34b', derivedEncryptedLogin) - }); - }); - it('should return two different passwords if counter different 1', function() { - const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option = {counter: 1}; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option).then(function(derivedEncryptedLogins) { - assert.equal('bb2e0b34036d', derivedEncryptedLogins) - }); - }); - it('should return two different passwords if counter different 2', function() { - const encryptedLogin = 'dfba06278c9aa24d992bc2d390a53efef482788859455875f72015335d085fcd'; - const site = 'lesspass.com'; - const option2 = {counter: 2}; - return LessPass._deriveEncryptedLogin(encryptedLogin, site, option2).then(function(derivedEncryptedLogins) { - assert.equal('67fe8c05a248', derivedEncryptedLogins) - }); - }); - it('should derive encrypted login with sha 256', function() { - const encryptedLogin = '9f505f3a95fe0485da3242cb81c9fe25c2f400d8399737655a8dad2b52778d88'; - const site = 'lesspass.com'; - LessPass._deriveEncryptedLogin(encryptedLogin, site).then(function(encryptedLogin) { - assert.equal('be00f942fc8a', encryptedLogin); - }); - }); - }); -}); - diff --git a/tests/v1/getPasswordTemplate.tests.js b/tests/v1/getPasswordTemplate.tests.js deleted file mode 100644 index 1072173..0000000 --- a/tests/v1/getPasswordTemplate.tests.js +++ /dev/null @@ -1,63 +0,0 @@ -var assert = chai.assert; - -describe('Lessass v1', function() { - describe('getPasswordTemplate', function() { - it('should get default template', function() { - assert.equal('vcVCns', LessPass._getPasswordTemplate({ - counter: 1, - length: 12, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - })); - }); - it('should get lowercase template', function() { - assert.equal('vc', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: false, - symbols: false - })); - }); - it('should get uppercase template', function() { - assert.equal('VC', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: true, - numbers: false, - symbols: false - })); - }); - it('should get numbers template', function() { - assert.equal('n', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: true, - symbols: false - })); - }); - it('should get symbols template', function() { - assert.equal('s', LessPass._getPasswordTemplate({ - lowercase: false, - uppercase: false, - numbers: false, - symbols: true - })); - }); - it('should concatenate template if two password settings', function() { - assert.equal('vcVC', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: true, - numbers: false, - symbols: false - })); - assert.equal('vcns', LessPass._getPasswordTemplate({ - lowercase: true, - uppercase: false, - numbers: true, - symbols: true - })); - }); - }); -}); - diff --git a/tests/v1/prettyPrint.js b/tests/v1/prettyPrint.js deleted file mode 100644 index ff259db..0000000 --- a/tests/v1/prettyPrint.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v1', function() { - describe('prettyPrint', function() { - it('should print different password if templates different', function() { - var encryptedLogin = '78ae5892055ab59fdd54489ae30928d322841a27590b65cf875fcfdd083f7c32'; - assert.notEqual(LessPass._prettyPrint(encryptedLogin, 'cv'), LessPass._prettyPrint(encryptedLogin, 'vc')); - }); - it('must return a string of the same length as the input', function() { - var hash = 'f5785e569ab5d38b02e2248c798ac17df90f57a85f34a9d5382408c2f0d9532d'; - assert.equal(hash.length, LessPass._prettyPrint(hash, 'cv').length); - }); - it('should return char inside a string based on modulo of the index', function() { - var template = 'cv'; - assert.equal('c', LessPass._getCharType(template, 0)); - assert.equal('v', LessPass._getCharType(template, 1)); - assert.equal('c', LessPass._getCharType(template, 10)); - }); - it('should convert a string into an array of char code', function() { - var charCodes = LessPass._string2charCodes('ab40f6ee71'); - assert.equal(97, charCodes[0]); - assert.equal(98, charCodes[1]); - assert.equal(10, charCodes.length); - }); - it('should get password char based on its type and index', function() { - var typeVowel = 'V'; - assert.equal('A', LessPass._getPasswordChar(typeVowel, 0)); - }); - it('should modulo if overflow', function() { - var typeVowel = 'V'; - assert.equal('E', LessPass._getPasswordChar(typeVowel, 1)); - assert.equal('E', LessPass._getPasswordChar(typeVowel, 7)); - }); - }); -}); diff --git a/tests/v2/api.tests.js b/tests/v2/api.tests.js deleted file mode 100644 index e6ffcb1..0000000 --- a/tests/v2/api.tests.js +++ /dev/null @@ -1,88 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v2', function() { - describe('API', function() { - it('render password', function() { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - length: 16, - counter: 1, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('WHLpUL)e00[iHR+w', generatedPassword); - }); - }); - it('render password no symbols', function() { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: true, - symbols: false, - length: 14, - counter: 2, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('MBAsB7b1Prt8Sl', generatedPassword); - }); - }); - it('render password only digit', function() { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: false, - uppercase: false, - numbers: true, - symbols: false, - length: 6, - counter: 3, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal('117843', generatedPassword); - }); - }); - it('render password no number', function() { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - lowercase: true, - uppercase: true, - numbers: false, - symbols: true, - length: 14, - counter: 1, - version: 2 - }; - return LessPass.generatePassword(site, login, masterPassword, passwordProfile).then(function(generatedPassword) { - assert.equal("sB>{qF}wN%/-fm", generatedPassword); - }); - }); - it('render password with default options', function() { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - return LessPass.generatePassword(site, login, masterPassword).then(function(generatedPassword) { - assert.equal('WHLpUL)e00[iHR+w', generatedPassword); - }); - }); - }); -}); - diff --git a/tests/v2/entropy.tests.js b/tests/v2/entropy.tests.js deleted file mode 100644 index 30c25f2..0000000 --- a/tests/v2/entropy.tests.js +++ /dev/null @@ -1,58 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v2', function() { - describe('entropy', function() { - it('calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)', function() { - this.timeout(10000); - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - iterations: 100000, - keylen: 32, - digest: 'sha256', - counter: 1 - }; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function(entropy) { - assert.equal('dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e', entropy); - }); - }); - it('calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)', function() { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile = { - iterations: 8192, - keylen: 16, - digest: 'sha512', - counter: 1 - }; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile).then(function(entropy) { - assert.equal('fff211c16a4e776b3574c6a5c91fd252', entropy); - }); - }); - it('calc entropy different if counter different 1', function() { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile1 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 1}; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile1).then(function(entropy) { - assert.equal('d3ec1e988dd0b3640c7491cd2c2a88b5', entropy) - }); - }); - it('calc entropy different if counter different 2', function() { - var site = 'example.org'; - var login = 'contact@example.org'; - var masterPassword = 'password'; - var passwordProfile2 = {iterations: 1, keylen: 16, digest: 'sha256', counter: 2}; - return LessPass._calcEntropy(site, login, masterPassword, passwordProfile2).then(function(entropy) { - assert.equal('ddfb1136260f930c21f6d72f6eddbd40', entropy) - }); - }); - it('consume entropy', function() { - var password = LessPass._consumeEntropy('', bigInt(4 * 4 + 2), "abcd", 2); - assert.equal('ca', password.value); - assert.equal(1, password.entropy) - }); - }); -}); diff --git a/tests/v2/renderPassword.tests.js b/tests/v2/renderPassword.tests.js deleted file mode 100644 index 2de96f1..0000000 --- a/tests/v2/renderPassword.tests.js +++ /dev/null @@ -1,70 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v2', function() { - var defaultPasswordProfile = { - length: 16, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - it('render password use remainder of long division beetween entropy and set of chars length as an index', function() { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal('W', LessPass._renderPassword(entropy, defaultPasswordProfile)[0]); - }); - it('render password use quotient as second entropy recursively', function() { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal('H', LessPass._renderPassword(entropy, defaultPasswordProfile)[1]); - }); - it('render password has default length of 16', function() { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - assert.equal(16, LessPass._renderPassword(entropy, defaultPasswordProfile).length); - }); - it('render password can specify length', function() { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var passwordProfile = { - length: 20, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true - }; - assert.equal(20, LessPass._renderPassword(entropy, passwordProfile).length); - }); - it('include one char per set of characters', function() { - var password = LessPass._insertStringPseudoRandomly('123456', bigInt(7 * 6 + 2), 'uT'); - assert.equal('T12u3456', password); - }); - it('render password return at least one char in every characters set', function() { - var entropy = 'dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e'; - var passwordProfile = { - length: 6, - lowercase: true, - uppercase: true, - numbers: true, - symbols: true, - }; - var generatedPassword = LessPass._renderPassword(entropy, passwordProfile); - var passwordLength = generatedPassword.length; - var lowercaseOk = false; - var uppercaseOk = false; - var numbersOk = false; - var symbolsOk = false; - while (passwordLength--) { - if ('abcdefghijklmnopqrstuvwxyz'.indexOf(generatedPassword[passwordLength]) !== -1) { - lowercaseOk = true; - } - if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(generatedPassword[passwordLength]) !== -1) { - uppercaseOk = true; - } - if ('0123456789'.indexOf(generatedPassword[passwordLength]) !== -1) { - numbersOk = true; - } - if ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.indexOf(generatedPassword[passwordLength]) !== -1) { - symbolsOk = true; - } - } - assert.equal(6, generatedPassword.length); - assert(lowercaseOk && uppercaseOk && numbersOk && symbolsOk, 'there is no at least one char in every characters set'); - }); -}); diff --git a/tests/v2/setOfCharacters.tests.js b/tests/v2/setOfCharacters.tests.js deleted file mode 100644 index 82134fa..0000000 --- a/tests/v2/setOfCharacters.tests.js +++ /dev/null @@ -1,59 +0,0 @@ -var assert = chai.assert; - -describe('LessPass v2', function() { - describe('set of characters', function() { - it('get default set of characters', function() { - var setOfCharacters = LessPass._getSetOfCharacters(); - assert.equal( - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', - setOfCharacters - ); - assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); - }); - it('get default set of characters concat rules in order', function() { - var setOfCharacters = LessPass._getSetOfCharacters(['lowercase', 'uppercase', 'numbers']); - assert.equal('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', setOfCharacters); - assert.equal(26 * 2 + 10, setOfCharacters.length); - }); - it('get set of characters only lowercase', function() { - var setOfCharacters = LessPass._getSetOfCharacters(['lowercase']); - assert.equal('abcdefghijklmnopqrstuvwxyz', setOfCharacters); - assert.equal(26, setOfCharacters.length); - }); - it('get set of characters only uppercase', function() { - var setOfCharacters = LessPass._getSetOfCharacters(['uppercase']); - assert.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZ', setOfCharacters); - assert.equal(26, setOfCharacters.length); - }); - it('get set of characters only numbers', function() { - var setOfCharacters = LessPass._getSetOfCharacters(['numbers']); - assert.equal('0123456789', setOfCharacters); - assert.equal(10, setOfCharacters.length); - }); - it('get set of characters only symbols', function() { - var setOfCharacters = LessPass._getSetOfCharacters(['symbols']); - assert.equal('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', setOfCharacters); - assert.equal(32, setOfCharacters.length); - }); - it('generate one char per rules', function() { - var oneCharPerSetOfCharacters = LessPass._getOneCharPerRule( - bigInt(26 * 26), - ['lowercase', 'uppercase'] - ); - assert.equal('aA', oneCharPerSetOfCharacters.value); - assert.equal(2, oneCharPerSetOfCharacters.value.length); - assert.equal(1, oneCharPerSetOfCharacters.entropy); - }); - it('configured rules', function() { - assert.deepEqual(['uppercase'], LessPass._getConfiguredRules({uppercase: true})); - assert.deepEqual(['lowercase', 'uppercase'], LessPass._getConfiguredRules({uppercase: true, lowercase: true})); - assert.deepEqual(['lowercase'], LessPass._getConfiguredRules({lowercase: true, symbols: false})); - assert.deepEqual(['lowercase', 'uppercase', 'numbers', 'symbols'], LessPass._getConfiguredRules({ - lowercase: true, - uppercase: true, - symbols: true, - numbers: true - })); - }); - }); -}); diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index ca67413..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,25 +0,0 @@ -var path = require('path'); -var webpack = require('webpack'); - -var production = process.env.NODE_ENV === 'production' || false; - -module.exports = { - entry: './src/lesspass.js', - output: { - filename: production ? 'lesspass.min.js' : 'lesspass.js', - path: path.resolve(__dirname, 'dist'), - library: 'LessPass', - libraryTarget: 'umd' - }, - module: { - rules: [ - {test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"} - ] - }, - plugins: production ? [ - new webpack.optimize.UglifyJsPlugin({ - beautify: false, - comments: false - }) - ] : [] -}; From 9627a1323b4e7d6a94559bdfd03732da8da77c5d Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Tue, 9 May 2017 12:01:09 +0200 Subject: [PATCH 117/124] Build minified js file fix https://github.com/lesspass/lesspass/issues/220 --- dist/lesspass.js | 18847 ++++++++++++++++++++++--------------------------- dist/lesspass.min.js | 1 + example/index.html | 2 +- package.json | 13 +- test/karma.conf.js | 2 +- 5 files changed, 8578 insertions(+), 10287 deletions(-) create mode 100644 dist/lesspass.min.js diff --git a/dist/lesspass.js b/dist/lesspass.js index 5c835f8..cdd329b 100644 --- a/dist/lesspass.js +++ b/dist/lesspass.js @@ -1,1725 +1,1491 @@ -(function(f) { - if (typeof exports === "object" && typeof module !== "undefined") { - module.exports = f(); - } else if (typeof define === "function" && define.amd) { - define([], f); - } else { - var g; - if (typeof window !== "undefined") { - g = window; - } else if (typeof global !== "undefined") { - g = global; - } else if (typeof self !== "undefined") { - g = self; - } else { - g = this; - } - g.LessPass = f(); - } -})(function() { - var define, module, exports; - return (function e(t, n, r) { - function s(o, u) { - if (!n[o]) { - if (!t[o]) { - var a = typeof require == "function" && require; - if (!u && a) return a(o, !0); - if (i) return i(o, !0); - var f = new Error("Cannot find module '" + o + "'"); - throw ((f.code = "MODULE_NOT_FOUND"), f); - } - var l = (n[o] = { exports: {} }); - t[o][0].call( - l.exports, - function(e) { - var n = t[o][1][e]; - return s(n ? n : e); - }, - l, - l.exports, - e, - t, - n, - r - ); - } - return n[o].exports; - } - var i = typeof require == "function" && require; - for (var o = 0; o < r.length; o++) s(r[o]); - return s; - })( - { - 1: [ - function(require, module, exports) { - "use strict"; - exports.byteLength = byteLength; - exports.toByteArray = toByteArray; - exports.fromByteArray = fromByteArray; - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - - var code = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup["-".charCodeAt(0)] = 62; - revLookup["_".charCodeAt(0)] = 63; - - function placeHoldersCount(b64) { - var len = b64.length; - if (len % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0; - } - - function byteLength(b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64); - } - - function toByteArray(b64) { - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - placeHolders = placeHoldersCount(b64); - - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for ((i = 0), (j = 0); i < l; (i += 4), (j += 3)) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xff; - arr[L++] = (tmp >> 8) & 0xff; - arr[L++] = tmp & 0xff; - } - - if (placeHolders === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xff; - } else if (placeHolders === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xff; - arr[L++] = tmp & 0xff; - } - - return arr; - } - - function tripletToBase64(num) { - return ( - lookup[(num >> 18) & 0x3f] + - lookup[(num >> 12) & 0x3f] + - lookup[(num >> 6) & 0x3f] + - lookup[num & 0x3f] - ); - } - - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; - output.push(tripletToBase64(tmp)); - } - return output.join(""); - } - - function fromByteArray(uint8) { - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ""; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for ( - var i = 0, len2 = len - extraBytes; - i < len2; - i += maxChunkLength - ) { - parts.push( - encodeChunk( - uint8, - i, - i + maxChunkLength > len2 ? len2 : i + maxChunkLength - ) - ); - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3f]; - output += "=="; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3f]; - output += lookup[(tmp << 2) & 0x3f]; - output += "="; - } - - parts.push(output); - - return parts.join(""); - } - }, - {} - ], - 2: [ - function(require, module, exports) { - var bigInt = (function(undefined) { - "use strict"; - var BASE = 1e7, - LOG_BASE = 7, - MAX_INT = 9007199254740992, - MAX_INT_ARR = smallToArray(MAX_INT), - LOG_MAX_INT = Math.log(MAX_INT); - - function Integer(v, radix) { - if (typeof v === "undefined") return Integer[0]; - if (typeof radix !== "undefined") - return +radix === 10 ? parseValue(v) : parseBase(v, radix); - return parseValue(v); - } - - function BigInteger(value, sign) { - this.value = value; - this.sign = sign; - this.isSmall = false; - } - BigInteger.prototype = Object.create(Integer.prototype); - - function SmallInteger(value) { - this.value = value; - this.sign = value < 0; - this.isSmall = true; - } - SmallInteger.prototype = Object.create(Integer.prototype); - - function isPrecise(n) { - return -MAX_INT < n && n < MAX_INT; - } - - function smallToArray(n) { - // For performance reasons doesn't reference BASE, need to change this function if BASE changes - if (n < 1e7) return [n]; - if (n < 1e14) return [n % 1e7, Math.floor(n / 1e7)]; - return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; - } - - function arrayToSmall(arr) { - // If BASE changes this function may need to change - trim(arr); - var length = arr.length; - if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { - switch (length) { - case 0: - return 0; - case 1: - return arr[0]; - case 2: - return arr[0] + arr[1] * BASE; - default: - return arr[0] + (arr[1] + arr[2] * BASE) * BASE; - } - } - return arr; - } - - function trim(v) { - var i = v.length; - while (v[--i] === 0); - v.length = i + 1; - } - - function createArray(length) { - // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger - var x = new Array(length); - var i = -1; - while (++i < length) { - x[i] = 0; - } - return x; - } - - function truncate(n) { - if (n > 0) return Math.floor(n); - return Math.ceil(n); - } - - function add(a, b) { - // assumes a and b are arrays with a.length >= b.length - var l_a = a.length, - l_b = b.length, - r = new Array(l_a), - carry = 0, - base = BASE, - sum, - i; - for (i = 0; i < l_b; i++) { - sum = a[i] + b[i] + carry; - carry = sum >= base ? 1 : 0; - r[i] = sum - carry * base; - } - while (i < l_a) { - sum = a[i] + carry; - carry = sum === base ? 1 : 0; - r[i++] = sum - carry * base; - } - if (carry > 0) r.push(carry); - return r; - } - - function addAny(a, b) { - if (a.length >= b.length) return add(a, b); - return add(b, a); - } - - function addSmall(a, carry) { - // assumes a is array, carry is number with 0 <= carry < MAX_INT - var l = a.length, r = new Array(l), base = BASE, sum, i; - for (i = 0; i < l; i++) { - sum = a[i] - base + carry; - carry = Math.floor(sum / base); - r[i] = sum - carry * base; - carry += 1; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - BigInteger.prototype.add = function(v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.subtract(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) { - return new BigInteger(addSmall(a, Math.abs(b)), this.sign); - } - return new BigInteger(addAny(a, b), this.sign); - }; - BigInteger.prototype.plus = BigInteger.prototype.add; - - SmallInteger.prototype.add = function(v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.subtract(n.negate()); - } - var b = n.value; - if (n.isSmall) { - if (isPrecise(a + b)) return new SmallInteger(a + b); - b = smallToArray(Math.abs(b)); - } - return new BigInteger(addSmall(b, Math.abs(a)), a < 0); - }; - SmallInteger.prototype.plus = SmallInteger.prototype.add; - - function subtract(a, b) { - // assumes a and b are arrays with a >= b - var a_l = a.length, - b_l = b.length, - r = new Array(a_l), - borrow = 0, - base = BASE, - i, - difference; - for (i = 0; i < b_l; i++) { - difference = a[i] - borrow - b[i]; - if (difference < 0) { - difference += base; - borrow = 1; - } else borrow = 0; - r[i] = difference; - } - for (i = b_l; i < a_l; i++) { - difference = a[i] - borrow; - if (difference < 0) difference += base; - else { - r[i++] = difference; - break; - } - r[i] = difference; - } - for (; i < a_l; i++) { - r[i] = a[i]; - } - trim(r); - return r; - } - - function subtractAny(a, b, sign) { - var value; - if (compareAbs(a, b) >= 0) { - value = subtract(a, b); - } else { - value = subtract(b, a); - sign = !sign; - } - value = arrayToSmall(value); - if (typeof value === "number") { - if (sign) value = -value; - return new SmallInteger(value); - } - return new BigInteger(value, sign); - } - - function subtractSmall(a, b, sign) { - // assumes a is array, b is number with 0 <= b < MAX_INT - var l = a.length, - r = new Array(l), - carry = -b, - base = BASE, - i, - difference; - for (i = 0; i < l; i++) { - difference = a[i] + carry; - carry = Math.floor(difference / base); - difference %= base; - r[i] = difference < 0 ? difference + base : difference; - } - r = arrayToSmall(r); - if (typeof r === "number") { - if (sign) r = -r; - return new SmallInteger(r); - } - return new BigInteger(r, sign); - } - - BigInteger.prototype.subtract = function(v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.add(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) return subtractSmall(a, Math.abs(b), this.sign); - return subtractAny(a, b, this.sign); - }; - BigInteger.prototype.minus = BigInteger.prototype.subtract; - - SmallInteger.prototype.subtract = function(v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.add(n.negate()); - } - var b = n.value; - if (n.isSmall) { - return new SmallInteger(a - b); - } - return subtractSmall(b, Math.abs(a), a >= 0); - }; - SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - - BigInteger.prototype.negate = function() { - return new BigInteger(this.value, !this.sign); - }; - SmallInteger.prototype.negate = function() { - var sign = this.sign; - var small = new SmallInteger(-this.value); - small.sign = !sign; - return small; - }; - - BigInteger.prototype.abs = function() { - return new BigInteger(this.value, false); - }; - SmallInteger.prototype.abs = function() { - return new SmallInteger(Math.abs(this.value)); - }; - - function multiplyLong(a, b) { - var a_l = a.length, - b_l = b.length, - l = a_l + b_l, - r = createArray(l), - base = BASE, - product, - carry, - i, - a_i, - b_j; - for (i = 0; i < a_l; ++i) { - a_i = a[i]; - for (var j = 0; j < b_l; ++j) { - b_j = b[j]; - product = a_i * b_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; - } - } - trim(r); - return r; - } - - function multiplySmall(a, b) { - // assumes a is array, b is number with |b| < BASE - var l = a.length, - r = new Array(l), - base = BASE, - carry = 0, - product, - i; - for (i = 0; i < l; i++) { - product = a[i] * b + carry; - carry = Math.floor(product / base); - r[i] = product - carry * base; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - function shiftLeft(x, n) { - var r = []; - while (n-- > 0) - r.push(0); - return r.concat(x); - } - - function multiplyKaratsuba(x, y) { - var n = Math.max(x.length, y.length); - - if (n <= 30) return multiplyLong(x, y); - n = Math.ceil(n / 2); - - var b = x.slice(n), - a = x.slice(0, n), - d = y.slice(n), - c = y.slice(0, n); - - var ac = multiplyKaratsuba(a, c), - bd = multiplyKaratsuba(b, d), - abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); - - var product = addAny( - addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), - shiftLeft(bd, 2 * n) - ); - trim(product); - return product; - } - - // The following function is derived from a surface fit of a graph plotting the performance difference - // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. - function useKaratsuba(l1, l2) { - return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; - } - - BigInteger.prototype.multiply = function(v) { - var n = parseValue(v), - a = this.value, - b = n.value, - sign = this.sign !== n.sign, - abs; - if (n.isSmall) { - if (b === 0) return Integer[0]; - if (b === 1) return this; - if (b === -1) return this.negate(); - abs = Math.abs(b); - if (abs < BASE) { - return new BigInteger(multiplySmall(a, abs), sign); - } - b = smallToArray(abs); - } - if ( - useKaratsuba(a.length, b.length) // Karatsuba is only faster for certain array sizes - ) - return new BigInteger(multiplyKaratsuba(a, b), sign); - return new BigInteger(multiplyLong(a, b), sign); - }; - - BigInteger.prototype.times = BigInteger.prototype.multiply; - - function multiplySmallAndArray(a, b, sign) { - // a >= 0 - if (a < BASE) { - return new BigInteger(multiplySmall(b, a), sign); - } - return new BigInteger(multiplyLong(b, smallToArray(a)), sign); - } - SmallInteger.prototype._multiplyBySmall = function(a) { - if (isPrecise(a.value * this.value)) { - return new SmallInteger(a.value * this.value); - } - return multiplySmallAndArray( - Math.abs(a.value), - smallToArray(Math.abs(this.value)), - this.sign !== a.sign - ); - }; - BigInteger.prototype._multiplyBySmall = function(a) { - if (a.value === 0) return Integer[0]; - if (a.value === 1) return this; - if (a.value === -1) return this.negate(); - return multiplySmallAndArray( - Math.abs(a.value), - this.value, - this.sign !== a.sign - ); - }; - SmallInteger.prototype.multiply = function(v) { - return parseValue(v)._multiplyBySmall(this); - }; - SmallInteger.prototype.times = SmallInteger.prototype.multiply; - - function square(a) { - var l = a.length, - r = createArray(l + l), - base = BASE, - product, - carry, - i, - a_i, - a_j; - for (i = 0; i < l; i++) { - a_i = a[i]; - for (var j = 0; j < l; j++) { - a_j = a[j]; - product = a_i * a_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; - } - } - trim(r); - return r; - } - - BigInteger.prototype.square = function() { - return new BigInteger(square(this.value), false); - }; - - SmallInteger.prototype.square = function() { - var value = this.value * this.value; - if (isPrecise(value)) return new SmallInteger(value); - return new BigInteger( - square(smallToArray(Math.abs(this.value))), - false - ); - }; - - function divMod1(a, b) { - // Left over from previous version. Performs faster than divMod2 on smaller input sizes. - var a_l = a.length, - b_l = b.length, - base = BASE, - result = createArray(b.length), - divisorMostSignificantDigit = b[b_l - 1], - // normalization - lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), - remainder = multiplySmall(a, lambda), - divisor = multiplySmall(b, lambda), - quotientDigit, - shift, - carry, - borrow, - i, - l, - q; - if (remainder.length <= a_l) remainder.push(0); - divisor.push(0); - divisorMostSignificantDigit = divisor[b_l - 1]; - for (shift = a_l - b_l; shift >= 0; shift--) { - quotientDigit = base - 1; - if (remainder[shift + b_l] !== divisorMostSignificantDigit) { - quotientDigit = Math.floor( - (remainder[shift + b_l] * base + - remainder[shift + b_l - 1]) / - divisorMostSignificantDigit - ); - } - // quotientDigit <= base - 1 - carry = 0; - borrow = 0; - l = divisor.length; - for (i = 0; i < l; i++) { - carry += quotientDigit * divisor[i]; - q = Math.floor(carry / base); - borrow += remainder[shift + i] - (carry - q * base); - carry = q; - if (borrow < 0) { - remainder[shift + i] = borrow + base; - borrow = -1; - } else { - remainder[shift + i] = borrow; - borrow = 0; - } - } - while (borrow !== 0) { - quotientDigit -= 1; - carry = 0; - for (i = 0; i < l; i++) { - carry += remainder[shift + i] - base + divisor[i]; - if (carry < 0) { - remainder[shift + i] = carry + base; - carry = 0; - } else { - remainder[shift + i] = carry; - carry = 1; - } - } - borrow += carry; - } - result[shift] = quotientDigit; - } - // denormalization - remainder = divModSmall(remainder, lambda)[0]; - return [arrayToSmall(result), arrayToSmall(remainder)]; - } - - function divMod2(a, b) { - // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ - // Performs faster than divMod1 on larger input sizes. - var a_l = a.length, - b_l = b.length, - result = [], - part = [], - base = BASE, - guess, - xlen, - highx, - highy, - check; - while (a_l) { - part.unshift(a[--a_l]); - trim(part); - if (compareAbs(part, b) < 0) { - result.push(0); - continue; - } - xlen = part.length; - highx = part[xlen - 1] * base + part[xlen - 2]; - highy = b[b_l - 1] * base + b[b_l - 2]; - if (xlen > b_l) { - highx = (highx + 1) * base; - } - guess = Math.ceil(highx / highy); - do { - check = multiplySmall(b, guess); - if (compareAbs(check, part) <= 0) break; - guess--; - } while (guess); - result.push(guess); - part = subtract(part, check); - } - result.reverse(); - return [arrayToSmall(result), arrayToSmall(part)]; - } - - function divModSmall(value, lambda) { - var length = value.length, - quotient = createArray(length), - base = BASE, - i, - q, - remainder, - divisor; - remainder = 0; - for (i = length - 1; i >= 0; --i) { - divisor = remainder * base + value[i]; - q = truncate(divisor / lambda); - remainder = divisor - q * lambda; - quotient[i] = q | 0; - } - return [quotient, remainder | 0]; - } +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LessPass = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - function divModAny(self, v) { - var value, n = parseValue(v); - var a = self.value, b = n.value; - var quotient; - if (b === 0) throw new Error("Cannot divide by zero"); - if (self.isSmall) { - if (n.isSmall) { - return [ - new SmallInteger(truncate(a / b)), - new SmallInteger(a % b) - ]; - } - return [Integer[0], self]; - } - if (n.isSmall) { - if (b === 1) return [self, Integer[0]]; - if (b == -1) return [self.negate(), Integer[0]]; - var abs = Math.abs(b); - if (abs < BASE) { - value = divModSmall(a, abs); - quotient = arrayToSmall(value[0]); - var remainder = value[1]; - if (self.sign) remainder = -remainder; - if (typeof quotient === "number") { - if (self.sign !== n.sign) quotient = -quotient; - return [ - new SmallInteger(quotient), - new SmallInteger(remainder) - ]; - } - return [ - new BigInteger(quotient, self.sign !== n.sign), - new SmallInteger(remainder) - ]; - } - b = smallToArray(abs); - } - var comparison = compareAbs(a, b); - if (comparison === -1) return [Integer[0], self]; - if (comparison === 0) - return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; - - // divMod1 is faster on smaller input sizes - if (a.length + b.length <= 200) value = divMod1(a, b); - else value = divMod2(a, b); - - quotient = value[0]; - var qSign = self.sign !== n.sign, - mod = value[1], - mSign = self.sign; - if (typeof quotient === "number") { - if (qSign) quotient = -quotient; - quotient = new SmallInteger(quotient); - } else quotient = new BigInteger(quotient, qSign); - if (typeof mod === "number") { - if (mSign) mod = -mod; - mod = new SmallInteger(mod); - } else mod = new BigInteger(mod, mSign); - return [quotient, mod]; - } + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} - BigInteger.prototype.divmod = function(v) { - var result = divModAny(this, v); - return { - quotient: result[0], - remainder: result[1] - }; - }; - SmallInteger.prototype.divmod = BigInteger.prototype.divmod; - - BigInteger.prototype.divide = function(v) { - return divModAny(this, v)[0]; - }; - SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = - BigInteger.prototype.divide; - - BigInteger.prototype.mod = function(v) { - return divModAny(this, v)[1]; - }; - SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = - BigInteger.prototype.mod; - - BigInteger.prototype.pow = function(v) { - var n = parseValue(v), a = this.value, b = n.value, value, x, y; - if (b === 0) return Integer[1]; - if (a === 0) return Integer[0]; - if (a === 1) return Integer[1]; - if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.sign) { - return Integer[0]; - } - if (!n.isSmall) - throw new Error( - "The exponent " + n.toString() + " is too large." - ); - if (this.isSmall) { - if (isPrecise((value = Math.pow(a, b)))) - return new SmallInteger(truncate(value)); - } - x = this; - y = Integer[1]; - while (true) { - if (b & (1 === 1)) { - y = y.times(x); - --b; - } - if (b === 0) break; - b /= 2; - x = x.square(); - } - return y; - }; - SmallInteger.prototype.pow = BigInteger.prototype.pow; - - BigInteger.prototype.modPow = function(exp, mod) { - exp = parseValue(exp); - mod = parseValue(mod); - if (mod.isZero()) - throw new Error("Cannot take modPow with modulus 0"); - var r = Integer[1], base = this.mod(mod); - while (exp.isPositive()) { - if (base.isZero()) return Integer[0]; - if (exp.isOdd()) r = r.multiply(base).mod(mod); - exp = exp.divide(2); - base = base.square().mod(mod); - } - return r; - }; - SmallInteger.prototype.modPow = BigInteger.prototype.modPow; +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} - function compareAbs(a, b) { - if (a.length !== b.length) { - return a.length > b.length ? 1 : -1; - } - for (var i = a.length - 1; i >= 0; i--) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; - } +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) - BigInteger.prototype.compareAbs = function(v) { - var n = parseValue(v), a = this.value, b = n.value; - if (n.isSmall) return 1; - return compareAbs(a, b); - }; - SmallInteger.prototype.compareAbs = function(v) { - var n = parseValue(v), a = Math.abs(this.value), b = n.value; - if (n.isSmall) { - b = Math.abs(b); - return a === b ? 0 : a > b ? 1 : -1; - } - return -1; - }; - - BigInteger.prototype.compare = function(v) { - // See discussion about comparison with Infinity: - // https://github.com/peterolson/BigInteger.js/issues/61 - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } + arr = new Arr(len * 3 / 4 - placeHolders) - var n = parseValue(v), a = this.value, b = n.value; - if (this.sign !== n.sign) { - return n.sign ? 1 : -1; - } - if (n.isSmall) { - return this.sign ? -1 : 1; - } - return compareAbs(a, b) * (this.sign ? -1 : 1); - }; - BigInteger.prototype.compareTo = BigInteger.prototype.compare; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len - SmallInteger.prototype.compare = function(v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } + var L = 0 - var n = parseValue(v), a = this.value, b = n.value; - if (n.isSmall) { - return a == b ? 0 : a > b ? 1 : -1; - } - if (a < 0 !== n.sign) { - return a < 0 ? -1 : 1; - } - return a < 0 ? 1 : -1; - }; - SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; - - BigInteger.prototype.equals = function(v) { - return this.compare(v) === 0; - }; - SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = - BigInteger.prototype.equals; - - BigInteger.prototype.notEquals = function(v) { - return this.compare(v) !== 0; - }; - SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = - BigInteger.prototype.notEquals; - - BigInteger.prototype.greater = function(v) { - return this.compare(v) > 0; - }; - SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = - BigInteger.prototype.greater; - - BigInteger.prototype.lesser = function(v) { - return this.compare(v) < 0; - }; - SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = - BigInteger.prototype.lesser; - - BigInteger.prototype.greaterOrEquals = function(v) { - return this.compare(v) >= 0; - }; - SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = - BigInteger.prototype.greaterOrEquals; - - BigInteger.prototype.lesserOrEquals = function(v) { - return this.compare(v) <= 0; - }; - SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = - BigInteger.prototype.lesserOrEquals; - - BigInteger.prototype.isEven = function() { - return (this.value[0] & 1) === 0; - }; - SmallInteger.prototype.isEven = function() { - return (this.value & 1) === 0; - }; - - BigInteger.prototype.isOdd = function() { - return (this.value[0] & 1) === 1; - }; - SmallInteger.prototype.isOdd = function() { - return (this.value & 1) === 1; - }; - - BigInteger.prototype.isPositive = function() { - return !this.sign; - }; - SmallInteger.prototype.isPositive = function() { - return this.value > 0; - }; - - BigInteger.prototype.isNegative = function() { - return this.sign; - }; - SmallInteger.prototype.isNegative = function() { - return this.value < 0; - }; - - BigInteger.prototype.isUnit = function() { - return false; - }; - SmallInteger.prototype.isUnit = function() { - return Math.abs(this.value) === 1; - }; - - BigInteger.prototype.isZero = function() { - return false; - }; - SmallInteger.prototype.isZero = function() { - return this.value === 0; - }; - BigInteger.prototype.isDivisibleBy = function(v) { - var n = parseValue(v); - var value = n.value; - if (value === 0) return false; - if (value === 1) return true; - if (value === 2) return this.isEven(); - return this.mod(n).equals(Integer[0]); - }; - SmallInteger.prototype.isDivisibleBy = - BigInteger.prototype.isDivisibleBy; - - function isBasicPrime(v) { - var n = v.abs(); - if (n.isUnit()) return false; - if (n.equals(2) || n.equals(3) || n.equals(5)) return true; - if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) - return false; - if (n.lesser(25)) return true; - // we don't know if it's prime: let the other functions figure it out - } + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } - BigInteger.prototype.isPrime = function() { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(), nPrev = n.prev(); - var a = [2, 3, 5, 7, 11, 13, 17, 19], b = nPrev, d, t, i, x; - while (b.isEven()) - b = b.divide(2); - for (i = 0; i < a.length; i++) { - x = bigInt(a[i]).modPow(b, n); - if (x.equals(Integer[1]) || x.equals(nPrev)) continue; - for ( - (t = true), (d = b); - t && d.lesser(nPrev); - d = d.multiply(2) - ) { - x = x.square().mod(n); - if (x.equals(nPrev)) t = false; - } - if (t) return false; - } - return true; - }; - SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; - - BigInteger.prototype.isProbablePrime = function(iterations) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var t = iterations === undefined ? 5 : iterations; - // use the Fermat primality test - for (var i = 0; i < t; i++) { - var a = bigInt.randBetween(2, n.minus(2)); - if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite - } - return true; // large chance of being prime - }; - SmallInteger.prototype.isProbablePrime = - BigInteger.prototype.isProbablePrime; - - BigInteger.prototype.modInv = function(n) { - var t = bigInt.zero, - newT = bigInt.one, - r = parseValue(n), - newR = this.abs(), - q, - lastT, - lastR; - while (!newR.equals(bigInt.zero)) { - q = r.divide(newR); - lastT = t; - lastR = r; - t = newT; - r = newR; - newT = lastT.subtract(q.multiply(newT)); - newR = lastR.subtract(q.multiply(newR)); - } - if (!r.equals(1)) - throw new Error( - this.toString() + " and " + n.toString() + " are not co-prime" - ); - if (t.compare(0) === -1) { - t = t.add(n); - } - if (this.isNegative()) { - return t.negate(); - } - return t; - }; + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } - SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + return arr +} - BigInteger.prototype.next = function() { - var value = this.value; - if (this.sign) { - return subtractSmall(value, 1, this.sign); - } - return new BigInteger(addSmall(value, 1), this.sign); - }; - SmallInteger.prototype.next = function() { - var value = this.value; - if (value + 1 < MAX_INT) return new SmallInteger(value + 1); - return new BigInteger(MAX_INT_ARR, false); - }; - - BigInteger.prototype.prev = function() { - var value = this.value; - if (this.sign) { - return new BigInteger(addSmall(value, 1), true); - } - return subtractSmall(value, 1, this.sign); - }; - SmallInteger.prototype.prev = function() { - var value = this.value; - if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); - return new BigInteger(MAX_INT_ARR, true); - }; - - var powersOfTwo = [1]; - while (powersOfTwo[powersOfTwo.length - 1] <= BASE) - powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); - var powers2Length = powersOfTwo.length, - highestPower2 = powersOfTwo[powers2Length - 1]; - - function shift_isSmall(n) { - return ( - ((typeof n === "number" || typeof n === "string") && - +Math.abs(n) <= BASE) || - (n instanceof BigInteger && n.value.length <= 1) - ); - } +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} - BigInteger.prototype.shiftLeft = function(n) { - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - n = +n; - if (n < 0) return this.shiftRight(-n); - var result = this; - while (n >= powers2Length) { - result = result.multiply(highestPower2); - n -= powers2Length - 1; - } - return result.multiply(powersOfTwo[n]); - }; - SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; - - BigInteger.prototype.shiftRight = function(n) { - var remQuo; - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - n = +n; - if (n < 0) return this.shiftLeft(-n); - var result = this; - while (n >= powers2Length) { - if (result.isZero()) return result; - remQuo = divModAny(result, highestPower2); - result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - n -= powers2Length - 1; - } - remQuo = divModAny(result, powersOfTwo[n]); - return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - }; - SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; - - function bitwise(x, y, fn) { - y = parseValue(y); - var xSign = x.isNegative(), ySign = y.isNegative(); - var xRem = xSign ? x.not() : x, yRem = ySign ? y.not() : y; - var xBits = [], yBits = []; - var xStop = false, yStop = false; - while (!xStop || !yStop) { - if (xRem.isZero()) { - // virtual sign extension for simulating two's complement - xStop = true; - xBits.push(xSign ? 1 : 0); - } else if (xSign) - xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers - else xBits.push(xRem.isEven() ? 0 : 1); - - if (yRem.isZero()) { - yStop = true; - yBits.push(ySign ? 1 : 0); - } else if (ySign) yBits.push(yRem.isEven() ? 1 : 0); - else yBits.push(yRem.isEven() ? 0 : 1); - - xRem = xRem.over(2); - yRem = yRem.over(2); - } - var result = []; - for (var i = 0; i < xBits.length; i++) - result.push(fn(xBits[i], yBits[i])); - var sum = bigInt(result.pop()) - .negate() - .times(bigInt(2).pow(result.length)); - while (result.length) { - sum = sum.add( - bigInt(result.pop()).times(bigInt(2).pow(result.length)) - ); - } - return sum; - } - - BigInteger.prototype.not = function() { - return this.negate().prev(); - }; - SmallInteger.prototype.not = BigInteger.prototype.not; - - BigInteger.prototype.and = function(n) { - return bitwise(this, n, function(a, b) { - return a & b; - }); - }; - SmallInteger.prototype.and = BigInteger.prototype.and; - - BigInteger.prototype.or = function(n) { - return bitwise(this, n, function(a, b) { - return a | b; - }); - }; - SmallInteger.prototype.or = BigInteger.prototype.or; - - BigInteger.prototype.xor = function(n) { - return bitwise(this, n, function(a, b) { - return a ^ b; - }); - }; - SmallInteger.prototype.xor = BigInteger.prototype.xor; - - var LOBMASK_I = 1 << 30, - LOBMASK_BI = ((BASE & -BASE) * (BASE & -BASE)) | LOBMASK_I; - function roughLOB(n) { - // get lowestOneBit (rough) - // SmallInteger: return Min(lowestOneBit(n), 1 << 30) - // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] - var v = n.value, - x = typeof v === "number" - ? v | LOBMASK_I - : (v[0] + v[1] * BASE) | LOBMASK_BI; - return x & -x; - } - - function max(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.greater(b) ? a : b; - } - function min(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.lesser(b) ? a : b; - } - function gcd(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - if (a.equals(b)) return a; - if (a.isZero()) return b; - if (b.isZero()) return a; - var c = Integer[1], d, t; - while (a.isEven() && b.isEven()) { - d = Math.min(roughLOB(a), roughLOB(b)); - a = a.divide(d); - b = b.divide(d); - c = c.multiply(d); - } - while (a.isEven()) { - a = a.divide(roughLOB(a)); - } - do { - while (b.isEven()) { - b = b.divide(roughLOB(b)); - } - if (a.greater(b)) { - t = b; - b = a; - a = t; - } - b = b.subtract(a); - } while (!b.isZero()); - return c.isUnit() ? a : a.multiply(c); - } - function lcm(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - return a.divide(gcd(a, b)).multiply(b); - } - function randBetween(a, b) { - a = parseValue(a); - b = parseValue(b); - var low = min(a, b), high = max(a, b); - var range = high.subtract(low); - if (range.isSmall) - return low.add(Math.round(Math.random() * range)); - var length = range.value.length - 1; - var result = [], restricted = true; - for (var i = length; i >= 0; i--) { - var top = restricted ? range.value[i] : BASE; - var digit = truncate(Math.random() * top); - result.unshift(digit); - if (digit < top) restricted = false; - } - result = arrayToSmall(result); - return low.add( - typeof result === "number" - ? new SmallInteger(result) - : new BigInteger(result, false) - ); - } - var parseBase = function(text, base) { - var length = text.length; - if (2 <= base && base <= 36) { - if (length <= LOG_MAX_INT / Math.log(base)) { - return new SmallInteger(parseInt(text, base)); - } - } - base = parseValue(base); - var digits = []; - var i; - var isNegative = text[0] === "-"; - for (i = isNegative ? 1 : 0; i < text.length; i++) { - var c = text[i].toLowerCase(), charCode = c.charCodeAt(0); - if (48 <= charCode && charCode <= 57) - digits.push(parseValue(c)); - else if (97 <= charCode && charCode <= 122) - digits.push(parseValue(c.charCodeAt(0) - 87)); - else if (c === "<") { - var start = i; - do { - i++; - } while (text[i] !== ">"); - digits.push(parseValue(text.slice(start + 1, i))); - } else throw new Error(c + " is not a valid character"); - } - return parseBaseFromArray(digits, base, isNegative); - }; - - function parseBaseFromArray(digits, base, isNegative) { - var val = Integer[0], pow = Integer[1], i; - for (i = digits.length - 1; i >= 0; i--) { - val = val.add(digits[i].times(pow)); - pow = pow.times(base); - } - return isNegative ? val.negate() : val; - } - - function stringify(digit) { - var v = digit.value; - if (typeof v === "number") v = [v]; - if (v.length === 1 && v[0] <= 35) { - return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]); - } - return "<" + v + ">"; - } - function toBase(n, base) { - base = bigInt(base); - if (base.isZero()) { - if (n.isZero()) return "0"; - throw new Error("Cannot convert nonzero numbers to base 0."); - } - if (base.equals(-1)) { - if (n.isZero()) return "0"; - if (n.isNegative()) return new Array(1 - n).join("10"); - return "1" + new Array(+n).join("01"); - } - var minusSign = ""; - if (n.isNegative() && base.isPositive()) { - minusSign = "-"; - n = n.abs(); - } - if (base.equals(1)) { - if (n.isZero()) return "0"; - return minusSign + new Array(+n + 1).join(1); - } - var out = []; - var left = n, divmod; - while (left.isNegative() || left.compareAbs(base) >= 0) { - divmod = left.divmod(base); - left = divmod.quotient; - var digit = divmod.remainder; - if (digit.isNegative()) { - digit = base.minus(digit).abs(); - left = left.next(); - } - out.push(stringify(digit)); - } - out.push(stringify(left)); - return minusSign + out.reverse().join(""); - } - - BigInteger.prototype.toString = function(radix) { - if (radix === undefined) radix = 10; - if (radix !== 10) return toBase(this, radix); - var v = this.value, - l = v.length, - str = String(v[--l]), - zeros = "0000000", - digit; - while (--l >= 0) { - digit = String(v[l]); - str += zeros.slice(digit.length) + digit; - } - var sign = this.sign ? "-" : ""; - return sign + str; - }; - SmallInteger.prototype.toString = function(radix) { - if (radix === undefined) radix = 10; - if (radix != 10) return toBase(this, radix); - return String(this.value); - }; - - BigInteger.prototype.valueOf = function() { - return +this.toString(); - }; - BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; - - SmallInteger.prototype.valueOf = function() { - return this.value; - }; - SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - - function parseStringValue(v) { - if (isPrecise(+v)) { - var x = +v; - if (x === truncate(x)) return new SmallInteger(x); - throw "Invalid integer: " + v; - } - var sign = v[0] === "-"; - if (sign) v = v.slice(1); - var split = v.split(/e/i); - if (split.length > 2) - throw new Error("Invalid integer: " + split.join("e")); - if (split.length === 2) { - var exp = split[1]; - if (exp[0] === "+") exp = exp.slice(1); - exp = +exp; - if (exp !== truncate(exp) || !isPrecise(exp)) - throw new Error( - "Invalid integer: " + exp + " is not a valid exponent." - ); - var text = split[0]; - var decimalPlace = text.indexOf("."); - if (decimalPlace >= 0) { - exp -= text.length - decimalPlace - 1; - text = - text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); - } - if (exp < 0) - throw new Error( - "Cannot include negative exponent part for integers" - ); - text += new Array(exp + 1).join("0"); - v = text; - } - var isValid = /^([0-9][0-9]*)$/.test(v); - if (!isValid) throw new Error("Invalid integer: " + v); - var r = [], max = v.length, l = LOG_BASE, min = max - l; - while (max > 0) { - r.push(+v.slice(min, max)); - min -= l; - if (min < 0) min = 0; - max -= l; - } - trim(r); - return new BigInteger(r, sign); - } +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } - function parseNumberValue(v) { - if (isPrecise(v)) { - if (v !== truncate(v)) - throw new Error(v + " is not an integer."); - return new SmallInteger(v); - } - return parseStringValue(v.toString()); - } + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } - function parseValue(v) { - if (typeof v === "number") { - return parseNumberValue(v); - } - if (typeof v === "string") { - return parseStringValue(v); - } - return v; - } - // Pre-define numbers in range [-999,999] - for (var i = 0; i < 1000; i++) { - Integer[i] = new SmallInteger(i); - if (i > 0) Integer[-i] = new SmallInteger(-i); - } - // Backwards compatibility - Integer.one = Integer[1]; - Integer.zero = Integer[0]; - Integer.minusOne = Integer[-1]; - Integer.max = max; - Integer.min = min; - Integer.gcd = gcd; - Integer.lcm = lcm; - Integer.isInstance = function(x) { - return x instanceof BigInteger || x instanceof SmallInteger; - }; - Integer.randBetween = randBetween; - - Integer.fromArray = function(digits, base, isNegative) { - return parseBaseFromArray( - digits.map(parseValue), - parseValue(base || 10), - isNegative - ); - }; - - return Integer; - })(); - - // Node.js check - if ( - typeof module !== "undefined" && - module.hasOwnProperty("exports") - ) { - module.exports = bigInt; - } + parts.push(output) + + return parts.join('') +} + +},{}],2:[function(require,module,exports){ +var bigInt = (function (undefined) { + "use strict"; + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + LOG_MAX_INT = Math.log(MAX_INT); + + function Integer(v, radix) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a,b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + function square(a) { + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + for (var j = 0; j < l; j++) { + a_j = a[j]; + product = a_i * a_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + var value = n.value; + if (value === 0) return false; + if (value === 1) return true; + if (value === 2) return this.isEven(); + return this.mod(n).equals(Integer[0]); + }; + SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(25)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + BigInteger.prototype.isPrime = function () { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(), + nPrev = n.prev(); + var a = [2, 3, 5, 7, 11, 13, 17, 19], + b = nPrev, + d, t, i, x; + while (b.isEven()) b = b.divide(2); + for (i = 0; i < a.length; i++) { + x = bigInt(a[i]).modPow(b, n); + if (x.equals(Integer[1]) || x.equals(nPrev)) continue; + for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) { + x = x.square().mod(n); + if (x.equals(nPrev)) t = false; + } + if (t) return false; + } + return true; + }; + SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + // use the Fermat primality test + for (var i = 0; i < t; i++) { + var a = bigInt.randBetween(2, n.minus(2)); + if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite + } + return true; // large chance of being prime + }; + SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.equals(bigInt.zero)) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + + var powersOfTwo = [1]; + while (powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) || + (n instanceof BigInteger && n.value.length <= 1); + } + + BigInteger.prototype.shiftLeft = function (n) { + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftRight(-n); + var result = this; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (n) { + var remQuo; + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + n = +n; + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero()) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xBits = [], yBits = []; + var xStop = false, yStop = false; + while (!xStop || !yStop) { + if (xRem.isZero()) { // virtual sign extension for simulating two's complement + xStop = true; + xBits.push(xSign ? 1 : 0); + } + else if (xSign) xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers + else xBits.push(xRem.isEven() ? 0 : 1); + + if (yRem.isZero()) { + yStop = true; + yBits.push(ySign ? 1 : 0); + } + else if (ySign) yBits.push(yRem.isEven() ? 1 : 0); + else yBits.push(yRem.isEven() ? 0 : 1); + + xRem = xRem.over(2); + yRem = yRem.over(2); + } + var result = []; + for (var i = 0; i < xBits.length; i++) result.push(fn(xBits[i], yBits[i])); + var sum = bigInt(result.pop()).negate().times(bigInt(2).pow(result.length)); + while (result.length) { + sum = sum.add(bigInt(result.pop()).times(bigInt(2).pow(result.length))); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = Math.min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b) { + a = parseValue(a); + b = parseValue(b); + var low = min(a, b), high = max(a, b); + var range = high.subtract(low); + if (range.isSmall) return low.add(Math.round(Math.random() * range)); + var length = range.value.length - 1; + var result = [], restricted = true; + for (var i = length; i >= 0; i--) { + var top = restricted ? range.value[i] : BASE; + var digit = truncate(Math.random() * top); + result.unshift(digit); + if (digit < top) restricted = false; + } + result = arrayToSmall(result); + return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false)); + } + var parseBase = function (text, base) { + var length = text.length; + if (2 <= base && base <= 36) { + if (length <= LOG_MAX_INT / Math.log(base)) { + return new SmallInteger(parseInt(text, base)); + } + } + base = parseValue(base); + var digits = []; + var i; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i].toLowerCase(), + charCode = c.charCodeAt(0); + if (48 <= charCode && charCode <= 57) digits.push(parseValue(c)); + else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87)); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">"); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit) { + var v = digit.value; + if (typeof v === "number") v = [v]; + if (v.length === 1 && v[0] <= 35) { + return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]); + } + return "<" + v + ">"; + } + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return "0"; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return "0"; + if (n.isNegative()) return new Array(1 - n).join("10"); + return "1" + new Array(+n).join("01"); + } + var minusSign = ""; + if (n.isNegative() && base.isPositive()) { + minusSign = "-"; + n = n.abs(); + } + if (base.equals(1)) { + if (n.isZero()) return "0"; + return minusSign + new Array(+n + 1).join(1); + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(stringify(digit)); + } + out.push(stringify(left)); + return minusSign + out.reverse().join(""); + } + + BigInteger.prototype.toString = function (radix) { + if (radix === undefined) radix = 10; + if (radix !== 10) return toBase(this, radix); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + SmallInteger.prototype.toString = function (radix) { + if (radix === undefined) radix = 10; + if (radix != 10) return toBase(this, radix); + return String(this.value); + }; + + BigInteger.prototype.valueOf = function () { + return +this.toString(); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return new SmallInteger(x); + throw "Invalid integer: " + v; + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = new SmallInteger(i); + if (i > 0) Integer[-i] = new SmallInteger(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; +})(); + +// Node.js check +if (typeof module !== "undefined" && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +//amd check +if ( typeof define === "function" && define.amd ) { + define( "big-integer", [], function() { + return bigInt; + }); +} + +},{}],3:[function(require,module,exports){ + +},{}],4:[function(require,module,exports){ +(function (global){ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } - //amd check - if (typeof define === "function" && define.amd) { - define("big-integer", [], function() { - return bigInt; - }); - } - }, - {} - ], - 3: [function(require, module, exports) {}, {}], - 4: [ - function(require, module, exports) { - (function(global) { - "use strict"; - var buffer = require("buffer"); - var Buffer = buffer.Buffer; - var SlowBuffer = buffer.SlowBuffer; - var MAX_LEN = buffer.kMaxLength || 2147483647; - exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === "function") { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === "number") { - throw new TypeError("encoding must not be number"); - } - if (typeof size !== "number") { - throw new TypeError("size must be a number"); - } - if (size > MAX_LEN) { - throw new RangeError("size is too large"); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === "string") { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; - }; - exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === "function") { - return Buffer.allocUnsafe(size); - } - if (typeof size !== "number") { - throw new TypeError("size must be a number"); - } - if (size > MAX_LEN) { - throw new RangeError("size is too large"); - } - return new Buffer(size); - }; - exports.from = function from(value, encodingOrOffset, length) { - if ( - typeof Buffer.from === "function" && - (!global.Uint8Array || Uint8Array.from !== Buffer.from) - ) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === "string") { - return new Buffer(value, encodingOrOffset); - } - if ( - typeof ArrayBuffer !== "undefined" && - value instanceof ArrayBuffer - ) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === "undefined") { - offset = 0; - } - var len = length; - if (typeof len === "undefined") { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError("'offset' is out of bounds"); - } - if (len > value.byteLength - offset) { - throw new RangeError("'length' is out of bounds"); - } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if ( - Array.isArray(value) || - (typeof ArrayBuffer !== "undefined" && - value.buffer instanceof ArrayBuffer) || - "length" in value - ) { - return new Buffer(value); - } - if (value.type === "Buffer" && Array.isArray(value.data)) { - return new Buffer(value.data); - } - } + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} - throw new TypeError( - "First argument must be a string, Buffer, " + - "ArrayBuffer, Array, or array-like object." - ); - }; - exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === "function") { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== "number") { - throw new TypeError("size must be a number"); - } - if (size >= MAX_LEN) { - throw new RangeError("size is too large"); - } - return new SlowBuffer(size); - }; - }.call( - this, - typeof global !== "undefined" - ? global - : typeof self !== "undefined" - ? self - : typeof window !== "undefined" ? window : {} - )); - }, - { buffer: 5 } - ], - 5: [ - function(require, module, exports) { - /*! +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"buffer":5}],5:[function(require,module,exports){ +/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ - /* eslint-disable no-proto */ +/* eslint-disable no-proto */ - "use strict"; - var base64 = require("base64-js"); - var ieee754 = require("ieee754"); +'use strict' - exports.Buffer = Buffer; - exports.SlowBuffer = SlowBuffer; - exports.INSPECT_MAX_BYTES = 50; +var base64 = require('base64-js') +var ieee754 = require('ieee754') - var K_MAX_LENGTH = 0x7fffffff; - exports.kMaxLength = K_MAX_LENGTH; +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 - /** +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object @@ -1733,46 +1499,38 @@ * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ - Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); - - if ( - !Buffer.TYPED_ARRAY_SUPPORT && - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error( - "This browser lacks typed array (Uint8Array) support which is required by " + - "`buffer` v5.x. Use `buffer` v4.x if you require old browser support." - ); - } - - function typedArraySupport() { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1); - arr.__proto__ = { - __proto__: Uint8Array.prototype, - foo: function() { - return 42; - } - }; - return arr.foo() === 42; - } catch (e) { - return false; - } - } +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } +} - function createBuffer(length) { - if (length > K_MAX_LENGTH) { - throw new RangeError("Invalid typed array length"); - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length); - buf.__proto__ = Buffer.prototype; - return buf; - } +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} - /** +/** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods @@ -1782,52 +1540,49 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer(arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new Error( - "If encoding is specified then the first argument must be a string" - ); - } - return allocUnsafe(arg); - } - return from(arg, encodingOrOffset, length); - } - - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - if ( - typeof Symbol !== "undefined" && - Symbol.species && - Buffer[Symbol.species] === Buffer - ) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }); - } - - Buffer.poolSize = 8192; // not used by this implementation - - function from(value, encodingOrOffset, length) { - if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - if (value instanceof ArrayBuffer) { - return fromArrayBuffer(value, encodingOrOffset, length); - } + if (value instanceof ArrayBuffer) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - if (typeof value === "string") { - return fromString(value, encodingOrOffset); - } + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - return fromObject(value); - } + return fromObject(value) +} - /** +/** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) @@ -1835,2187 +1590,1889 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer.from = function(value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); - }; - - // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: - // https://github.com/feross/buffer/pull/148 - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; - - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be a number'); - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative'); - } - } +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === "string" - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill); - } - return createBuffer(size); - } +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} - /** +/** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} - function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} - /** +/** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer.allocUnsafe = function(size) { - return allocUnsafe(size); - }; - /** +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer.allocUnsafeSlow = function(size) { - return allocUnsafe(size); - }; - - function fromString(string, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding'); - } - - var length = byteLength(string, encoding) | 0; - var buf = createBuffer(length); - - var actual = buf.write(string, encoding); - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual); - } - - return buf; - } - - function fromArrayLike(array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - var buf = createBuffer(length); - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255; - } - return buf; - } - - function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError("'offset' is out of bounds"); - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError("'length' is out of bounds"); - } - - var buf; - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array); - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length); - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype; - return buf; - } - - function fromObject(obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); - - if (buf.length === 0) { - return buf; - } - - obj.copy(buf, 0, 0, len); - return buf; - } - - if (obj) { - if (isArrayBufferView(obj) || "length" in obj) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - - throw new TypeError( - "First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object." - ); - } - - function checked(length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError( - "Attempt to allocate Buffer larger than maximum " + - "size: 0x" + - K_MAX_LENGTH.toString(16) + - " bytes" - ); - } - return length | 0; - } - - function SlowBuffer(length) { - if (+length != length) { - // eslint-disable-line eqeqeq - length = 0; - } - return Buffer.alloc(+length); - } - - Buffer.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true; - }; - - Buffer.compare = function compare(a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError("Arguments must be Buffers"); - } - - if (a === b) return 0; - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - Buffer.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "latin1": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return true; - default: - return false; - } - }; +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} - Buffer.concat = function concat(list, length) { - if (!Array.isArray(list)) { - throw new TypeError( - '"list" argument must be an Array of Buffers' - ); - } - - if (list.length === 0) { - return Buffer.alloc(0); - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!Buffer.isBuffer(buf)) { - throw new TypeError( - '"list" argument must be an Array of Buffers' - ); - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer; - }; - - function byteLength(string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length; - } - if (isArrayBufferView(string) || string instanceof ArrayBuffer) { - return string.byteLength; - } - if (typeof string !== "string") { - string = "" + string; - } +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - var len = string.length; - if (len === 0) return 0; - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - case undefined: - return utf8ToBytes(string).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string).length; - default: - if (loweredCase) return utf8ToBytes(string).length; // assume utf8 - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer.byteLength = byteLength; + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } - function slowToString(encoding, start, end) { - var loweredCase = false; + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + var actual = buf.write(string, encoding) - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return ""; - } + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } - if (end === undefined || end > this.length) { - end = this.length; - } + return buf +} - if (end <= 0) { - return ""; - } +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } - if (end <= start) { - return ""; - } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } - if (!encoding) encoding = "utf8"; + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) - case "ascii": - return asciiSlice(this, start, end); + if (buf.length === 0) { + return buf + } - case "latin1": - case "binary": - return latin1Slice(this, start, end); + obj.copy(buf, 0, 0, len) + return buf + } - case "base64": - return base64Slice(this, start, end); + if (obj) { + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} - // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) - // to detect a Buffer instance. It's not possible to use `instanceof Buffer` - // reliably in a browserify context because there could be multiple different - // copies of the 'buffer' package in use. This method works even for Buffer - // instances that were created from another copy of the `buffer` package. - // See: https://github.com/feross/buffer/issues/154 - Buffer.prototype._isBuffer = true; - - function swap(b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} - Buffer.prototype.swap16 = function swap16() { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this; - }; +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} - Buffer.prototype.swap32 = function swap32() { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this; - }; +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true +} - Buffer.prototype.swap64 = function swap64() { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this; - }; - - Buffer.prototype.toString = function toString() { - var length = this.length; - if (length === 0) return ""; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - - Buffer.prototype.equals = function equals(b) { - if (!Buffer.isBuffer(b)) - throw new TypeError("Argument must be a Buffer"); - if (this === b) return true; - return Buffer.compare(this, b) === 0; - }; - - Buffer.prototype.inspect = function inspect() { - var str = ""; - var max = exports.INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString("hex", 0, max).match(/.{2}/g).join(" "); - if (this.length > max) str += " ... "; - } - return ""; - }; - - Buffer.prototype.compare = function compare( - target, - start, - end, - thisStart, - thisEnd - ) { - if (!Buffer.isBuffer(target)) { - throw new TypeError("Argument must be a Buffer"); - } +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + if (a === b) return 0 - if ( - start < 0 || - end > target.length || - thisStart < 0 || - thisEnd > this.length - ) { - throw new RangeError("out of range index"); - } + var x = a.length + var y = b.length - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} - if (this === target) return 0; +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + if (list.length === 0) { + return Buffer.alloc(0) + } - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf( - buffer, - val, - byteOffset, - encoding, - dir - ) { - // Empty buffer means no match - if (buffer.length === 0) return -1; - - // Normalize byteOffset - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - } +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (isArrayBufferView(string) || string instanceof ArrayBuffer) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1; - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1; - } + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength - // Normalize val - if (typeof val === "string") { - val = Buffer.from(val, encoding); - } +function slowToString (encoding, start, end) { + var loweredCase = false - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 0xff; // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call( - buffer, - val, - byteOffset - ); - } else { - return Uint8Array.prototype.lastIndexOf.call( - buffer, - val, - byteOffset - ); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - throw new TypeError("val must be string, number or Buffer"); - } + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if ( - encoding === "ucs2" || - encoding === "ucs-2" || - encoding === "utf16le" || - encoding === "utf-16le" - ) { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } + if (end === undefined || end > this.length) { + end = this.length + } - function read(buf, i) { - if (indexSize === 1) { - return buf[i]; - } else { - return buf.readUInt16BE(i * indexSize); - } - } + if (end <= 0) { + return '' + } - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if ( - read(arr, i) === - read(val, foundIndex === -1 ? 0 : i - foundIndex) - ) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) - return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) - byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - if (found) return i; - } - } + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 - return -1; - } + if (end <= start) { + return '' + } - Buffer.prototype.includes = function includes( - val, - byteOffset, - encoding - ) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - - Buffer.prototype.indexOf = function indexOf( - val, - byteOffset, - encoding - ) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - - Buffer.prototype.lastIndexOf = function lastIndexOf( - val, - byteOffset, - encoding - ) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + if (!encoding) encoding = 'utf8' - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError("Invalid hex string"); + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset + i] = parsed; - } - return i; - } + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - function utf8Write(buf, string, offset, length) { - return blitBuffer( - utf8ToBytes(string, buf.length - offset), - buf, - offset, - length - ); - } + case 'ascii': + return asciiSlice(this, start, end) - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); - } + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - function latin1Write(buf, string, offset, length) { - return asciiWrite(buf, string, offset, length); - } + case 'base64': + return base64Slice(this, start, end) - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - function ucs2Write(buf, string, offset, length) { - return blitBuffer( - utf16leToBytes(string, buf.length - offset), - buf, - offset, - length - ); - } + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} - Buffer.prototype.write = function write( - string, - offset, - length, - encoding - ) { - // Buffer#write(string) - if (offset === undefined) { - encoding = "utf8"; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === "string") { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length)) { - length = length >>> 0; - if (encoding === undefined) encoding = "utf8"; - } else { - encoding = length; - length = undefined; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} - if ( - (string.length > 0 && (length < 0 || offset < 0)) || - offset > this.length - ) { - throw new RangeError("Attempt to write outside buffer bounds"); - } +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } - if (!encoding) encoding = "utf8"; + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } - var loweredCase = false; - for (;;) { - switch (encoding) { - case "hex": - return hexWrite(this, string, offset, length); + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - case "utf8": - case "utf-8": - return utf8Write(this, string, offset, length); + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - case "ascii": - return asciiWrite(this, string, offset, length); + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 - case "latin1": - case "binary": - return latin1Write(this, string, offset, length); + if (this === target) return 0 - case "base64": - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length); + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string, offset, length); + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - - Buffer.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf); - } else { - return base64.fromByteArray(buf.slice(start, end)); - } - } + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = firstByte > 0xef - ? 4 - : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xc0) === 0x80) { - tempCodePoint = - ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f); - if (tempCodePoint > 0x7f) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ( - (secondByte & 0xc0) === 0x80 && - (thirdByte & 0xc0) === 0x80 - ) { - tempCodePoint = - ((firstByte & 0xf) << 0xc) | - ((secondByte & 0x3f) << 0x6) | - (thirdByte & 0x3f); - if ( - tempCodePoint > 0x7ff && - (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff) - ) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ( - (secondByte & 0xc0) === 0x80 && - (thirdByte & 0xc0) === 0x80 && - (fourthByte & 0xc0) === 0x80 - ) { - tempCodePoint = - ((firstByte & 0xf) << 0x12) | - ((secondByte & 0x3f) << 0xc) | - ((thirdByte & 0x3f) << 0x6) | - (fourthByte & 0x3f); - if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xfffd; - bytesPerSequence = 1; - } else if (codePoint > 0xffff) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(((codePoint >>> 10) & 0x3ff) | 0xd800); - codePoint = 0xdc00 | (codePoint & 0x3ff); - } + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } - res.push(codePoint); - i += bytesPerSequence; - } + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } - return decodeCodePointsArray(res); - } + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000; + throw new TypeError('val must be string, number or Buffer') +} - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() - } +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length - // Decode in chunks to avoid "call stack size exceeded". - var res = ""; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH)) - ); - } - return res; - } + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } - function asciiSlice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7f); - } - return ret; - } + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } - function latin1Slice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); + return -1 +} - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret; - } +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} - function hexSlice(buf, start, end) { - var len = buf.length; +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} - var out = ""; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out; - } +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ""; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res; - } + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - Buffer.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } - if (end < start) end = start; + if (!encoding) encoding = 'utf8' - var newBuf = this.subarray(start, end); - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype; - return newBuf; - }; + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) - throw new RangeError("offset is not uint"); - if (offset + ext > length) - throw new RangeError("Trying to access beyond buffer length"); - } + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - Buffer.prototype.readUIntLE = function readUIntLE( - offset, - byteLength, - noAssert - ) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } + case 'ascii': + return asciiWrite(this, string, offset, length) - return val; - }; - - Buffer.prototype.readUIntBE = function readUIntBE( - offset, - byteLength, - noAssert - ) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - return val; - }; - - Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - - Buffer.prototype.readUInt16LE = function readUInt16LE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8); - }; - - Buffer.prototype.readUInt16BE = function readUInt16BE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1]; - }; - - Buffer.prototype.readUInt32LE = function readUInt32LE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - - return ( - (this[offset] | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - this[offset + 3] * 0x1000000 - ); - }; - - Buffer.prototype.readUInt32BE = function readUInt32BE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - - return ( - this[offset] * 0x1000000 + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - ); - }; - - Buffer.prototype.readIntLE = function readIntLE( - offset, - byteLength, - noAssert - ) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val; - }; - - Buffer.prototype.readIntBE = function readIntBE( - offset, - byteLength, - noAssert - ) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val; - }; - - Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return this[offset]; - return (0xff - this[offset] + 1) * -1; - }; - - Buffer.prototype.readInt16LE = function readInt16LE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return val & 0x8000 ? val | 0xffff0000 : val; - }; - - Buffer.prototype.readInt16BE = function readInt16BE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return val & 0x8000 ? val | 0xffff0000 : val; - }; - - Buffer.prototype.readInt32LE = function readInt32LE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - - return ( - this[offset] | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - ); - }; - - Buffer.prototype.readInt32BE = function readInt32BE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - - return ( - (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3] - ); - }; - - Buffer.prototype.readFloatLE = function readFloatLE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); - }; - - Buffer.prototype.readFloatBE = function readFloatBE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); - }; - - Buffer.prototype.readDoubleLE = function readDoubleLE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); - }; - - Buffer.prototype.readDoubleBE = function readDoubleBE( - offset, - noAssert - ) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); - }; - - function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) - throw new TypeError( - '"buffer" argument must be a Buffer instance' - ); - if (value > max || value < min) - throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - Buffer.prototype.writeUIntLE = function writeUIntLE( - value, - offset, - byteLength, - noAssert - ) { - value = +value; - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} - var mul = 1; - var i = 0; - this[offset] = value & 0xff; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xff; - } +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} - return offset + byteLength; - }; - - Buffer.prototype.writeUIntBE = function writeUIntBE( - value, - offset, - byteLength, - noAssert - ) { - value = +value; - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint } + } + } + } - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xff; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xff; - } + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } - return offset + byteLength; - }; - - Buffer.prototype.writeUInt8 = function writeUInt8( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeUInt16LE = function writeUInt16LE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - - Buffer.prototype.writeUInt16BE = function writeUInt16BE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeUInt32LE = function writeUInt32LE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 0xff; - return offset + 4; - }; - - Buffer.prototype.writeUInt32BE = function writeUInt32BE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - return offset + 4; - }; - - Buffer.prototype.writeIntLE = function writeIntLE( - value, - offset, - byteLength, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + res.push(codePoint) + i += bytesPerSequence + } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xff; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; - } + return decodeCodePointsArray(res) +} - return offset + byteLength; - }; - - Buffer.prototype.writeIntBE = function writeIntBE( - value, - offset, - byteLength, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xff; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; - } +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - return offset + byteLength; - }; - - Buffer.prototype.writeInt8 = function writeInt8( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (value < 0) value = 0xff + value + 1; - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeInt16LE = function writeInt16LE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - - Buffer.prototype.writeInt16BE = function writeInt16BE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - return offset + 2; - }; - - Buffer.prototype.writeInt32LE = function writeInt32LE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; - }; - - Buffer.prototype.writeInt32BE = function writeInt32BE( - value, - offset, - noAssert - ) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - return offset + 4; - }; - - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - if (offset < 0) throw new RangeError("Index out of range"); - } + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} - function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754( - buf, - value, - offset, - 4, - 3.4028234663852886e38, - -3.4028234663852886e38 - ); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - Buffer.prototype.writeFloatLE = function writeFloatLE( - value, - offset, - noAssert - ) { - return writeFloat(this, value, offset, true, noAssert); - }; - - Buffer.prototype.writeFloatBE = function writeFloatBE( - value, - offset, - noAssert - ) { - return writeFloat(this, value, offset, false, noAssert); - }; - - function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754( - buf, - value, - offset, - 8, - 1.7976931348623157e308, - -1.7976931348623157e308 - ); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} - Buffer.prototype.writeDoubleLE = function writeDoubleLE( - value, - offset, - noAssert - ) { - return writeDouble(this, value, offset, true, noAssert); - }; - - Buffer.prototype.writeDoubleBE = function writeDoubleBE( - value, - offset, - noAssert - ) { - return writeDouble(this, value, offset, false, noAssert); - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy( - target, - targetStart, - start, - end - ) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) - throw new RangeError("sourceStart out of bounds"); - if (end < 0) throw new RangeError("sourceEnd out of bounds"); - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - var len = end - start; - var i; + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } +function hexSlice (buf, start, end) { + var len = buf.length - return len; - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if ( - typeof encoding === "string" && - !Buffer.isEncoding(encoding) - ) { - throw new TypeError("Unknown encoding: " + encoding); - } - } else if (typeof val === "number") { - val = val & 255; - } + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } - if (end <= start) { - return this; - } + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + if (end < start) end = start - if (!val) val = 0; + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} - var i; - if (typeof val === "number") { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : new Buffer(val, encoding); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } - return this; - }; + return val +} - // HELPER FUNCTIONS - // ================ +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } - function base64clean(str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, ""); - // Node converts strings with length < 2 to '' - if (str.length < 2) return ""; - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 - function toHex(n) { - if (n < 16) return "0" + n.toString(16); - return n.toString(16); - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xd7ff && codePoint < 0xe000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xdbff) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); - continue; - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); - continue; - } - - // valid lead - leadSurrogate = codePoint; - - continue; - } - - // 2 leads in a row - if (codePoint < 0xdc00) { - if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); - leadSurrogate = codePoint; - continue; - } - - // valid surrogate pair - codePoint = - (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + - 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); - } + return val +} - leadSurrogate = null; - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break; - bytes.push( - (codePoint >> 0x6) | 0xc0, - (codePoint & 0x3f) | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break; - bytes.push( - (codePoint >> 0xc) | 0xe0, - ((codePoint >> 0x6) & 0x3f) | 0x80, - (codePoint & 0x3f) | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break; - bytes.push( - (codePoint >> 0x12) | 0xf0, - ((codePoint >> 0xc) & 0x3f) | 0x80, - ((codePoint >> 0x6) & 0x3f) | 0x80, - (codePoint & 0x3f) | 0x80 - ); - } else { - throw new Error("Invalid code point"); - } - } +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - return bytes; - } + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - function asciiToBytes(str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xff); - } - return byteArray; - } + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } + return offset + byteLength +} - return byteArray; - } +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - function base64ToBytes(str) { - return base64.toByteArray(base64clean(str)); - } + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - function blitBuffer(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - return i; - } + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` - function isArrayBufferView(obj) { - return ( - typeof ArrayBuffer.isView === "function" && - ArrayBuffer.isView(obj) - ); - } + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - function numberIsNaN(obj) { - return obj !== obj; // eslint-disable-line no-self-compare - } - }, - { "base64-js": 1, ieee754: 14 } - ], - 6: [ - function(require, module, exports) { - (function(Buffer) { - var Transform = require("stream").Transform; - var inherits = require("inherits"); - var StringDecoder = require("string_decoder").StringDecoder; - module.exports = CipherBase; - inherits(CipherBase, Transform); - function CipherBase(hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === "string"; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - this._decoder = null; - this._encoding = null; - } - CipherBase.prototype.update = function(data, inputEnc, outputEnc) { - if (typeof data === "string") { - data = new Buffer(data, inputEnc); - } - var outData = this._update(data); - if (this.hashMode) { - return this; - } - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } - return outData; - }; + return offset + byteLength +} - CipherBase.prototype.setAutoPadding = function() {}; +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) - CipherBase.prototype.getAuthTag = function() { - throw new Error("trying to get auth tag in unsupported state"); - }; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - CipherBase.prototype.setAuthTag = function() { - throw new Error("trying to set auth tag in unsupported state"); - }; + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - CipherBase.prototype.setAAD = function() { - throw new Error("trying to set aad in unsupported state"); - }; + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - CipherBase.prototype._transform = function(data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function(done) { - var err; - try { - this.push(this._final()); - } catch (e) { - err = e; - } finally { - done(err); - } - }; - CipherBase.prototype._finalOrDigest = function(outputEnc) { - var outData = this._final() || new Buffer(""); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData; - }; + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } - CipherBase.prototype._toString = function(value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; - } - if (this._encoding !== enc) { - throw new Error("can't switch encodings"); - } - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - return out; - }; - }.call(this, require("buffer").Buffer)); - }, - { buffer: 5, inherits: 15, stream: 45, string_decoder: 46 } - ], - 7: [ - function(require, module, exports) { - (function(Buffer) { - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - - function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === "[object Array]"; - } - exports.isArray = isArray; + var len = end - start + var i - function isBoolean(arg) { - return typeof arg === "boolean"; - } - exports.isBoolean = isBoolean; + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } - function isNumber(arg) { - return typeof arg === "number"; - } - exports.isNumber = isNumber; + if (end <= start) { + return this + } - function isString(arg) { - return typeof arg === "string"; - } - exports.isString = isString; + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - function isSymbol(arg) { - return typeof arg === "symbol"; - } - exports.isSymbol = isSymbol; + if (!val) val = 0 - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } - function isRegExp(re) { - return objectToString(re) === "[object RegExp]"; - } - exports.isRegExp = isRegExp; + return this +} - function isObject(arg) { - return typeof arg === "object" && arg !== null; - } - exports.isObject = isObject; +// HELPER FUNCTIONS +// ================ - function isDate(d) { - return objectToString(d) === "[object Date]"; - } - exports.isDate = isDate; +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - function isError(e) { - return ( - objectToString(e) === "[object Error]" || e instanceof Error - ); - } - exports.isError = isError; +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } - function isFunction(arg) { - return typeof arg === "function"; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return ( - arg === null || - typeof arg === "boolean" || - typeof arg === "number" || - typeof arg === "string" || - typeof arg === "symbol" || // ES6 symbol - typeof arg === "undefined" - ); - } - exports.isPrimitive = isPrimitive; + // valid lead + leadSurrogate = codePoint - exports.isBuffer = Buffer.isBuffer; + continue + } - function objectToString(o) { - return Object.prototype.toString.call(o); - } - }.call(this, { isBuffer: require("../../is-buffer/index.js") })); - }, - { "../../is-buffer/index.js": 16 } - ], - 8: [ - function(require, module, exports) { - (function(Buffer) { - "use strict"; - var inherits = require("inherits"); - var md5 = require("./md5"); - var rmd160 = require("ripemd160"); - var sha = require("sha.js"); - - var Base = require("cipher-base"); - - function HashNoConstructor(hash) { - Base.call(this, "digest"); - - this._hash = hash; - this.buffers = []; - } + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } - inherits(HashNoConstructor, Base); + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } - HashNoConstructor.prototype._update = function(data) { - this.buffers.push(data); - }; + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } - HashNoConstructor.prototype._final = function() { - var buf = Buffer.concat(this.buffers); - var r = this._hash(buf); - this.buffers = null; + return bytes +} - return r; - }; +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } - function Hash(hash) { - Base.call(this, "digest"); + return byteArray +} - this._hash = hash; - } +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} - inherits(Hash, Base); +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` +function isArrayBufferView (obj) { + return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) +} + +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} + +},{"base64-js":1,"ieee754":14}],6:[function(require,module,exports){ +(function (Buffer){ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} - Hash.prototype._update = function(data) { - this._hash.update(data); - }; +CipherBase.prototype.setAutoPadding = function () {} - Hash.prototype._final = function() { - return this._hash.digest(); - }; +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} - module.exports = function createHash(alg) { - alg = alg.toLowerCase(); - if ("md5" === alg) return new HashNoConstructor(md5); - if ("rmd160" === alg || "ripemd160" === alg) - return new HashNoConstructor(rmd160); +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} - return new Hash(sha(alg)); - }; - }.call(this, require("buffer").Buffer)); - }, - { - "./md5": 10, - buffer: 5, - "cipher-base": 6, - inherits: 15, - ripemd160: 36, - "sha.js": 38 - } - ], - 9: [ - function(require, module, exports) { - (function(Buffer) { - "use strict"; - var intSize = 4; - var zeroBuffer = new Buffer(intSize); - zeroBuffer.fill(0); - var chrsz = 8; - - function toArray(buf, bigEndian) { - if (buf.length % intSize !== 0) { - var len = buf.length + (intSize - buf.length % intSize); - buf = Buffer.concat([buf, zeroBuffer], len); - } +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} - var arr = []; - var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; - for (var i = 0; i < buf.length; i += intSize) { - arr.push(fn.call(buf, i)); - } - return arr; - } +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} - function toBuffer(arr, size, bigEndian) { - var buf = new Buffer(size); - var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; - for (var i = 0; i < arr.length; i++) { - fn.call(buf, arr[i], i * 4, true); - } - return buf; - } +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + return out +} + +}).call(this,require("buffer").Buffer) +},{"buffer":5,"inherits":15,"stream":45,"string_decoder":46}],7:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":16}],8:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var inherits = require('inherits') +var md5 = require('./md5') +var rmd160 = require('ripemd160') +var sha = require('sha.js') + +var Base = require('cipher-base') + +function HashNoConstructor(hash) { + Base.call(this, 'digest') + + this._hash = hash + this.buffers = [] +} + +inherits(HashNoConstructor, Base) + +HashNoConstructor.prototype._update = function (data) { + this.buffers.push(data) +} + +HashNoConstructor.prototype._final = function () { + var buf = Buffer.concat(this.buffers) + var r = this._hash(buf) + this.buffers = null + + return r +} + +function Hash(hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if ('md5' === alg) return new HashNoConstructor(md5) + if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160) + + return new Hash(sha(alg)) +} + +}).call(this,require("buffer").Buffer) +},{"./md5":10,"buffer":5,"cipher-base":6,"inherits":15,"ripemd160":36,"sha.js":38}],9:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } - function hash(buf, fn, hashSize, bigEndian) { - if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); - var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); - return toBuffer(arr, hashSize, bigEndian); - } - exports.hash = hash; - }.call(this, require("buffer").Buffer)); - }, - { buffer: 5 } - ], - 10: [ - function(require, module, exports) { - "use strict"; - /* + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} +exports.hash = hash; +}).call(this,require("buffer").Buffer) +},{"buffer":5}],10:[function(require,module,exports){ +'use strict'; +/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. @@ -4024,229 +3481,227 @@ * See http://pajhome.org.uk/crypt/md5 for more info. */ - var helpers = require("./helpers"); +var helpers = require('./helpers'); - /* +/* * Calculate the MD5 of an array of little-endian words, and a bit length */ - function core_md5(x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << (len % 32); - x[((len + 64) >>> 9 << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for (var i = 0; i < x.length; i += 16) { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936); - d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); - c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); - b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); - d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); - a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); - b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); - c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - - a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); - d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); - b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302); - a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); - d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); - c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); - b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); - a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); - d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); - b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); - c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - - a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); - d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); - a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); - b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); - d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222); - c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); - b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); - a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); - d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); - c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); - b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - - a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844); - d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); - a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); - b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); - c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); - d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); - b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - - a = safe_add(a, olda); - b = safe_add(b, oldb); - c = safe_add(c, oldc); - d = safe_add(d, oldd); - } - return Array(a, b, c, d); - } +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} - /* +/* * These functions implement the four basic operations the algorithm uses. */ - function md5_cmn(q, a, b, x, s, t) { - return safe_add( - bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), - b - ); - } - function md5_ff(a, b, c, d, x, s, t) { - return md5_cmn((b & c) | (~b & d), a, b, x, s, t); - } - function md5_gg(a, b, c, d, x, s, t) { - return md5_cmn((b & d) | (c & ~d), a, b, x, s, t); - } - function md5_hh(a, b, c, d, x, s, t) { - return md5_cmn(b ^ c ^ d, a, b, x, s, t); - } - function md5_ii(a, b, c, d, x, s, t) { - return md5_cmn(c ^ (b | ~d), a, b, x, s, t); - } - - /* +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ - function safe_add(x, y) { - var lsw = (x & 0xffff) + (y & 0xffff); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xffff); - } - - /* +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* * Bitwise rotate a 32-bit number to the left. */ - function bit_rol(num, cnt) { - return (num << cnt) | (num >>> (32 - cnt)); - } +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; +},{"./helpers":9}],11:[function(require,module,exports){ +(function (Buffer){ +'use strict'; +var createHash = require('create-hash/browser'); +var inherits = require('inherits') + +var Transform = require('stream').Transform + +var ZEROS = new Buffer(128) +ZEROS.fill(0) + +function Hmac(alg, key) { + Transform.call(this) + alg = alg.toLowerCase() + if (typeof key === 'string') { + key = new Buffer(key) + } - module.exports = function md5(buf) { - return helpers.hash(buf, core_md5, 16); - }; - }, - { "./helpers": 9 } - ], - 11: [ - function(require, module, exports) { - (function(Buffer) { - "use strict"; - var createHash = require("create-hash/browser"); - var inherits = require("inherits"); - - var Transform = require("stream").Transform; - - var ZEROS = new Buffer(128); - ZEROS.fill(0); - - function Hmac(alg, key) { - Transform.call(this); - alg = alg.toLowerCase(); - if (typeof key === "string") { - key = new Buffer(key); - } + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 - var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64; + this._alg = alg + this._key = key - this._alg = alg; - this._key = key; + if (key.length > blocksize) { + key = createHash(alg).update(key).digest() - if (key.length > blocksize) { - key = createHash(alg).update(key).digest(); - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize); - } + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } - var ipad = (this._ipad = new Buffer(blocksize)); - var opad = (this._opad = new Buffer(blocksize)); + var ipad = this._ipad = new Buffer(blocksize) + var opad = this._opad = new Buffer(blocksize) - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5c; - } + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } - this._hash = createHash(alg).update(ipad); - } + this._hash = createHash(alg).update(ipad) +} - inherits(Hmac, Transform); +inherits(Hmac, Transform) - Hmac.prototype.update = function(data, enc) { - this._hash.update(data, enc); +Hmac.prototype.update = function (data, enc) { + this._hash.update(data, enc) - return this; - }; + return this +} - Hmac.prototype._transform = function(data, _, next) { - this._hash.update(data); +Hmac.prototype._transform = function (data, _, next) { + this._hash.update(data) - next(); - }; + next() +} - Hmac.prototype._flush = function(next) { - this.push(this.digest()); +Hmac.prototype._flush = function (next) { + this.push(this.digest()) - next(); - }; + next() +} - Hmac.prototype.digest = function(enc) { - var h = this._hash.digest(); +Hmac.prototype.digest = function (enc) { + var h = this._hash.digest() - return createHash(this._alg) - .update(this._opad) - .update(h) - .digest(enc); - }; + return createHash(this._alg).update(this._opad).update(h).digest(enc) +} - module.exports = function createHmac(alg, key) { - return new Hmac(alg, key); - }; - }.call(this, require("buffer").Buffer)); - }, - { buffer: 5, "create-hash/browser": 8, inherits: 15, stream: 45 } - ], - 12: [ - function(require, module, exports) { - (function(process, global) { - /*! +module.exports = function createHmac(alg, key) { + return new Hmac(alg, key) +} + +}).call(this,require("buffer").Buffer) +},{"buffer":5,"create-hash/browser":8,"inherits":15,"stream":45}],12:[function(require,module,exports){ +(function (process,global){ +/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license @@ -4254,207 +3709,184 @@ * @version 4.1.0 */ - (function(global, factory) { - typeof exports === "object" && typeof module !== "undefined" - ? (module.exports = factory()) - : typeof define === "function" && define.amd - ? define(factory) - : (global.ES6Promise = factory()); - })(this, function() { - "use strict"; - function objectOrFunction(x) { - return ( - typeof x === "function" || - (typeof x === "object" && x !== null) - ); - } - - function isFunction(x) { - return typeof x === "function"; - } - - var _isArray = undefined; - if (!Array.isArray) { - _isArray = function(x) { - return Object.prototype.toString.call(x) === "[object Array]"; - }; - } else { - _isArray = Array.isArray; - } - - var isArray = _isArray; - - var len = 0; - var vertxNext = undefined; - var customSchedulerFn = undefined; - - var asap = function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (customSchedulerFn) { - customSchedulerFn(flush); - } else { - scheduleFlush(); - } - } - }; - - function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; - } - - function setAsap(asapFn) { - asap = asapFn; - } - - var browserWindow = typeof window !== "undefined" - ? window - : undefined; - var browserGlobal = browserWindow || {}; - var BrowserMutationObserver = - browserGlobal.MutationObserver || - browserGlobal.WebKitMutationObserver; - var isNode = - typeof self === "undefined" && - typeof process !== "undefined" && - {}.toString.call(process) === "[object process]"; - - // test for web worker but not in IE10 - var isWorker = - typeof Uint8ClampedArray !== "undefined" && - typeof importScripts !== "undefined" && - typeof MessageChannel !== "undefined"; - - // node - function useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - return process.nextTick(flush); - }; - } - - // vertx - function useVertxTimer() { - if (typeof vertxNext !== "undefined") { - return function() { - vertxNext(flush); - }; - } - - return useSetTimeout(); - } - - function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(""); - observer.observe(node, { characterData: true }); - - return function() { - node.data = iterations = ++iterations % 2; - }; - } - - // web worker - function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function() { - return channel.port2.postMessage(0); - }; - } - - function useSetTimeout() { - // Store setTimeout reference so es6-promise will be unaffected by - // other code modifying setTimeout (like sinon.useFakeTimers()) - var globalSetTimeout = setTimeout; - return function() { - return globalSetTimeout(flush, 1); - }; - } - - var queue = new Array(1000); - function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; - - callback(arg); - - queue[i] = undefined; - queue[i + 1] = undefined; - } - - len = 0; - } - - function attemptVertx() { - try { - var r = require; - var vertx = r("vertx"); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } - } - - var scheduleFlush = undefined; - // Decide what async method to use to triggering processing of queued callbacks: - if (isNode) { - scheduleFlush = useNextTick(); - } else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); - } else if (isWorker) { - scheduleFlush = useMessageChannel(); - } else if ( - browserWindow === undefined && - typeof require === "function" - ) { - scheduleFlush = attemptVertx(); - } else { - scheduleFlush = useSetTimeout(); - } - - function then(onFulfillment, onRejection) { - var _arguments = arguments; - - var parent = this; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} + +function isFunction(x) { + return typeof x === 'function'; +} + +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } - var child = new this.constructor(noop); + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = undefined; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var _arguments = arguments; + + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } - var _state = parent._state; + var _state = parent._state; - if (_state) { - (function() { - var callback = _arguments[_state - 1]; - asap(function() { - return invokeCallback( - _state, - child, - callback, - parent._result - ); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } - return child; - } + return child; +} - /** +/** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: @@ -4485,411 +3917,372 @@ @return {Promise} a promise that will become fulfilled with the given `value` */ - function resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if ( - object && - typeof object === "object" && - object.constructor === Constructor - ) { - return object; - } - - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; - } +function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; - var PROMISE_ID = Math.random().toString(36).substring(16); + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } - function noop() {} + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} - var PENDING = void 0; - var FULFILLED = 1; - var REJECTED = 2; +var PROMISE_ID = Math.random().toString(36).substring(16); - var GET_THEN_ERROR = new ErrorObject(); +function noop() {} - function selfFulfillment() { - return new TypeError( - "You cannot resolve a promise with itself" - ); - } +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; - function cannotReturnOwn() { - return new TypeError( - "A promises callback cannot return that same promise." - ); - } +var GET_THEN_ERROR = new ErrorObject(); - function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } - } +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} - function tryThen( - then, - value, - fulfillmentHandler, - rejectionHandler - ) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } - } +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} - function handleForeignThenable(promise, thenable, then) { - asap(function(promise) { - var sealed = false; - var error = tryThen( - then, - thenable, - function(value) { - if (sealed) { - return; - } - sealed = true; - if (thenable !== value) { - _resolve(promise, value); - } else { - fulfill(promise, value); - } - }, - function(reason) { - if (sealed) { - return; - } - sealed = true; - - _reject(promise, reason); - }, - "Settle: " + (promise._label || " unknown promise") - ); - - if (!sealed && error) { - sealed = true; - _reject(promise, error); - } - }, promise); - } +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} - function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - _reject(promise, thenable._result); - } else { - subscribe( - thenable, - undefined, - function(value) { - return _resolve(promise, value); - }, - function(reason) { - return _reject(promise, reason); - } - ); - } - } +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + _resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; - function handleMaybeThenable(promise, maybeThenable, then$$) { - if ( - maybeThenable.constructor === promise.constructor && - then$$ === then && - maybeThenable.constructor.resolve === resolve - ) { - handleOwnThenable(promise, maybeThenable); - } else { - if (then$$ === GET_THEN_ERROR) { - _reject(promise, GET_THEN_ERROR.error); - GET_THEN_ERROR.error = null; - } else if (then$$ === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then$$)) { - handleForeignThenable(promise, maybeThenable, then$$); - } else { - fulfill(promise, maybeThenable); - } - } - } + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); - function _resolve(promise, value) { - if (promise === value) { - _reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } - } + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + _reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return _resolve(promise, value); + }, function (reason) { + return _reject(promise, reason); + }); + } +} - function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } +function handleMaybeThenable(promise, maybeThenable, then$$) { + if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$ === GET_THEN_ERROR) { + _reject(promise, GET_THEN_ERROR.error); + GET_THEN_ERROR.error = null; + } else if (then$$ === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$)) { + handleForeignThenable(promise, maybeThenable, then$$); + } else { + fulfill(promise, maybeThenable); + } + } +} - publish(promise); - } +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} - function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } - promise._result = value; - promise._state = FULFILLED; + publish(promise); +} - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } - } +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } - function _reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; + promise._result = value; + promise._state = FULFILLED; - asap(publishRejection, promise); - } + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} - function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; - parent._onerror = null; + asap(publishRejection, promise); +} - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; - if (length === 0 && parent._state) { - asap(publish, parent); - } - } + parent._onerror = null; - function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; - if (subscribers.length === 0) { - return; - } + if (length === 0 && parent._state) { + asap(publish, parent); + } +} - var child = undefined, - callback = undefined, - detail = promise._result; +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; + if (subscribers.length === 0) { + return; + } - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } + var child = undefined, + callback = undefined, + detail = promise._result; - promise._subscribers.length = 0; - } + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; - function ErrorObject() { - this.error = null; - } + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } - var TRY_CATCH_ERROR = new ErrorObject(); + promise._subscribers.length = 0; +} - function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } - } +function ErrorObject() { + this.error = null; +} - function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value.error = null; - } else { - succeeded = true; - } - - if (promise === value) { - _reject(promise, cannotReturnOwn()); - return; - } - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - _resolve(promise, value); - } else if (failed) { - _reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - _reject(promise, value); - } - } +var TRY_CATCH_ERROR = new ErrorObject(); - function initializePromise(promise, resolver) { - try { - resolver( - function resolvePromise(value) { - _resolve(promise, value); - }, - function rejectPromise(reason) { - _reject(promise, reason); - } - ); - } catch (e) { - _reject(promise, e); - } - } +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } - var id = 0; - function nextId() { - return id++; - } + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } - function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; - } + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + _resolve(promise, value); + } else if (failed) { + _reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + _reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - function Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); - - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } - - if (isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(); - if (this._remaining === 0) { - fulfill(this.promise, this._result); - } - } - } else { - _reject(this.promise, validationError()); - } - } + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; - function validationError() { - return new Error("Array Methods must be provided an Array"); - } + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + _reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + + if (resolve$$ === resolve) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$) { + return resolve$$(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$(entry), i); + } +}; + +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; - Enumerator.prototype._enumerate = function() { - var length = this.length; - var _input = this._input; - - for (var i = 0; this._state === PENDING && i < length; i++) { - this._eachEntry(_input[i], i); - } - }; - - Enumerator.prototype._eachEntry = function(entry, i) { - var c = this._instanceConstructor; - var resolve$$ = c.resolve; - - if (resolve$$ === resolve) { - var _then = getThen(entry); - - if (_then === then && entry._state !== PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof _then !== "function") { - this._remaining--; - this._result[i] = entry; - } else if (c === Promise) { - var promise = new c(noop); - handleMaybeThenable(promise, entry, _then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt( - new c(function(resolve$$) { - return resolve$$(entry); - }), - i - ); - } - } else { - this._willSettleAt(resolve$$(entry), i); - } - }; - - Enumerator.prototype._settledAt = function(state, i, value) { - var promise = this.promise; - - if (promise._state === PENDING) { - this._remaining--; - - if (state === REJECTED) { - _reject(promise, value); - } else { - this._result[i] = value; - } - } - - if (this._remaining === 0) { - fulfill(promise, this._result); - } - }; - - Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - subscribe( - promise, - undefined, - function(value) { - return enumerator._settledAt(FULFILLED, i, value); - }, - function(reason) { - return enumerator._settledAt(REJECTED, i, reason); - } - ); - }; - - /** + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); +}; + +/** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all @@ -4936,11 +4329,11 @@ fulfilled, or rejected if any of them become rejected. @static */ - function all(entries) { - return new Enumerator(this, entries).promise; - } +function all(entries) { + return new Enumerator(this, entries).promise; +} - /** +/** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. @@ -5005,27 +4398,25 @@ @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ - function race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!isArray(entries)) { - return new Constructor(function(_, reject) { - return reject( - new TypeError("You must pass an array to race.") - ); - }); - } else { - return new Constructor(function(resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); - } - }); - } - } +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} - /** +/** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: @@ -5059,27 +4450,23 @@ Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ - function reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - _reject(promise, reason); - return promise; - } - - function needsResolver() { - throw new TypeError( - "You must pass a resolver function as the first argument to the promise constructor" - ); - } - - function needsNew() { - throw new TypeError( - "Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function." - ); - } - - /** +function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason @@ -5182,31 +4569,29 @@ Useful for tooling. @constructor */ - function Promise(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (noop !== resolver) { - typeof resolver !== "function" && needsResolver(); - this instanceof Promise - ? initializePromise(this, resolver) - : needsNew(); - } - } +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} - Promise.all = all; - Promise.race = race; - Promise.resolve = resolve; - Promise.reject = reject; - Promise._setScheduler = setScheduler; - Promise._setAsap = setAsap; - Promise._asap = asap; +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; - Promise.prototype = { - constructor: Promise, +Promise.prototype = { + constructor: Promise, - /** + /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. @@ -5399,9 +4784,9 @@ Useful for tooling. @return {Promise} */ - then: then, + then: then, - /** + /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. @@ -5428,560 +4813,501 @@ Useful for tooling. @return {Promise} */ - catch: function _catch(onRejection) { - return this.then(null, onRejection); - } - }; - - function polyfill() { - var local = undefined; - - if (typeof global !== "undefined") { - local = global; - } else if (typeof self !== "undefined") { - local = self; - } else { - try { - local = Function("return this")(); - } catch (e) { - throw new Error( - "polyfill failed because global object is unavailable in this environment" - ); - } - } - - var P = local.Promise; - - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call( - P.resolve() - ); - } catch (e) { - // silently ignored - } - - if (promiseToString === "[object Promise]" && !P.cast) { - return; - } - } - - local.Promise = Promise; - } + 'catch': function _catch(onRejection) { + return this.then(null, onRejection); + } +}; - // Strange compat.. - Promise.polyfill = polyfill; - Promise.Promise = Promise; - - return Promise; - }); - }.call( - this, - require("_process"), - typeof global !== "undefined" - ? global - : typeof self !== "undefined" - ? self - : typeof window !== "undefined" ? window : {} - )); - }, - { _process: 22 } - ], - 13: [ - function(require, module, exports) { - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; - } - module.exports = EventEmitter; - - // Backwards-compat with node 0.10.x - EventEmitter.EventEmitter = EventEmitter; - - EventEmitter.prototype._events = undefined; - EventEmitter.prototype._maxListeners = undefined; - - // By default EventEmitters will print a warning if more than 10 listeners are - // added to it. This is a useful default which helps finding memory leaks. - EventEmitter.defaultMaxListeners = 10; - - // Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError("n must be a positive number"); - this._maxListeners = n; - return this; - }; - - EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === "error") { - if ( - !this._events.error || - (isObject(this._events.error) && !this._events.error.length) - ) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error( - 'Uncaught, unspecified "error" event. (' + er + ")" - ); - err.context = er; - throw err; - } - } - } +function polyfill() { + var local = undefined; - handler = this._events[type]; - - if (isUndefined(handler)) return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } - return true; - }; - - EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError("listener must be a function"); - - if (!this._events) this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit( - "newListener", - type, - isFunction(listener.listener) ? listener.listener : listener - ); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } + var P = local.Promise; - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error( - "(node) warning: possible EventEmitter memory " + - "leak detected. %d listeners added. " + - "Use emitter.setMaxListeners() to increase limit.", - this._events[type].length - ); - if (typeof console.trace === "function") { - // not supported in IE 10 - console.trace(); - } - } - } + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } - return this; - }; + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } - EventEmitter.prototype.on = EventEmitter.prototype.addListener; + local.Promise = Promise; +} + +// Strange compat.. +Promise.polyfill = polyfill; +Promise.Promise = Promise; + +return Promise; + +}))); + + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":22}],13:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError("listener must be a function"); + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - var fired = false; + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } - function g() { - this.removeListener(type, g); + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } + return this; +}; - g.listener = listener; - this.on(type, g); - - return this; - }; - - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError("listener must be a function"); - - if (!this._events || !this._events[type]) return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if ( - list === listener || - (isFunction(list.listener) && list.listener === listener) - ) { - delete this._events[type]; - if (this._events.removeListener) - this.emit("removeListener", type, listener); - } else if (isObject(list)) { - for (i = length; i-- > 0; ) { - if ( - list[i] === listener || - (list[i].listener && list[i].listener === listener) - ) { - position = i; - break; - } - } +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - if (position < 0) return this; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + var fired = false; - if (this._events.removeListener) - this.emit("removeListener", type, listener); - } + function g() { + this.removeListener(type, g); - return this; - }; + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + g.listener = listener; + this.on(type, g); - if (!this._events) return this; + return this; +}; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) this._events = {}; - else if (this._events[type]) delete this._events[type]; - return this; - } +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === "removeListener") continue; - this.removeAllListeners(key); - } - this.removeAllListeners("removeListener"); - this._events = {}; - return this; - } + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - listeners = this._events[type]; + if (!this._events || !this._events[type]) + return this; - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; + list = this._events[type]; + length = list.length; + position = -1; - return this; - }; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) ret = []; - else if (isFunction(this._events[type])) ret = [this._events[type]]; - else ret = this._events[type].slice(); - return ret; - }; + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } - EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + if (position < 0) + return this; - if (isFunction(evlistener)) return 1; - else if (evlistener) return evlistener.length; - } - return 0; - }; + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } - EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); - }; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } - function isFunction(arg) { - return typeof arg === "function"; - } + return this; +}; - function isNumber(arg) { - return typeof arg === "number"; - } +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - function isObject(arg) { - return typeof arg === "object" && arg !== null; - } + if (!this._events) + return this; - function isUndefined(arg) { - return arg === void 0; - } - }, - {} - ], - 14: [ - function(require, module, exports) { - exports.read = function(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << -nBits) - 1); - s >>= -nBits; - nBits += eLen; - for ( - ; - nBits > 0; - (e = e * 256 + buffer[offset + i]), (i += d), (nBits -= 8) - ) { - } + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - m = e & ((1 << -nBits) - 1); - e >>= -nBits; - nBits += mLen; - for ( - ; - nBits > 0; - (m = m * 256 + buffer[offset + i]), (i += d), (nBits -= 8) - ) { - } + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - - exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } + listeners = this._events[type]; - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],14:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } - for ( - ; - mLen >= 8; - (buffer[offset + i] = m & 0xff), (i += d), (m /= 256), (mLen -= 8) - ) { - } + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } - e = (e << mLen) | m; - eLen += mLen; - for ( - ; - eLen > 0; - (buffer[offset + i] = e & 0xff), (i += d), (e /= 256), (eLen -= 8) - ) { - } + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],15:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} - buffer[offset + i - d] |= s * 128; - }; - }, - {} - ], - 15: [ - function(require, module, exports) { - if (typeof Object.create === "function") { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - }, - {} - ], - 16: [ - function(require, module, exports) { - /*! +},{}],16:[function(require,module,exports){ +/*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - module.exports = function(obj) { - return ( - obj != null && - (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) - ); - }; - - function isBuffer(obj) { - return ( - !!obj.constructor && - typeof obj.constructor.isBuffer === "function" && - obj.constructor.isBuffer(obj) - ); - } +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer(obj) { - return ( - typeof obj.readFloatLE === "function" && - typeof obj.slice === "function" && - isBuffer(obj.slice(0, 0)) - ); - } - }, - {} - ], - 17: [ - function(require, module, exports) { - var toString = {}.toString; - - module.exports = - Array.isArray || - function(arr) { - return toString.call(arr) == "[object Array]"; - }; - }, - {} - ], - 18: [ - function(require, module, exports) { - /** +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],17:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],18:[function(require,module,exports){ +/** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors @@ -5990,18 +5316,18 @@ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** `Object#toString` result references. */ - var argsTag = "[object Arguments]", - funcTag = "[object Function]", - genTag = "[object GeneratorFunction]"; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - /** +/** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * @@ -6011,21 +5337,17 @@ * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: - return func.call(thisArg); - case 1: - return func.call(thisArg, args[0]); - case 2: - return func.call(thisArg, args[0], args[1]); - case 3: - return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} - /** +/** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * @@ -6034,16 +5356,17 @@ * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ - function baseTimes(n, iteratee) { - var index = -1, result = Array(n); +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - /** +/** * Creates a unary function that invokes `func` with its argument transformed. * * @private @@ -6051,38 +5374,36 @@ * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} - /** Used for built-in method references. */ - var objectProto = Object.prototype; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** +/** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ - var objectToString = objectProto.toString; +var objectToString = objectProto.toString; - /** Built-in value references. */ - var propertyIsEnumerable = objectProto.propertyIsEnumerable; +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max; +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; - /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ - var nonEnumShadows = !propertyIsEnumerable.call( - { valueOf: 1 }, - "valueOf" - ); +/** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ +var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf'); - /** +/** * Creates an array of the enumerable property names of the array-like `value`. * * @private @@ -6090,27 +5411,26 @@ * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = isArray(value) || isArguments(value) - ? baseTimes(value.length, String) - : []; - - var length = result.length, skipIndexes = !!length; - - for (var key in value) { - if ( - (inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == "length" || isIndex(key, length))) - ) { - result.push(key); - } - } - return result; - } +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} - /** +/** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. @@ -6120,37 +5440,35 @@ * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ - function assignValue(object, key, value) { - var objValue = object[key]; - if ( - !(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object)) - ) { - object[key] = value; - } - } +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; + } +} - /** +/** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != "constructor") { - result.push(key); - } - } - return result; - } +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} - /** +/** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private @@ -6158,28 +5476,28 @@ * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ - function baseRest(func, start) { - start = nativeMax(start === undefined ? func.length - 1 : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; - } +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} - /** +/** * Copies properties of `source` to `object`. * * @private @@ -6189,62 +5507,58 @@ * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ - function copyObject(source, props, object, customizer) { - object || (object = {}); +function copyObject(source, props, object, customizer) { + object || (object = {}); - var index = -1, length = props.length; + var index = -1, + length = props.length; - while (++index < length) { - var key = props[index]; + while (++index < length) { + var key = props[index]; - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; - assignValue( - object, - key, - newValue === undefined ? source[key] : newValue - ); - } - return object; - } + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} - /** +/** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = assigner.length > 3 && - typeof customizer == "function" - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} - /** +/** * Checks if `value` is a valid array-like index. * * @private @@ -6252,16 +5566,14 @@ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return ( - !!length && - (typeof value == "number" || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length) - ); - } - - /** +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** * Checks if the given arguments are from an iteratee call. * * @private @@ -6271,37 +5583,35 @@ * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if ( - type == "number" - ? isArrayLike(object) && isIndex(index, object.length) - : type == "string" && index in object - ) { - return eq(object[index], value); - } - return false; - } +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} - /** +/** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = - (typeof Ctor == "function" && Ctor.prototype) || objectProto; +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - return value === proto; - } + return value === proto; +} - /** +/** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. @@ -6333,11 +5643,11 @@ * _.eq(NaN, NaN); * // => true */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - /** +/** * Checks if `value` is likely an `arguments` object. * * @static @@ -6355,17 +5665,13 @@ * _.isArguments([1, 2, 3]); * // => false */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return ( - isArrayLikeObject(value) && - hasOwnProperty.call(value, "callee") && - (!propertyIsEnumerable.call(value, "callee") || - objectToString.call(value) == argsTag) - ); - } +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** +/** * Checks if `value` is classified as an `Array` object. * * @static @@ -6388,9 +5694,9 @@ * _.isArray(_.noop); * // => false */ - var isArray = Array.isArray; +var isArray = Array.isArray; - /** +/** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. @@ -6415,13 +5721,11 @@ * _.isArrayLike(_.noop); * // => false */ - function isArrayLike(value) { - return ( - value != null && isLength(value.length) && !isFunction(value) - ); - } +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** +/** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * @@ -6446,11 +5750,11 @@ * _.isArrayLikeObject(_.noop); * // => false */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** +/** * Checks if `value` is classified as a `Function` object. * * @static @@ -6467,14 +5771,14 @@ * _.isFunction(/abc/); * // => false */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ""; - return tag == funcTag || tag == genTag; - } - - /** +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on @@ -6500,16 +5804,12 @@ * _.isLength('3'); * // => false */ - function isLength(value) { - return ( - typeof value == "number" && - value > -1 && - value % 1 == 0 && - value <= MAX_SAFE_INTEGER - ); - } +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - /** +/** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) @@ -6534,12 +5834,12 @@ * _.isObject(null); * // => false */ - function isObject(value) { - var type = typeof value; - return !!value && (type == "object" || type == "function"); - } +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** +/** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * @@ -6563,11 +5863,11 @@ * _.isObjectLike(null); * // => false */ - function isObjectLike(value) { - return !!value && typeof value == "object"; - } +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** +/** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. @@ -6599,19 +5899,19 @@ * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ - var assign = createAssigner(function(object, source) { - if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); +var assign = createAssigner(function(object, source) { + if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } +}); - /** +/** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the @@ -6639,2823 +5939,2480 @@ * _.keys('hi'); * // => ['0', '1'] */ - function keys(object) { - return isArrayLike(object) - ? arrayLikeKeys(object) - : baseKeys(object); - } +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} - module.exports = assign; - }, - {} - ], - 19: [ - function(require, module, exports) { - (function(process, Buffer) { - var createHmac = require("create-hmac"); - var checkParameters = require("./precondition"); - - exports.pbkdf2 = function( - password, - salt, - iterations, - keylen, - digest, - callback - ) { - if (typeof digest === "function") { - callback = digest; - digest = undefined; - } +module.exports = assign; - checkParameters(iterations, keylen); - if (typeof callback !== "function") - throw new Error("No callback provided to pbkdf2"); - - setTimeout(function() { - callback( - null, - exports.pbkdf2Sync(password, salt, iterations, keylen, digest) - ); - }); - }; - - var defaultEncoding; - if (process.browser) { - defaultEncoding = "utf-8"; - } else { - var pVersionMajor = parseInt( - process.version.split(".")[0].slice(1), - 10 - ); +},{}],19:[function(require,module,exports){ +(function (process,Buffer){ +var createHmac = require('create-hmac') +var checkParameters = require('./precondition') - defaultEncoding = pVersionMajor >= 6 ? "utf-8" : "binary"; - } +exports.pbkdf2 = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } - exports.pbkdf2Sync = function( - password, - salt, - iterations, - keylen, - digest - ) { - if (!Buffer.isBuffer(password)) - password = new Buffer(password, defaultEncoding); - if (!Buffer.isBuffer(salt)) - salt = new Buffer(salt, defaultEncoding); - - checkParameters(iterations, keylen); - - digest = digest || "sha1"; - - var hLen; - var l = 1; - var DK = new Buffer(keylen); - var block1 = new Buffer(salt.length + 4); - salt.copy(block1, 0, 0, salt.length); - - var r; - var T; - - for (var i = 1; i <= l; i++) { - block1.writeUInt32BE(i, salt.length); - var U = createHmac(digest, password).update(block1).digest(); - - if (!hLen) { - hLen = U.length; - T = new Buffer(hLen); - l = Math.ceil(keylen / hLen); - r = keylen - (l - 1) * hLen; - } - - U.copy(T, 0, 0, hLen); - - for (var j = 1; j < iterations; j++) { - U = createHmac(digest, password).update(U).digest(); - for (var k = 0; k < hLen; k++) - T[k] ^= U[k]; - } - - var destPos = (i - 1) * hLen; - var len = i === l ? r : hLen; - T.copy(DK, destPos, 0, len); - } + checkParameters(iterations, keylen) + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') - return DK; - }; - }.call(this, require("_process"), require("buffer").Buffer)); - }, - { "./precondition": 20, _process: 22, buffer: 5, "create-hmac": 11 } - ], - 20: [ - function(require, module, exports) { - var MAX_ALLOC = Math.pow(2, 30) - 1; // default in iojs - module.exports = function(iterations, keylen) { - if (typeof iterations !== "number") { - throw new TypeError("Iterations not a number"); - } + setTimeout(function () { + callback(null, exports.pbkdf2Sync(password, salt, iterations, keylen, digest)) + }) +} - if (iterations < 0) { - throw new TypeError("Bad iterations"); - } +var defaultEncoding +if (process.browser) { + defaultEncoding = 'utf-8' +} else { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) - if (typeof keylen !== "number") { - throw new TypeError("Key length not a number"); - } + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} - if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { - /* eslint no-self-compare: 0 */ - throw new TypeError("Bad key length"); - } - }; - }, - {} - ], - 21: [ - function(require, module, exports) { - (function(process) { - "use strict"; - if ( - !process.version || - process.version.indexOf("v0.") === 0 || - (process.version.indexOf("v1.") === 0 && - process.version.indexOf("v1.8.") !== 0) - ) { - module.exports = nextTick; - } else { - module.exports = process.nextTick; - } +exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) { + if (!Buffer.isBuffer(password)) password = new Buffer(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, defaultEncoding) - function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== "function") { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } - } - }.call(this, require("_process"))); - }, - { _process: 22 } - ], - 22: [ - function(require, module, exports) { - // shim for using process in browser - var process = (module.exports = {}); - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); - } - function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); - } - (function() { - try { - if (typeof setTimeout === "function") { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === "function") { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - })(); - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ( - (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && - setTimeout - ) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ( - (cachedClearTimeout === defaultClearTimeout || - !cachedClearTimeout) && - clearTimeout - ) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } + checkParameters(iterations, keylen) - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } + digest = digest || 'sha1' - process.nextTick = function(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; + var hLen + var l = 1 + var DK = new Buffer(keylen) + var block1 = new Buffer(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function() { - this.fun.apply(null, this.array); - }; - process.title = "browser"; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ""; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - process.prependListener = noop; - process.prependOnceListener = noop; - - process.listeners = function(name) { - return []; - }; - - process.binding = function(name) { - throw new Error("process.binding is not supported"); - }; - - process.cwd = function() { - return "/"; - }; - process.chdir = function(dir) { - throw new Error("process.chdir is not supported"); - }; - process.umask = function() { - return 0; - }; - }, - {} - ], - 23: [ - function(require, module, exports) { - module.exports = require("./lib/_stream_duplex.js"); - }, - { "./lib/_stream_duplex.js": 24 } - ], - 24: [ - function(require, module, exports) { - // a duplex stream is just a stream that is both readable and writable. - // Since JS doesn't have multiple prototypal inheritance, this class - // prototypally inherits from Readable, and then parasitically from - // Writable. - - "use strict"; - /**/ - - var objectKeys = - Object.keys || - function(obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - } - return keys; - }; - /**/ + var r + var T + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + var U = createHmac(digest, password).update(block1).digest() - module.exports = Duplex; + if (!hLen) { + hLen = U.length + T = new Buffer(hLen) + l = Math.ceil(keylen / hLen) + r = keylen - (l - 1) * hLen + } - /**/ - var processNextTick = require("process-nextick-args"); - /**/ + U.copy(T, 0, 0, hLen) - /**/ - var util = require("core-util-is"); - util.inherits = require("inherits"); - /**/ + for (var j = 1; j < iterations; j++) { + U = createHmac(digest, password).update(U).digest() + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } - var Readable = require("./_stream_readable"); - var Writable = require("./_stream_writable"); + var destPos = (i - 1) * hLen + var len = (i === l ? r : hLen) + T.copy(DK, destPos, 0, len) + } - util.inherits(Duplex, Readable); + return DK +} - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; - } +}).call(this,require('_process'),require("buffer").Buffer) +},{"./precondition":20,"_process":22,"buffer":5,"create-hmac":11}],20:[function(require,module,exports){ +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + if (iterations < 0) { + throw new TypeError('Bad iterations') + } - Readable.call(this, options); - Writable.call(this, options); + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } - if (options && options.readable === false) this.readable = false; + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + +},{}],21:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + +}).call(this,require('_process')) +},{"_process":22}],22:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - if (options && options.writable === false) this.writable = false; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } - this.once("end", onend); - } - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); - } +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; - function onEndNT(self) { - self.end(); - } +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); } - } - }, - { - "./_stream_readable": 26, - "./_stream_writable": 28, - "core-util-is": 7, - inherits: 15, - "process-nextick-args": 21 } - ], - 25: [ - function(require, module, exports) { - // a passthrough stream. - // basically just the most minimal sort of Transform stream. - // Every written chunk gets output as-is. - - "use strict"; - module.exports = PassThrough; + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],23:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); + +},{"./lib/_stream_duplex.js":24}],24:[function(require,module,exports){ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} - var Transform = require("./_stream_transform"); +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":26,"./_stream_writable":28,"core-util-is":7,"inherits":15,"process-nextick-args":21}],25:[function(require,module,exports){ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - /**/ - var util = require("core-util-is"); - util.inherits = require("inherits"); - /**/ +'use strict'; - util.inherits(PassThrough, Transform); +module.exports = PassThrough; - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); +var Transform = require('./_stream_transform'); - Transform.call(this, options); - } +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); - }; - }, - { "./_stream_transform": 27, "core-util-is": 7, inherits: 15 } - ], - 26: [ - function(require, module, exports) { - (function(process) { - "use strict"; - module.exports = Readable; - - /**/ - var processNextTick = require("process-nextick-args"); - /**/ - - /**/ - var isArray = require("isarray"); - /**/ - - /**/ - var Duplex; - /**/ - - Readable.ReadableState = ReadableState; - - /**/ - var EE = require("events").EventEmitter; - - var EElistenerCount = function(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ - - /**/ - var Stream = require("./internal/streams/stream"); - /**/ - - var Buffer = require("buffer").Buffer; - /**/ - var bufferShim = require("buffer-shims"); - /**/ - - /**/ - var util = require("core-util-is"); - util.inherits = require("inherits"); - /**/ - - /**/ - var debugUtil = require("util"); - var debug = void 0; - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); - } else { - debug = function() {}; - } - /**/ - - var BufferList = require("./internal/streams/BufferList"); - var StringDecoder; - - util.inherits(Readable, Stream); - - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === "function") { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else emitter._events[event] = [fn, emitter._events[event]]; - } - } +util.inherits(PassThrough, Transform); - function ReadableState(options, stream) { - Duplex = Duplex || require("./_stream_duplex"); - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) - this.objectMode = - this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || "utf8"; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require("string_decoder/").StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - function Readable(options) { - Duplex = Duplex || require("./_stream_duplex"); + Transform.call(this, options); +} - if (!(this instanceof Readable)) return new Readable(options); +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":27,"core-util-is":7,"inherits":15}],26:[function(require,module,exports){ +(function (process){ +'use strict'; - this._readableState = new ReadableState(options, this); +module.exports = Readable; - // legacy - this.readable = true; +/**/ +var processNextTick = require('process-nextick-args'); +/**/ - if (options && typeof options.read === "function") - this._read = options.read; +/**/ +var isArray = require('isarray'); +/**/ - Stream.call(this); - } +/**/ +var Duplex; +/**/ - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (!state.objectMode && typeof chunk === "string") { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = bufferShim.from(chunk, encoding); - encoding = ""; - } - } +Readable.ReadableState = ReadableState; - return readableAddChunk(this, state, chunk, encoding, false); - }; - - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, "", true); - }; - - Readable.prototype.isPaused = function() { - return this._readableState.flowing === false; - }; - - function readableAddChunk( - stream, - state, - chunk, - encoding, - addToFront - ) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit("error", er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || (chunk && chunk.length > 0)) { - if (state.ended && !addToFront) { - var e = new Error("stream.push() after EOF"); - stream.emit("error", e); - } else if (state.endEmitted && addToFront) { - var _e = new Error("stream.unshift() after end event"); - stream.emit("error", _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } - - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit("data", chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk); - else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } +/**/ +var EE = require('events').EventEmitter; - return needMoreData(state); - } +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return ( - !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0) - ); - } +/**/ +var Stream = require('./internal/streams/stream'); +/**/ - // backwards compatibility. - Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require("string_decoder/").StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; - - // Don't raise the hwm > 8MB - var MAX_HWM = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; - } +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead(n, state) { - if (n <= 0 || (state.length === 0 && state.ended)) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) - return state.buffer.head.data.length; - else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) - state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; - } +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function(n) { - debug("read", n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if ( - n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended) - ) { - debug("read: emitReadable", state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this); - else emitReadable(this); - return null; - } +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ - n = howMuchToRead(n, state); +var BufferList = require('./internal/streams/BufferList'); +var StringDecoder; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +util.inherits(Readable, Stream); - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug("need readable", doRead); - - // if we currently have less than the highWaterMark, then also read some - if ( - state.length === 0 || - state.length - n < state.highWaterMark - ) { - doRead = true; - debug("length less than watermark", doRead); - } +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug("reading or ended", doRead); - } else if (doRead) { - debug("do read"); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} - var ret; - if (n > 0) ret = fromList(n, state); - else ret = null; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + if (!(this instanceof Readable)) return new Readable(options); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + this._readableState = new ReadableState(options, this); - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + // legacy + this.readable = true; - if (ret !== null) this.emit("data", ret); - - return ret; - }; - - function chunkInvalid(state, chunk) { - var er = null; - if ( - !Buffer.isBuffer(chunk) && - typeof chunk !== "string" && - chunk !== null && - chunk !== undefined && - !state.objectMode - ) { - er = new TypeError("Invalid non-string/buffer chunk"); - } - return er; - } + if (options && typeof options.read === 'function') this._read = options.read; - function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + Stream.call(this); +} - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug("emitReadable", state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream); - else emitReadable_(stream); - } - } + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ''; + } + } - function emitReadable_(stream) { - debug("emit readable"); - stream.emit("readable"); - flow(stream); - } + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } - } + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } - function maybeReadMore_(stream, state) { - var len = state.length; - while ( - !state.reading && - !state.flowing && - !state.ended && - state.length < state.highWaterMark - ) { - debug("maybeReadMore read 0"); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else len = state.length; - } - state.readingMore = false; - } + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable.prototype._read = function(n) { - this.emit("error", new Error("_read() is not implemented")); - }; - - Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); - - var doEnd = - (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) processNextTick(endFn); - else src.once("end", endFn); - - dest.on("unpipe", onunpipe); - function onunpipe(readable) { - debug("onunpipe"); - if (readable === src) { - cleanup(); - } - } + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - function onend() { - debug("onend"); - dest.end(); - } + n = howMuchToRead(n, state); - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on("drain", ondrain); - - var cleanedUp = false; - function cleanup() { - debug("cleanup"); - // cleanup event handlers once the pipe is broken - dest.removeListener("close", onclose); - dest.removeListener("finish", onfinish); - dest.removeListener("drain", ondrain); - dest.removeListener("error", onerror); - dest.removeListener("unpipe", onunpipe); - src.removeListener("end", onend); - src.removeListener("end", cleanup); - src.removeListener("data", ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if ( - state.awaitDrain && - (!dest._writableState || dest._writableState.needDrain) - ) - ondrain(); - } + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on("data", ondata); - function ondata(chunk) { - debug("ondata"); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ( - ((state.pipesCount === 1 && state.pipes === dest) || - (state.pipesCount > 1 && - indexOf(state.pipes, dest) !== -1)) && - !cleanedUp - ) { - debug( - "false write response, pause", - src._readableState.awaitDrain - ); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug("onerror", er); - unpipe(); - dest.removeListener("error", onerror); - if (EElistenerCount(dest, "error") === 0) - dest.emit("error", er); - } + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } - // Make sure our error handler is attached before userland ones. - prependListener(dest, "error", onerror); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); - } - dest.once("close", onclose); - function onfinish() { - debug("onfinish"); - dest.removeListener("close", onclose); - unpipe(); - } - dest.once("finish", onfinish); + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } - function unpipe() { - debug("unpipe"); - src.unpipe(dest); - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - // tell the dest that it's being piped to - dest.emit("pipe", src); + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug("pipe resume"); - src.resume(); - } + if (ret !== null) this.emit('data', ret); - return dest; - }; - - function pipeOnDrain(src) { - return function() { - var state = src._readableState; - debug("pipeOnDrain", state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { - state.flowing = true; - flow(src); - } - }; - } + return ret; +}; - Readable.prototype.unpipe = function(dest) { - var state = this._readableState; +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); - if (!dest) dest = state.pipes; + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit("unpipe", this); - return this; - } + function onend() { + debug('onend'); + dest.end(); + } - // slow case. multiple pipe destinations. + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } - for (var i = 0; i < len; i++) { - dests[i].emit("unpipe", this); - } - return this; - } + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit("unpipe", this); - - return this; - }; - - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === "data") { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === "readable") { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); - } - } - } + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - function nReadingNextTick(self) { - debug("readable nexttick read 0"); - self.read(0); - } + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug("resume"); - state.flowing = true; - resume(this, state); - } - return this; - }; + // tell the dest that it's being piped to + dest.emit('pipe', src); - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } - } + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - function resume_(stream, state) { - if (!state.reading) { - debug("resume read 0"); - stream.read(0); - } + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit("resume"); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; - Readable.prototype.pause = function() { - debug("call pause flowing=%j", this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug("pause"); - this._readableState.flowing = false; - this.emit("pause"); - } - return this; - }; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - function flow(stream) { - var state = stream._readableState; - debug("flow", state.flowing); - while (state.flowing && stream.read() !== null) { - } - } + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on("end", function() { - debug("wrapped end"); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on("data", function(chunk) { - debug("wrapped data"); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === "function") { - this[i] = (function(method) { - return function() { - return stream[method].apply(stream, arguments); - }; - })(i); - } - } + if (!dest) dest = state.pipes; - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on( - kProxyEvents[n], - self.emit.bind(self, kProxyEvents[n]) - ); - } + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - debug("wrapped _read", n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; - }; - - // exposed for testing purposes only. - Readable._fromList = fromList; - - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift(); - else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join(""); - else if (state.buffer.length === 1) - ret = state.buffer.head.data; - else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + // slow case. multiple pipe destinations. - return ret; - } + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings - ? copyFromBufferString(n, list) - : copyFromBuffer(n, list); - } - return ret; - } + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this); + }return this; + } - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while ((p = p.next)) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str; - else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next; - else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = bufferShim.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while ((p = p.next)) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next; - else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; - function endReadable(stream) { - var state = stream._readableState; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('"endReadable()" called on non-empty stream'); +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } - } + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit("end"); - } - } + self.push(null); + }); - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } - }.call(this, require("_process"))); - }, - { - "./_stream_duplex": 24, - "./internal/streams/BufferList": 29, - "./internal/streams/stream": 30, - _process: 22, - buffer: 5, - "buffer-shims": 4, - "core-util-is": 7, - events: 13, - inherits: 15, - isarray: 17, - "process-nextick-args": 21, - "string_decoder/": 31, - util: 3 - } - ], - 27: [ - function(require, module, exports) { - // a transform stream is a readable/writable stream where you do - // something with the data. Sometimes it's called a "filter", - // but that's not a great name for it, since that implies a thing where - // some bits pass through, and others are simply ignored. (That would - // be a valid example of a transform, of course.) - // - // While the output is causally related to the input, it's not a - // necessarily symmetric or synchronous transformation. For example, - // a zlib stream might take multiple plain-text writes(), and then - // emit a single compressed chunk some time in the future. - // - // Here's how this works: - // - // The Transform stream has all the aspects of the readable and writable - // stream classes. When you write(chunk), that calls _write(chunk,cb) - // internally, and returns false if there's a lot of pending writes - // buffered up. When you call read(), that calls _read(n) until - // there's enough pending readable data buffered up. - // - // In a transform stream, the written data is placed in a buffer. When - // _read(n) is called, it transforms the queued up data, calling the - // buffered _write cb's as it consumes chunks. If consuming a single - // written chunk would result in multiple output chunks, then the first - // outputted bit calls the readcb, and subsequent chunks just go into - // the read buffer, and will cause it to emit 'readable' if necessary. - // - // This way, back-pressure is actually determined by the reading side, - // since _read has to be called to start processing a new chunk. However, - // a pathological inflate type of transform can cause excessive buffering - // here. For example, imagine a stream where every byte of input is - // interpreted as an integer from 0-255, and then results in that many - // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in - // 1kb of data being output. In this case, you could write a very small - // amount of input, and end up with a very large amount of output. In - // such a pathological inflating mechanism, there'd be no way to tell - // the system to stop doing the transform. A single 4MB write could - // cause the system to run out of memory. - // - // However, even in such a pathological case, only a single written chunk - // would be consumed, and then the rest would wait (un-transformed) until - // the results of the previous transformed chunk were consumed. - - "use strict"; - module.exports = Transform; - - var Duplex = require("./_stream_duplex"); - - /**/ - var util = require("core-util-is"); - util.inherits = require("inherits"); - /**/ - - util.inherits(Transform, Duplex); - - function TransformState(stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - var cb = ts.writecb; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } - if (!cb) - return stream.emit( - "error", - new Error("no writecb in Transform class") - ); + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + } - ts.writechunk = null; - ts.writecb = null; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - if (data !== null && data !== undefined) stream.push(data); + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = bufferShim.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - cb(er); +function endReadable(stream) { + var state = stream._readableState; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - Duplex.call(this, options); +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} - this._transformState = new TransformState(this); +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process')) +},{"./_stream_duplex":24,"./internal/streams/BufferList":29,"./internal/streams/stream":30,"_process":22,"buffer":5,"buffer-shims":4,"core-util-is":7,"events":13,"inherits":15,"isarray":17,"process-nextick-args":21,"string_decoder/":31,"util":3}],27:[function(require,module,exports){ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} - var stream = this; +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + Duplex.call(this, options); - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + this._transformState = new TransformState(this); - if (options) { - if (typeof options.transform === "function") - this._transform = options.transform; + var stream = this; - if (typeof options.flush === "function") - this._flush = options.flush; - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - // When the writable side finishes, then flush out anything remaining. - this.once("prefinish", function() { - if (typeof this._flush === "function") - this._flush(function(er, data) { - done(stream, er, data); - }); - else done(stream); - }); - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error("_transform() is not implemented"); - }; - - Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if ( - ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark - ) - this._read(rs.highWaterMark); - } - }; - - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform( - ts.writechunk, - ts.writeencoding, - ts.afterTransform - ); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - function done(stream, er, data) { - if (er) return stream.emit("error", er); + if (typeof options.flush === 'function') this._flush = options.flush; + } - if (data !== null && data !== undefined) stream.push(data); + // When the writable side finishes, then flush out anything remaining. + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er, data) { + done(stream, er, data); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - if (ws.length) - throw new Error("Calling transform done when ws.length != 0"); + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; - if (ts.transforming) - throw new Error("Calling transform done when still transforming"); +function done(stream, er, data) { + if (er) return stream.emit('error', er); - return stream.push(null); - } - }, - { "./_stream_duplex": 24, "core-util-is": 7, inherits: 15 } - ], - 28: [ - function(require, module, exports) { - (function(process) { - // A bit simpler than readable streams. - // Implement an async ._write(chunk, encoding, cb), and it'll handle all - // the drain event emission and buffering. - - "use strict"; - module.exports = Writable; - - /**/ - var processNextTick = require("process-nextick-args"); - /**/ - - /**/ - var asyncWrite = !process.browser && - ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 - ? setImmediate - : processNextTick; - /**/ - - /**/ - var Duplex; - /**/ - - Writable.WritableState = WritableState; - - /**/ - var util = require("core-util-is"); - util.inherits = require("inherits"); - /**/ - - /**/ - var internalUtil = { - deprecate: require("util-deprecate") - }; - /**/ - - /**/ - var Stream = require("./internal/streams/stream"); - /**/ - - var Buffer = require("buffer").Buffer; - /**/ - var bufferShim = require("buffer-shims"); - /**/ - - util.inherits(Writable, Stream); - - function nop() {} - - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } + if (data !== null && data !== undefined) stream.push(data); - function WritableState(options, stream) { - Duplex = Duplex || require("./_stream_duplex"); - - options = options || {}; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) - this.objectMode = - this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || "utf8"; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); - } + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - (function() { - try { - Object.defineProperty(WritableState.prototype, "buffer", { - get: internalUtil.deprecate(function() { - return this.getBuffer(); - }, "_writableState.buffer is deprecated. Use _writableState.getBuffer " + - "instead.") - }); - } catch (_) {} - })(); - - // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. - var realHasInstance; - if ( - typeof Symbol === "function" && - Symbol.hasInstance && - typeof Function.prototype[Symbol.hasInstance] === "function" - ) { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function(object) { - if (realHasInstance.call(this, object)) return true; - - return ( - object && object._writableState instanceof WritableState - ); - } - }); - } else { - realHasInstance = function(object) { - return object instanceof this; - }; - } + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - function Writable(options) { - Duplex = Duplex || require("./_stream_duplex"); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if ( - !realHasInstance.call(Writable, this) && - !(this instanceof Duplex) - ) { - return new Writable(options); - } + return stream.push(null); +} +},{"./_stream_duplex":24,"core-util-is":7,"inherits":15}],28:[function(require,module,exports){ +(function (process){ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - this._writableState = new WritableState(options, this); +'use strict'; - // legacy. - this.writable = true; +module.exports = Writable; - if (options) { - if (typeof options.write === "function") - this._write = options.write; +/**/ +var processNextTick = require('process-nextick-args'); +/**/ - if (typeof options.writev === "function") - this._writev = options.writev; - } +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ - Stream.call(this); - } +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function() { - this.emit("error", new Error("Cannot pipe, not readable")); - }; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - function writeAfterEnd(stream, cb) { - var er = new Error("write after end"); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit("error", er); - processNextTick(cb, er); - } +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ - // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - - if (chunk === null) { - er = new TypeError("May not write null values to stream"); - } else if ( - typeof chunk !== "string" && - chunk !== undefined && - !state.objectMode - ) { - er = new TypeError("Invalid non-string/buffer chunk"); - } - if (er) { - stream.emit("error", er); - processNextTick(cb, er); - valid = false; - } - return valid; - } +/**/ +var Stream = require('./internal/streams/stream'); +/**/ - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = Buffer.isBuffer(chunk); +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ - if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } +util.inherits(Writable, Stream); - if (isBuf) encoding = "buffer"; - else if (!encoding) encoding = state.defaultEncoding; +function nop() {} - if (typeof cb !== "function") cb = nop; +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - if (state.ended) writeAfterEnd(this, cb); - else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); - return ret; - }; + options = options || {}; - Writable.prototype.cork = function() { - var state = this._writableState; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - state.corked++; - }; + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - Writable.prototype.uncork = function() { - var state = this._writableState; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - if (state.corked) { - state.corked--; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - if ( - !state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.bufferedRequest - ) - clearBuffer(this, state); - } - }; - - Writable.prototype.setDefaultEncoding = function setDefaultEncoding( - encoding - ) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === "string") - encoding = encoding.toLowerCase(); - if ( - !([ - "hex", - "utf8", - "utf-8", - "ascii", - "binary", - "base64", - "ucs2", - "ucs-2", - "utf16le", - "utf-16le", - "raw" - ].indexOf((encoding + "").toLowerCase()) > -1) - ) - throw new TypeError("Unknown encoding: " + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - function decodeChunk(state, chunk, encoding) { - if ( - !state.objectMode && - state.decodeStrings !== false && - typeof chunk === "string" - ) { - chunk = bufferShim.from(chunk, encoding); - } - return chunk; - } + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) encoding = "buffer"; - } - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + this._writableState = new WritableState(options, this); - return ret; - } + // legacy. + this.writable = true; - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite); - else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + if (options) { + if (typeof options.write === 'function') this._write = options.write; - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) processNextTick(cb, er); - else cb(er); + if (typeof options.writev === 'function') this._writev = options.writev; + } - stream._writableState.errorEmitted = true; - stream.emit("error", er); - } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = Buffer.isBuffer(chunk); - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if ( - !finished && - !state.corked && - !state.bufferProcessing && - state.bufferedRequest - ) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } - } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit("drain"); - } - } + if (typeof cb !== 'function') cb = nop; - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } - - doWrite( - stream, - state, - true, - state.length, - buffer, - "", - holder.finish - ); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + return ret; +}; - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error("_write() is not implemented")); - }; +Writable.prototype.cork = function () { + var state = this._writableState; - Writable.prototype._writev = null; + state.corked++; +}; - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; +Writable.prototype.uncork = function () { + var state = this._writableState; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } + if (state.corked) { + state.corked--; - if (chunk !== null && chunk !== undefined) - this.write(chunk, encoding); + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = bufferShim.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + } + var len = state.objectMode ? 1 : chunk.length; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + state.length += len; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); - }; - - function needFinish(state) { - return ( - state.ending && - state.length === 0 && - state.bufferedRequest === null && - !state.finished && - !state.writing - ); - } + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit("prefinish"); - } - } + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit("finish"); - } else { - prefinish(stream, state); - } - } - return need; - } + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb); - else stream.once("finish", cb); - } - state.ended = true; - stream.writable = false; - } + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - this.finish = function(err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } - }.call(this, require("_process"))); - }, - { - "./_stream_duplex": 24, - "./internal/streams/stream": 30, - _process: 22, - buffer: 5, - "buffer-shims": 4, - "core-util-is": 7, - inherits: 15, - "process-nextick-args": 21, - "util-deprecate": 47 - } - ], - 29: [ - function(require, module, exports) { - "use strict"; - var Buffer = require("buffer").Buffer; - /**/ - var bufferShim = require("buffer-shims"); - /**/ - - module.exports = BufferList; - - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - BufferList.prototype.push = function(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry; - else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null; - else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function() { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function(s) { - if (this.length === 0) return ""; - var p = this.head; - var ret = "" + p.data; - while ((p = p.next)) { - ret += s + p.data; - } - return ret; - }; - - BufferList.prototype.concat = function(n) { - if (this.length === 0) return bufferShim.alloc(0); - if (this.length === 1) return this.head.data; - var ret = bufferShim.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - }, - { buffer: 5, "buffer-shims": 4 } - ], - 30: [ - function(require, module, exports) { - module.exports = require("events").EventEmitter; - }, - { events: 13 } - ], - 31: [ - function(require, module, exports) { - "use strict"; - var Buffer = require("buffer").Buffer; - var bufferShim = require("buffer-shims"); - - var isEncoding = - Buffer.isEncoding || - function(encoding) { - encoding = "" + encoding; - switch (encoding && encoding.toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - case "raw": - return true; - default: - return false; - } - }; - - function _normalizeEncoding(enc) { - if (!enc) return "utf8"; - var retried; - while (true) { - switch (enc) { - case "utf8": - case "utf-8": - return "utf8"; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return "utf16le"; - case "latin1": - case "binary": - return "latin1"; - case "base64": - case "ascii": - case "hex": - return enc; - default: - if (retried) return; // undefined - enc = ("" + enc).toLowerCase(); - retried = true; - } - } - } + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } - // Do not cache `Buffer.isEncoding` when checking encoding names as some - // modules monkey-patch it to support additional encodings - function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if ( - typeof nenc !== "string" && - (Buffer.isEncoding === isEncoding || !isEncoding(enc)) - ) - throw new Error("Unknown encoding: " + enc); - return nenc || enc; - } + if (entry === null) state.lastBufferedRequest = null; + } - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. - exports.StringDecoder = StringDecoder; - function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case "utf16le": - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case "utf8": - this.fillLast = utf8FillLast; - nb = 4; - break; - case "base64": - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = bufferShim.allocUnsafe(nb); - } + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} - StringDecoder.prototype.write = function(buf) { - if (buf.length === 0) return ""; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ""; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) - return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ""; - }; - - StringDecoder.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder.prototype.text = utf8Text; - - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder.prototype.fillLast = function(buf) { - if (this.lastNeed <= buf.length) { - buf.copy( - this.lastChar, - this.lastTotal - this.lastNeed, - 0, - this.lastNeed - ); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy( - this.lastChar, - this.lastTotal - this.lastNeed, - 0, - buf.length - ); - this.lastNeed -= buf.length; - }; - - // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a - // continuation byte. - function utf8CheckByte(byte) { - if (byte <= 0x7f) return 0; - else if (byte >> 5 === 0x06) return 2; - else if (byte >> 4 === 0x0e) return 3; - else if (byte >> 3 === 0x1e) return 4; - return -1; - } +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; - // Checks at most 3 bytes at the end of a Buffer in order to detect an - // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) - // needed to complete the UTF-8 character (if applicable) are returned. - function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0; - else self.lastNeed = nb - 3; - } - return nb; - } - return 0; - } +Writable.prototype._writev = null; - // Validates as many continuation bytes for a multi-byte UTF-8 character as - // needed or are available. If we see a non-continuation byte where we expect - // one, we "replace" the validated continuation bytes we've seen so far with - // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding - // behavior. The continuation byte check is included three times in the case - // where all of the continuation bytes for a character exist in the same buffer. - // It is also done this way as a slight performance increase instead of using a - // loop. - function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xc0) !== 0x80) { - self.lastNeed = 0; - return "\ufffd".repeat(p); - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xc0) !== 0x80) { - self.lastNeed = 1; - return "\ufffd".repeat(p + 1); - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xc0) !== 0x80) { - self.lastNeed = 2; - return "\ufffd".repeat(p + 2); - } - } - } - } +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. - function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; - } + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a - // partial character, the character's bytes are buffered until the required - // number of bytes are available. - function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString("utf8", i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString("utf8", i, end); - } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - // For UTF-8, a replacement character for each buffered byte of a (partial) - // character needs to be added to the output. - function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) - return r + "\ufffd".repeat(this.lastTotal - this.lastNeed); - return r; - } + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - // UTF-16LE typically needs two bytes per character, but even if we have an even - // number of bytes available, we need to check if we end on a leading/high - // surrogate. In that case, we need to wait for the next two bytes in order to - // decode the last character properly. - function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString("utf16le", i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xd800 && c <= 0xdbff) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString("utf16le", i, buf.length - 1); - } + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; - // For UTF-16LE we do not explicitly append special replacement characters if we - // end on a partial character, we simply let v8 handle that. - function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString("utf16le", 0, end); - } - return r; - } +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} - function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString("base64", i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString("base64", i, buf.length - n); - } +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} +}).call(this,require('_process')) +},{"./_stream_duplex":24,"./internal/streams/stream":30,"_process":22,"buffer":5,"buffer-shims":4,"core-util-is":7,"inherits":15,"process-nextick-args":21,"util-deprecate":47}],29:[function(require,module,exports){ +'use strict'; + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +module.exports = BufferList; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return bufferShim.alloc(0); + if (this.length === 1) return this.head.data; + var ret = bufferShim.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; +},{"buffer":5,"buffer-shims":4}],30:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":13}],31:[function(require,module,exports){ +'use strict'; + +var Buffer = require('buffer').Buffer; +var bufferShim = require('buffer-shims'); + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = bufferShim.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) - return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); - return r; - } +StringDecoder.prototype.end = utf8End; - // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) - function simpleWrite(buf) { - return buf.toString(this.encoding); - } +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ""; - } - }, - { buffer: 5, "buffer-shims": 4 } - ], - 32: [ - function(require, module, exports) { - module.exports = require("./readable").PassThrough; - }, - { "./readable": 33 } - ], - 33: [ - function(require, module, exports) { - exports = module.exports = require("./lib/_stream_readable.js"); - exports.Stream = exports; - exports.Readable = exports; - exports.Writable = require("./lib/_stream_writable.js"); - exports.Duplex = require("./lib/_stream_duplex.js"); - exports.Transform = require("./lib/_stream_transform.js"); - exports.PassThrough = require("./lib/_stream_passthrough.js"); - }, - { - "./lib/_stream_duplex.js": 24, - "./lib/_stream_passthrough.js": 25, - "./lib/_stream_readable.js": 26, - "./lib/_stream_transform.js": 27, - "./lib/_stream_writable.js": 28 - } - ], - 34: [ - function(require, module, exports) { - module.exports = require("./readable").Transform; - }, - { "./readable": 33 } - ], - 35: [ - function(require, module, exports) { - module.exports = require("./lib/_stream_writable.js"); - }, - { "./lib/_stream_writable.js": 28 } - ], - 36: [ - function(require, module, exports) { - (function(Buffer) { - /* +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return -1; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character for each buffered byte of a (partial) +// character needs to be added to the output. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"buffer":5,"buffer-shims":4}],32:[function(require,module,exports){ +module.exports = require('./readable').PassThrough + +},{"./readable":33}],33:[function(require,module,exports){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":24,"./lib/_stream_passthrough.js":25,"./lib/_stream_readable.js":26,"./lib/_stream_transform.js":27,"./lib/_stream_writable.js":28}],34:[function(require,module,exports){ +module.exports = require('./readable').Transform + +},{"./readable":33}],35:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); + +},{"./lib/_stream_writable.js":28}],36:[function(require,module,exports){ +(function (Buffer){ +/* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ - /** @preserve +/** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -9466,635 +8423,294 @@ Redistribution and use in source and binary forms, with or without modification, THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - // constants table - var zl = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 7, - 4, - 13, - 1, - 10, - 6, - 15, - 3, - 12, - 0, - 9, - 5, - 2, - 14, - 11, - 8, - 3, - 10, - 14, - 4, - 9, - 15, - 8, - 1, - 2, - 7, - 0, - 6, - 13, - 11, - 5, - 12, - 1, - 9, - 11, - 10, - 0, - 8, - 12, - 4, - 13, - 3, - 7, - 15, - 14, - 5, - 6, - 2, - 4, - 0, - 5, - 9, - 7, - 12, - 2, - 10, - 14, - 1, - 3, - 8, - 11, - 6, - 15, - 13 - ]; - - var zr = [ - 5, - 14, - 7, - 0, - 9, - 2, - 11, - 4, - 13, - 6, - 15, - 8, - 1, - 10, - 3, - 12, - 6, - 11, - 3, - 7, - 0, - 13, - 5, - 10, - 14, - 15, - 8, - 12, - 4, - 9, - 1, - 2, - 15, - 5, - 1, - 3, - 7, - 14, - 6, - 9, - 11, - 8, - 12, - 2, - 10, - 0, - 4, - 13, - 8, - 6, - 4, - 1, - 3, - 11, - 15, - 0, - 5, - 12, - 2, - 13, - 9, - 7, - 10, - 14, - 12, - 15, - 10, - 4, - 1, - 5, - 8, - 7, - 6, - 2, - 13, - 14, - 0, - 3, - 9, - 11 - ]; - - var sl = [ - 11, - 14, - 15, - 12, - 5, - 8, - 7, - 9, - 11, - 13, - 14, - 15, - 6, - 7, - 9, - 8, - 7, - 6, - 8, - 13, - 11, - 9, - 7, - 15, - 7, - 12, - 15, - 9, - 11, - 7, - 13, - 12, - 11, - 13, - 6, - 7, - 14, - 9, - 13, - 15, - 14, - 8, - 13, - 6, - 5, - 12, - 7, - 5, - 11, - 12, - 14, - 15, - 14, - 15, - 9, - 8, - 9, - 14, - 5, - 6, - 8, - 6, - 5, - 12, - 9, - 15, - 5, - 11, - 6, - 8, - 13, - 12, - 5, - 12, - 13, - 14, - 11, - 8, - 5, - 6 - ]; - - var sr = [ - 8, - 9, - 9, - 11, - 13, - 15, - 15, - 5, - 7, - 7, - 8, - 11, - 14, - 14, - 12, - 6, - 9, - 13, - 15, - 7, - 12, - 8, - 9, - 11, - 7, - 7, - 12, - 7, - 6, - 15, - 13, - 11, - 9, - 7, - 15, - 11, - 8, - 6, - 6, - 14, - 12, - 13, - 5, - 14, - 13, - 13, - 7, - 5, - 15, - 5, - 8, - 11, - 14, - 14, - 6, - 14, - 6, - 9, - 12, - 9, - 12, - 5, - 15, - 8, - 8, - 5, - 12, - 9, - 12, - 5, - 14, - 6, - 8, - 13, - 6, - 5, - 15, - 13, - 11, - 11 - ]; - - var hl = [ - 0x00000000, - 0x5a827999, - 0x6ed9eba1, - 0x8f1bbcdc, - 0xa953fd4e - ]; - var hr = [ - 0x50a28be6, - 0x5c4dd124, - 0x6d703ef3, - 0x7a6d76e9, - 0x00000000 - ]; - - function bytesToWords(bytes) { - var words = []; - for (var i = 0, b = 0; i < bytes.length; i++, (b += 8)) { - words[b >>> 5] |= bytes[i] << (24 - b % 32); - } - return words; - } +// constants table +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] +var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] + +function bytesToWords (bytes) { + var words = [] + for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { + words[b >>> 5] |= bytes[i] << (24 - b % 32) + } + return words +} - function wordsToBytes(words) { - var bytes = []; - for (var b = 0; b < words.length * 32; b += 8) { - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xff); - } - return bytes; - } +function wordsToBytes (words) { + var bytes = [] + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) + } + return bytes +} + +function processBlock (H, M, offset) { + // swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i + var M_offset_i = M[offset_i] + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ) + } + + // Working variables + var al, bl, cl, dl, el + var ar, br, cr, dr, er + + ar = al = H[0] + br = bl = H[1] + cr = cl = H[2] + dr = dl = H[3] + er = el = H[4] + + // computation + var t + for (i = 0; i < 80; i += 1) { + t = (al + M[offset + zl[i]]) | 0 + if (i < 16) { + t += f1(bl, cl, dl) + hl[0] + } else if (i < 32) { + t += f2(bl, cl, dl) + hl[1] + } else if (i < 48) { + t += f3(bl, cl, dl) + hl[2] + } else if (i < 64) { + t += f4(bl, cl, dl) + hl[3] + } else {// if (i<80) { + t += f5(bl, cl, dl) + hl[4] + } + t = t | 0 + t = rotl(t, sl[i]) + t = (t + el) | 0 + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = t + + t = (ar + M[offset + zr[i]]) | 0 + if (i < 16) { + t += f5(br, cr, dr) + hr[0] + } else if (i < 32) { + t += f4(br, cr, dr) + hr[1] + } else if (i < 48) { + t += f3(br, cr, dr) + hr[2] + } else if (i < 64) { + t += f2(br, cr, dr) + hr[3] + } else {// if (i<80) { + t += f1(br, cr, dr) + hr[4] + } + + t = t | 0 + t = rotl(t, sr[i]) + t = (t + er) | 0 + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = t + } - function processBlock(H, M, offset) { - // swap endian - for (var i = 0; i < 16; i++) { - var offset_i = offset + i; - var M_offset_i = M[offset_i]; + // intermediate hash value + t = (H[1] + cl + dr) | 0 + H[1] = (H[2] + dl + er) | 0 + H[2] = (H[3] + el + ar) | 0 + H[3] = (H[4] + al + br) | 0 + H[4] = (H[0] + bl + cr) | 0 + H[0] = t +} - // Swap - M[offset_i] = - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00); - } +function f1 (x, y, z) { + return ((x) ^ (y) ^ (z)) +} - // Working variables - var al, bl, cl, dl, el; - var ar, br, cr, dr, er; - - ar = al = H[0]; - br = bl = H[1]; - cr = cl = H[2]; - dr = dl = H[3]; - er = el = H[4]; - - // computation - var t; - for (i = 0; i < 80; i += 1) { - t = (al + M[offset + zl[i]]) | 0; - if (i < 16) { - t += f1(bl, cl, dl) + hl[0]; - } else if (i < 32) { - t += f2(bl, cl, dl) + hl[1]; - } else if (i < 48) { - t += f3(bl, cl, dl) + hl[2]; - } else if (i < 64) { - t += f4(bl, cl, dl) + hl[3]; - } else { - // if (i<80) { - t += f5(bl, cl, dl) + hl[4]; - } - t = t | 0; - t = rotl(t, sl[i]); - t = (t + el) | 0; - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = t; - - t = (ar + M[offset + zr[i]]) | 0; - if (i < 16) { - t += f5(br, cr, dr) + hr[0]; - } else if (i < 32) { - t += f4(br, cr, dr) + hr[1]; - } else if (i < 48) { - t += f3(br, cr, dr) + hr[2]; - } else if (i < 64) { - t += f2(br, cr, dr) + hr[3]; - } else { - // if (i<80) { - t += f1(br, cr, dr) + hr[4]; - } - - t = t | 0; - t = rotl(t, sr[i]); - t = (t + er) | 0; - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = t; - } +function f2 (x, y, z) { + return (((x) & (y)) | ((~x) & (z))) +} - // intermediate hash value - t = (H[1] + cl + dr) | 0; - H[1] = (H[2] + dl + er) | 0; - H[2] = (H[3] + el + ar) | 0; - H[3] = (H[4] + al + br) | 0; - H[4] = (H[0] + bl + cr) | 0; - H[0] = t; - } +function f3 (x, y, z) { + return (((x) | (~(y))) ^ (z)) +} - function f1(x, y, z) { - return x ^ y ^ z; - } +function f4 (x, y, z) { + return (((x) & (z)) | ((y) & (~(z)))) +} - function f2(x, y, z) { - return (x & y) | (~x & z); - } +function f5 (x, y, z) { + return ((x) ^ ((y) | (~(z)))) +} - function f3(x, y, z) { - return (x | ~y) ^ z; - } +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} - function f4(x, y, z) { - return (x & z) | (y & ~z); - } +function ripemd160 (message) { + var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] - function f5(x, y, z) { - return x ^ (y | ~z); - } + if (typeof message === 'string') { + message = new Buffer(message, 'utf8') + } - function rotl(x, n) { - return (x << n) | (x >>> (32 - n)); - } + var m = bytesToWords(message) - function ripemd160(message) { - var H = [ - 0x67452301, - 0xefcdab89, - 0x98badcfe, - 0x10325476, - 0xc3d2e1f0 - ]; - - if (typeof message === "string") { - message = new Buffer(message, "utf8"); - } + var nBitsLeft = message.length * 8 + var nBitsTotal = message.length * 8 - var m = bytesToWords(message); + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) + m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ) - var nBitsLeft = message.length * 8; - var nBitsTotal = message.length * 8; + for (var i = 0; i < m.length; i += 16) { + processBlock(H, m, i) + } - // Add padding - m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - m[((nBitsLeft + 64) >>> 9 << 4) + 14] = - (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | - (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00); + // swap endian + for (i = 0; i < 5; i++) { + // shortcut + var H_i = H[i] - for (var i = 0; i < m.length; i += 16) { - processBlock(H, m, i); - } + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00) + } - // swap endian - for (i = 0; i < 5; i++) { - // shortcut - var H_i = H[i]; + var digestbytes = wordsToBytes(H) + return new Buffer(digestbytes) +} + +module.exports = ripemd160 + +}).call(this,require("buffer").Buffer) +},{"buffer":5}],37:[function(require,module,exports){ +(function (Buffer){ +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = new Buffer(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + this._s = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = new Buffer(data, enc) + } - // Swap - H[i] = - (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } + var l = this._len += data.length + var s = this._s || 0 + var f = 0 + var buffer = this._block - var digestbytes = wordsToBytes(H); - return new Buffer(digestbytes); - } + while (s < l) { + var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) + var ch = (t - f) - module.exports = ripemd160; - }.call(this, require("buffer").Buffer)); - }, - { buffer: 5 } - ], - 37: [ - function(require, module, exports) { - (function(Buffer) { - // prototype class for hash functions - function Hash(blockSize, finalSize) { - this._block = new Buffer(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - this._s = 0; - } + for (var i = 0; i < ch; i++) { + buffer[(s % this._blockSize) + i] = data[i + f] + } - Hash.prototype.update = function(data, enc) { - if (typeof data === "string") { - enc = enc || "utf8"; - data = new Buffer(data, enc); - } + s += ch + f += ch - var l = (this._len += data.length); - var s = this._s || 0; - var f = 0; - var buffer = this._block; + if ((s % this._blockSize) === 0) { + this._update(buffer) + } + } + this._s = s - while (s < l) { - var t = Math.min( - data.length, - f + this._blockSize - s % this._blockSize - ); - var ch = t - f; + return this +} - for (var i = 0; i < ch; i++) { - buffer[s % this._blockSize + i] = data[i + f]; - } +Hash.prototype.digest = function (enc) { + // Suppose the length of the message M, in bits, is l + var l = this._len * 8 - s += ch; - f += ch; + // Append the bit 1 to the end of the message + this._block[this._len % this._blockSize] = 0x80 - if (s % this._blockSize === 0) { - this._update(buffer); - } - } - this._s = s; + // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize + this._block.fill(0, this._len % this._blockSize + 1) - return this; - }; + if (l % (this._blockSize * 8) >= this._finalSize * 8) { + this._update(this._block) + this._block.fill(0) + } - Hash.prototype.digest = function(enc) { - // Suppose the length of the message M, in bits, is l - var l = this._len * 8; + // to this append the block which is equal to the number l written in binary + // TODO: handle case where l is > Math.pow(2, 29) + this._block.writeInt32BE(l, this._blockSize - 4) - // Append the bit 1 to the end of the message - this._block[this._len % this._blockSize] = 0x80; + var hash = this._update(this._block) || this._hash() - // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize - this._block.fill(0, this._len % this._blockSize + 1); + return enc ? hash.toString(enc) : hash +} - if (l % (this._blockSize * 8) >= this._finalSize * 8) { - this._update(this._block); - this._block.fill(0); - } +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} - // to this append the block which is equal to the number l written in binary - // TODO: handle case where l is > Math.pow(2, 29) - this._block.writeInt32BE(l, this._blockSize - 4); +module.exports = Hash - var hash = this._update(this._block) || this._hash(); +}).call(this,require("buffer").Buffer) +},{"buffer":5}],38:[function(require,module,exports){ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() - return enc ? hash.toString(enc) : hash; - }; + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - Hash.prototype._update = function() { - throw new Error("_update must be implemented by subclass"); - }; + return new Algorithm() +} - module.exports = Hash; - }.call(this, require("buffer").Buffer)); - }, - { buffer: 5 } - ], - 38: [ - function(require, module, exports) { - var exports = (module.exports = function SHA(algorithm) { - algorithm = algorithm.toLowerCase(); - - var Algorithm = exports[algorithm]; - if (!Algorithm) - throw new Error( - algorithm + " is not supported (we accept pull requests)" - ); - - return new Algorithm(); - }); +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') - exports.sha = require("./sha"); - exports.sha1 = require("./sha1"); - exports.sha224 = require("./sha224"); - exports.sha256 = require("./sha256"); - exports.sha384 = require("./sha384"); - exports.sha512 = require("./sha512"); - }, - { - "./sha": 39, - "./sha1": 40, - "./sha224": 41, - "./sha256": 42, - "./sha384": 43, - "./sha512": 44 - } - ], - 39: [ - function(require, module, exports) { - (function(Buffer) { - /* +},{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(require,module,exports){ +(function (Buffer){ +/* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined * in FIPS PUB 180-1 * This source code is derived from sha1.js of the same repository. @@ -10102,99 +8718,96 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * operation was added. */ - var inherits = require("inherits"); - var Hash = require("./hash"); +var inherits = require('inherits') +var Hash = require('./hash') - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]; +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] - var W = new Array(80); +var W = new Array(80) - function Sha() { - this.init(); - this._w = W; +function Sha () { + this.init() + this._w = W - Hash.call(this, 64, 56); - } + Hash.call(this, 64, 56) +} - inherits(Sha, Hash); +inherits(Sha, Hash) - Sha.prototype.init = function() { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 - return this; - }; + return this +} - function rotl5(num) { - return (num << 5) | (num >>> 27); - } +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} - function rotl30(num) { - return (num << 30) | (num >>> 2); - } +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} - function ft(s, b, c, d) { - if (s === 0) return (b & c) | (~b & d); - if (s === 2) return (b & c) | (b & d) | (c & d); - return b ^ c ^ d; - } +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} - Sha.prototype._update = function(M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) - W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) - W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0; - - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } +Sha.prototype._update = function (M) { + var W = this._w - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 - Sha.prototype._hash = function() { - var H = new Buffer(20); + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - return H; - }; + e = d + d = c + c = rotl30(b) + b = a + a = t + } - module.exports = Sha; - }.call(this, require("buffer").Buffer)); - }, - { "./hash": 37, buffer: 5, inherits: 15 } - ], - 40: [ - function(require, module, exports) { - (function(Buffer) { - /* + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":5,"inherits":15}],40:[function(require,module,exports){ +(function (Buffer){ +/* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. @@ -10203,162 +8816,100 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * See http://pajhome.org.uk/crypt/md5 for details. */ - var inherits = require("inherits"); - var Hash = require("./hash"); - - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]; +var inherits = require('inherits') +var Hash = require('./hash') - var W = new Array(80); +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] - function Sha1() { - this.init(); - this._w = W; +var W = new Array(80) - Hash.call(this, 64, 56); - } +function Sha1 () { + this.init() + this._w = W - inherits(Sha1, Hash); + Hash.call(this, 64, 56) +} - Sha1.prototype.init = function() { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; +inherits(Sha1, Hash) - return this; - }; +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 - function rotl1(num) { - return (num << 1) | (num >>> 31); - } + return this +} - function rotl5(num) { - return (num << 5) | (num >>> 27); - } +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} - function rotl30(num) { - return (num << 30) | (num >>> 2); - } +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} - function ft(s, b, c, d) { - if (s === 0) return (b & c) | (~b & d); - if (s === 2) return (b & c) | (b & d) | (c & d); - return b ^ c ^ d; - } +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} - Sha1.prototype._update = function(M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) - W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) - W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0; - - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; +Sha1.prototype._update = function (M) { + var W = this._w - Sha1.prototype._hash = function() { - var H = new Buffer(20); + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) - return H; - }; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - module.exports = Sha1; - }.call(this, require("buffer").Buffer)); - }, - { "./hash": 37, buffer: 5, inherits: 15 } - ], - 41: [ - function(require, module, exports) { - (function(Buffer) { - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + e = d + d = c + c = rotl30(b) + b = a + a = t + } - var inherits = require("inherits"); - var Sha256 = require("./sha256"); - var Hash = require("./hash"); + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} - var W = new Array(64); +Sha1.prototype._hash = function () { + var H = new Buffer(20) - function Sha224() { - this.init(); + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) - this._w = W; // new Array(64) + return H +} - Hash.call(this, 64, 56); - } +module.exports = Sha1 - inherits(Sha224, Sha256); - - Sha224.prototype.init = function() { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; - - return this; - }; - - Sha224.prototype._hash = function() { - var H = new Buffer(28); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - - return H; - }; - - module.exports = Sha224; - }.call(this, require("buffer").Buffer)); - }, - { "./hash": 37, "./sha256": 42, buffer: 5, inherits: 15 } - ], - 42: [ - function(require, module, exports) { - (function(Buffer) { - /** +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":5,"inherits":15}],41:[function(require,module,exports){ +(function (Buffer){ +/** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. @@ -10366,1065 +8917,875 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * */ - var inherits = require("inherits"); - var Hash = require("./hash"); - - var K = [ - 0x428a2f98, - 0x71374491, - 0xb5c0fbcf, - 0xe9b5dba5, - 0x3956c25b, - 0x59f111f1, - 0x923f82a4, - 0xab1c5ed5, - 0xd807aa98, - 0x12835b01, - 0x243185be, - 0x550c7dc3, - 0x72be5d74, - 0x80deb1fe, - 0x9bdc06a7, - 0xc19bf174, - 0xe49b69c1, - 0xefbe4786, - 0x0fc19dc6, - 0x240ca1cc, - 0x2de92c6f, - 0x4a7484aa, - 0x5cb0a9dc, - 0x76f988da, - 0x983e5152, - 0xa831c66d, - 0xb00327c8, - 0xbf597fc7, - 0xc6e00bf3, - 0xd5a79147, - 0x06ca6351, - 0x14292967, - 0x27b70a85, - 0x2e1b2138, - 0x4d2c6dfc, - 0x53380d13, - 0x650a7354, - 0x766a0abb, - 0x81c2c92e, - 0x92722c85, - 0xa2bfe8a1, - 0xa81a664b, - 0xc24b8b70, - 0xc76c51a3, - 0xd192e819, - 0xd6990624, - 0xf40e3585, - 0x106aa070, - 0x19a4c116, - 0x1e376c08, - 0x2748774c, - 0x34b0bcb5, - 0x391c0cb3, - 0x4ed8aa4a, - 0x5b9cca4f, - 0x682e6ff3, - 0x748f82ee, - 0x78a5636f, - 0x84c87814, - 0x8cc70208, - 0x90befffa, - 0xa4506ceb, - 0xbef9a3f7, - 0xc67178f2 - ]; - - var W = new Array(64); - - function Sha256() { - this.init(); - - this._w = W; // new Array(64) - - Hash.call(this, 64, 56); - } - - inherits(Sha256, Hash); - - Sha256.prototype.init = function() { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; - - return this; - }; +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') - function ch(x, y, z) { - return z ^ (x & (y ^ z)); - } - - function maj(x, y, z) { - return (x & y) | (z & (x | y)); - } - - function sigma0(x) { - return ( - ((x >>> 2) | (x << 30)) ^ - ((x >>> 13) | (x << 19)) ^ - ((x >>> 22) | (x << 10)) - ); - } - - function sigma1(x) { - return ( - ((x >>> 6) | (x << 26)) ^ - ((x >>> 11) | (x << 21)) ^ - ((x >>> 25) | (x << 7)) - ); - } - - function gamma0(x) { - return ( - ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3) - ); - } - - function gamma1(x) { - return ( - ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10) - ); - } - - Sha256.prototype._update = function(M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) - W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) - W[i] = - (gamma1(W[i - 2]) + - W[i - 7] + - gamma0(W[i - 15]) + - W[i - 16]) | - 0; - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0; - var T2 = (sigma0(a) + maj(a, b, c)) | 0; - - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256.prototype._hash = function() { - var H = new Buffer(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); - - return H; - }; - - module.exports = Sha256; - }.call(this, require("buffer").Buffer)); - }, - { "./hash": 37, buffer: 5, inherits: 15 } - ], - 43: [ - function(require, module, exports) { - (function(Buffer) { - var inherits = require("inherits"); - var SHA512 = require("./sha512"); - var Hash = require("./hash"); - - var W = new Array(160); - - function Sha384() { - this.init(); - this._w = W; - - Hash.call(this, 128, 112); - } +var W = new Array(64) - inherits(Sha384, SHA512); - - Sha384.prototype.init = function() { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; - - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - - return this; - }; - - Sha384.prototype._hash = function() { - var H = new Buffer(48); - - function writeInt64BE(h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H; - }; - - module.exports = Sha384; - }.call(this, require("buffer").Buffer)); - }, - { "./hash": 37, "./sha512": 44, buffer: 5, inherits: 15 } - ], - 44: [ - function(require, module, exports) { - (function(Buffer) { - var inherits = require("inherits"); - var Hash = require("./hash"); - - var K = [ - 0x428a2f98, - 0xd728ae22, - 0x71374491, - 0x23ef65cd, - 0xb5c0fbcf, - 0xec4d3b2f, - 0xe9b5dba5, - 0x8189dbbc, - 0x3956c25b, - 0xf348b538, - 0x59f111f1, - 0xb605d019, - 0x923f82a4, - 0xaf194f9b, - 0xab1c5ed5, - 0xda6d8118, - 0xd807aa98, - 0xa3030242, - 0x12835b01, - 0x45706fbe, - 0x243185be, - 0x4ee4b28c, - 0x550c7dc3, - 0xd5ffb4e2, - 0x72be5d74, - 0xf27b896f, - 0x80deb1fe, - 0x3b1696b1, - 0x9bdc06a7, - 0x25c71235, - 0xc19bf174, - 0xcf692694, - 0xe49b69c1, - 0x9ef14ad2, - 0xefbe4786, - 0x384f25e3, - 0x0fc19dc6, - 0x8b8cd5b5, - 0x240ca1cc, - 0x77ac9c65, - 0x2de92c6f, - 0x592b0275, - 0x4a7484aa, - 0x6ea6e483, - 0x5cb0a9dc, - 0xbd41fbd4, - 0x76f988da, - 0x831153b5, - 0x983e5152, - 0xee66dfab, - 0xa831c66d, - 0x2db43210, - 0xb00327c8, - 0x98fb213f, - 0xbf597fc7, - 0xbeef0ee4, - 0xc6e00bf3, - 0x3da88fc2, - 0xd5a79147, - 0x930aa725, - 0x06ca6351, - 0xe003826f, - 0x14292967, - 0x0a0e6e70, - 0x27b70a85, - 0x46d22ffc, - 0x2e1b2138, - 0x5c26c926, - 0x4d2c6dfc, - 0x5ac42aed, - 0x53380d13, - 0x9d95b3df, - 0x650a7354, - 0x8baf63de, - 0x766a0abb, - 0x3c77b2a8, - 0x81c2c92e, - 0x47edaee6, - 0x92722c85, - 0x1482353b, - 0xa2bfe8a1, - 0x4cf10364, - 0xa81a664b, - 0xbc423001, - 0xc24b8b70, - 0xd0f89791, - 0xc76c51a3, - 0x0654be30, - 0xd192e819, - 0xd6ef5218, - 0xd6990624, - 0x5565a910, - 0xf40e3585, - 0x5771202a, - 0x106aa070, - 0x32bbd1b8, - 0x19a4c116, - 0xb8d2d0c8, - 0x1e376c08, - 0x5141ab53, - 0x2748774c, - 0xdf8eeb99, - 0x34b0bcb5, - 0xe19b48a8, - 0x391c0cb3, - 0xc5c95a63, - 0x4ed8aa4a, - 0xe3418acb, - 0x5b9cca4f, - 0x7763e373, - 0x682e6ff3, - 0xd6b2b8a3, - 0x748f82ee, - 0x5defb2fc, - 0x78a5636f, - 0x43172f60, - 0x84c87814, - 0xa1f0ab72, - 0x8cc70208, - 0x1a6439ec, - 0x90befffa, - 0x23631e28, - 0xa4506ceb, - 0xde82bde9, - 0xbef9a3f7, - 0xb2c67915, - 0xc67178f2, - 0xe372532b, - 0xca273ece, - 0xea26619c, - 0xd186b8c7, - 0x21c0c207, - 0xeada7dd6, - 0xcde0eb1e, - 0xf57d4f7f, - 0xee6ed178, - 0x06f067aa, - 0x72176fba, - 0x0a637dc5, - 0xa2c898a6, - 0x113f9804, - 0xbef90dae, - 0x1b710b35, - 0x131c471b, - 0x28db77f5, - 0x23047d84, - 0x32caab7b, - 0x40c72493, - 0x3c9ebe0a, - 0x15c9bebc, - 0x431d67c4, - 0x9c100d4c, - 0x4cc5d4be, - 0xcb3e42b6, - 0x597f299c, - 0xfc657e2a, - 0x5fcb6fab, - 0x3ad6faec, - 0x6c44198c, - 0x4a475817 - ]; - - var W = new Array(160); - - function Sha512() { - this.init(); - this._w = W; - - Hash.call(this, 128, 112); - } - - inherits(Sha512, Hash); - - Sha512.prototype.init = function() { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; - - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; - - return this; - }; - - function Ch(x, y, z) { - return z ^ (x & (y ^ z)); - } +function Sha224 () { + this.init() - function maj(x, y, z) { - return (x & y) | (z & (x | y)); - } - - function sigma0(x, xl) { - return ( - ((x >>> 28) | (xl << 4)) ^ - ((xl >>> 2) | (x << 30)) ^ - ((xl >>> 7) | (x << 25)) - ); - } - - function sigma1(x, xl) { - return ( - ((x >>> 14) | (xl << 18)) ^ - ((x >>> 18) | (xl << 14)) ^ - ((xl >>> 9) | (x << 23)) - ); - } + this._w = W // new Array(64) - function Gamma0(x, xl) { - return ( - ((x >>> 1) | (xl << 31)) ^ ((x >>> 8) | (xl << 24)) ^ (x >>> 7) - ); - } + Hash.call(this, 64, 56) +} - function Gamma0l(x, xl) { - return ( - ((x >>> 1) | (xl << 31)) ^ - ((x >>> 8) | (xl << 24)) ^ - ((x >>> 7) | (xl << 25)) - ); - } +inherits(Sha224, Sha256) - function Gamma1(x, xl) { - return ( - ((x >>> 19) | (xl << 13)) ^ ((xl >>> 29) | (x << 3)) ^ (x >>> 6) - ); - } +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 - function Gamma1l(x, xl) { - return ( - ((x >>> 19) | (xl << 13)) ^ - ((xl >>> 29) | (x << 3)) ^ - ((x >>> 6) | (xl << 26)) - ); - } + return this +} - function getCarry(a, b) { - return a >>> 0 < b >>> 0 ? 1 : 0; - } +Sha224.prototype._hash = function () { + var H = new Buffer(28) - Sha512.prototype._update = function(M) { - var W = this._w; - - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; - - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; - - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; - - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - - W[i] = Wih; - W[i + 1] = Wil; - } + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); - - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j]; - var Kil = K[j + 1]; - - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); - - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } + return H +} - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; - - Sha512.prototype._hash = function() { - var H = new Buffer(64); - - function writeInt64BE(h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } +module.exports = Sha224 - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); +}).call(this,require("buffer").Buffer) +},{"./hash":37,"./sha256":42,"buffer":5,"inherits":15}],42:[function(require,module,exports){ +(function (Buffer){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - return H; - }; +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } - module.exports = Sha512; - }.call(this, require("buffer").Buffer)); - }, - { "./hash": 37, buffer: 5, inherits: 15 } - ], - 45: [ - function(require, module, exports) { - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - module.exports = Stream; - - var EE = require("events").EventEmitter; - var inherits = require("inherits"); - - inherits(Stream, EE); - Stream.Readable = require("readable-stream/readable.js"); - Stream.Writable = require("readable-stream/writable.js"); - Stream.Duplex = require("readable-stream/duplex.js"); - Stream.Transform = require("readable-stream/transform.js"); - Stream.PassThrough = require("readable-stream/passthrough.js"); - - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; - - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. - - function Stream() { - EE.call(this); - } + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = new Buffer(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":5,"inherits":15}],43:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = new Buffer(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } - Stream.prototype.pipe = function(dest, options) { - var source = this; + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"./sha512":44,"buffer":5,"inherits":15}],44:[function(require,module,exports){ +(function (Buffer){ +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } - source.on("data", ondata); + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = new Buffer(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + +}).call(this,require("buffer").Buffer) +},{"./hash":37,"buffer":5,"inherits":15}],45:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } - dest.on("drain", ondrain); + source.on('data', ondata); - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on("end", onend); - source.on("close", onclose); - } + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + dest.on('drain', ondrain); - dest.end(); - } + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - if (typeof dest.destroy === "function") dest.destroy(); - } + dest.end(); + } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, "error") === 0) { - throw er; // Unhandled stream error in pipe. - } - } - source.on("error", onerror); - dest.on("error", onerror); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - // remove all the event listeners that were added. - function cleanup() { - source.removeListener("data", ondata); - dest.removeListener("drain", ondrain); + if (typeof dest.destroy === 'function') dest.destroy(); + } - source.removeListener("end", onend); - source.removeListener("close", onclose); + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } - source.removeListener("error", onerror); - dest.removeListener("error", onerror); + source.on('error', onerror); + dest.on('error', onerror); - source.removeListener("end", cleanup); - source.removeListener("close", cleanup); + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - dest.removeListener("close", cleanup); - } + source.removeListener('end', onend); + source.removeListener('close', onclose); - source.on("end", cleanup); - source.on("close", cleanup); + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - dest.on("close", cleanup); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - dest.emit("pipe", source); + dest.removeListener('close', cleanup); + } - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; - }, - { - events: 13, - inherits: 15, - "readable-stream/duplex.js": 23, - "readable-stream/passthrough.js": 32, - "readable-stream/readable.js": 33, - "readable-stream/transform.js": 34, - "readable-stream/writable.js": 35 - } - ], - 46: [ - function(require, module, exports) { - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var Buffer = require("buffer").Buffer; - - var isBufferEncoding = - Buffer.isEncoding || - function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - case "raw": - return true; - default: - return false; - } - }; + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":13,"inherits":15,"readable-stream/duplex.js":23,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],46:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error("Unknown encoding: " + encoding); - } - } + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder = (exports.StringDecoder = function(encoding) { - this.encoding = (encoding || "utf8") - .toLowerCase() - .replace(/[-_]/, ""); - assertEncoding(encoding); - switch (this.encoding) { - case "utf8": - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case "ucs2": - case "utf16le": - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case "base64": - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }); + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder.prototype.write = function(buffer) { - var charStr = ""; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = buffer.length >= - this.charLength - this.charReceived - ? this.charLength - this.charReceived - : buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ""; - } + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } - // get the character that was split - charStr = this.charBuffer - .slice(0, this.charLength) - .toString(this.encoding); + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xd800 && charCode <= 0xdbff) { - this.charLength += this.surrogateSize; - charStr = ""; - continue; - } - this.charReceived = this.charLength = 0; + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy( - this.charBuffer, - 0, - buffer.length - this.charReceived, - end - ); - end -= this.charReceived; - } + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xd800 && charCode <= 0xdbff) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - // or just emit the charStr - return charStr; - }; - - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = buffer.length >= 3 ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0e) { - this.charLength = 3; - break; - } + return res; +}; - // 11110XXX - if (i <= 3 && c >> 3 == 0x1e) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; - - StringDecoder.prototype.end = function(buffer) { - var res = ""; - if (buffer && buffer.length) res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} - return res; - }; +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } +},{"buffer":5}],47:[function(require,module,exports){ +(function (global){ - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } - }, - { buffer: 5 } - ], - 47: [ - function(require, module, exports) { - (function(global) { - /** +/** * Module exports. */ - module.exports = deprecate; +module.exports = deprecate; - /** +/** * Mark that a method should not be used. * Returns a modified function which warns once by default. * @@ -11442,30 +9803,30 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * @api public */ - function deprecate(fn, msg) { - if (config("noDeprecation")) { - return fn; - } +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } - var warned = false; - function deprecated() { - if (!warned) { - if (config("throwDeprecation")) { - throw new Error(msg); - } else if (config("traceDeprecation")) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - return deprecated; - } + return deprecated; +} - /** +/** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name @@ -11473,451 +9834,379 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * @api private */ - function config(name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === "true"; - } - }.call( - this, - typeof global !== "undefined" - ? global - : typeof self !== "undefined" - ? self - : typeof window !== "undefined" ? window : {} - )); - }, - {} - ], - 48: [ - function(require, module, exports) { - var v1 = require("./v1"); - var v2 = require("./v2"); - var createHMAC = require("create-hmac"); - var Buffer = require("buffer/").Buffer; - var Promise = require("es6-promise").Promise; - - module.exports = { - generatePassword: function(site, login, masterPassword, options) { - if (typeof options !== "undefined" && options.version === 1) { - return v1.generatePassword( - site, - login, - masterPassword, - options - ); - } - return v2.generatePassword(site, login, masterPassword, options); - }, - createFingerprint: function(str) { - return new Promise(function(resolve) { - resolve(createHMAC("sha256", new Buffer(str)).digest("hex")); - }); - } - }; - }, +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],48:[function(require,module,exports){ +var v1 = require("./v1"); +var v2 = require("./v2"); +var createHMAC = require("create-hmac"); +var Buffer = require("buffer/").Buffer; +var Promise = require("es6-promise").Promise; + +module.exports = { + generatePassword: function(site, login, masterPassword, options) { + if (typeof options !== "undefined" && options.version === 1) { + return v1.generatePassword(site, login, masterPassword, options); + } + return v2.generatePassword(site, login, masterPassword, options); + }, + createFingerprint: function(str) { + return new Promise(function(resolve) { + resolve(createHMAC("sha256", new Buffer(str)).digest("hex")); + }); + } +}; + +},{"./v1":50,"./v2":51,"buffer/":5,"create-hmac":11,"es6-promise":12}],49:[function(require,module,exports){ +var pbkdf2 = require("pbkdf2"); +var Buffer = require("buffer/").Buffer; +var Promise = require("es6-promise").Promise; + +function shouldUseNative() { + return !!(typeof window !== "undefined" && + window.crypto && + window.crypto.subtle); +} + +function pbkdf2WebCrypto(password, salt, iterations, keylen, digest) { + var algorithms = { + sha1: "SHA-1", + "sha-1": "SHA-1", + sha256: "SHA-256", + "sha-256": "SHA-256", + sha512: "SHA-512", + "sha-512": "SHA-512" + }; + return window.crypto.subtle + .importKey("raw", new Buffer(password), "PBKDF2", false, ["deriveKey"]) + .then(function(key) { + var algo = { + name: "PBKDF2", + salt: new Buffer(salt), + iterations: iterations, + hash: algorithms[digest.toLowerCase()] + }; + return window.crypto.subtle.deriveKey( + algo, + key, { - "./v1": 50, - "./v2": 51, - "buffer/": 5, - "create-hmac": 11, - "es6-promise": 12 - } - ], - 49: [ - function(require, module, exports) { - var pbkdf2 = require("pbkdf2"); - var Buffer = require("buffer/").Buffer; - var Promise = require("es6-promise").Promise; - - function shouldUseNative() { - return !!(typeof window !== "undefined" && - window.crypto && - window.crypto.subtle); - } - - function pbkdf2WebCrypto(password, salt, iterations, keylen, digest) { - var algorithms = { - sha1: "SHA-1", - "sha-1": "SHA-1", - sha256: "SHA-256", - "sha-256": "SHA-256", - sha512: "SHA-512", - "sha-512": "SHA-512" - }; - return window.crypto.subtle - .importKey("raw", new Buffer(password), "PBKDF2", false, [ - "deriveKey" - ]) - .then(function(key) { - var algo = { - name: "PBKDF2", - salt: new Buffer(salt), - iterations: iterations, - hash: algorithms[digest.toLowerCase()] - }; - return window.crypto.subtle.deriveKey( - algo, - key, - { - name: "AES-CTR", - length: keylen * 8 - }, - true, - ["encrypt", "decrypt"] - ); - }) - .then(function(derivedKey) { - return window.crypto.subtle - .exportKey("raw", derivedKey) - .then(function(keyArray) { - return new Buffer(keyArray).toString("hex"); - }); - }); - } - - function pbkdf2Browserified( - password, - salt, - iterations, - keylen, - digest - ) { - return new Promise(function(resolve, reject) { - pbkdf2.pbkdf2( - password, - salt, - iterations, - keylen, - digest, - function(error, key) { - if (error) { - reject("error in pbkdf2"); - } else { - resolve(key.toString("hex")); - } - } - ); - }); - } - - module.exports = shouldUseNative() - ? pbkdf2WebCrypto - : pbkdf2Browserified; - }, - { "buffer/": 5, "es6-promise": 12, pbkdf2: 19 } - ], - 50: [ - function(require, module, exports) { - (function(Buffer) { - var pbkdf2 = require("./pbkdf2"); - var assign = require("lodash.assign"); - var createHMAC = require("create-hmac"); - - module.exports = { - generatePassword: generatePassword, - _renderPassword: renderPassword, - _createHmac: createHmac, - _deriveEncryptedLogin: deriveEncryptedLogin, - _getPasswordTemplate: getPasswordTemplate, - _prettyPrint: prettyPrint, - _string2charCodes: string2charCodes, - _getCharType: getCharType, - _getPasswordChar: getPasswordChar - }; - - var defaultOptions = { - version: 1, - lowercase: true, - numbers: true, - uppercase: true, - symbols: true, - keylen: 32, - digest: "sha256", - length: 12, - counter: 1, - iterations: 8192 - }; - - function generatePassword(site, login, masterPassword, options) { - var _options = assign({}, defaultOptions, options); - return pbkdf2( - masterPassword, - login, - _options.iterations, - _options.keylen, - "sha256" - ).then(function(encryptedLogin) { - return renderPassword( - encryptedLogin, - site, - _options - ).then(function(generatedPassword) { - return generatedPassword; - }); - }); - } - - function renderPassword(encryptedLogin, site, passwordOptions) { - return deriveEncryptedLogin( - encryptedLogin, - site, - passwordOptions - ).then(function(derivedEncryptedLogin) { - var template = - passwordOptions.template || - getPasswordTemplate(passwordOptions); - return prettyPrint(derivedEncryptedLogin, template); - }); - } - - function createHmac(encryptedLogin, salt) { - return new Promise(function(resolve) { - resolve( - createHMAC("sha256", new Buffer(encryptedLogin)) - .update(salt) - .digest("hex") - ); - }); - } - - function deriveEncryptedLogin(encryptedLogin, site, options) { - var _options = options !== undefined ? options : {}; - var length = _options.length || 12; - var counter = _options.counter || 1; - - var salt = site + counter.toString(); - return createHmac(encryptedLogin, salt).then(function( - derivedHash - ) { - return derivedHash.substring(0, length); - }); - } - - function getPasswordTemplate(passwordTypes) { - var templates = { - lowercase: "vc", - uppercase: "VC", - numbers: "n", - symbols: "s" - }; - var returnedTemplate = ""; - Object.keys(templates).forEach(function(template) { - if ( - passwordTypes.hasOwnProperty(template) && - passwordTypes[template] - ) { - returnedTemplate += templates[template]; - } - }); - return returnedTemplate; - } - - function prettyPrint(hash, template) { - var password = ""; - - string2charCodes(hash).forEach(function(charCode, index) { - var charType = getCharType(template, index); - password += getPasswordChar(charType, charCode); - }); - return password; - } - - function string2charCodes(text) { - var charCodes = []; - for (var i = 0; i < text.length; i++) { - charCodes.push(text.charCodeAt(i)); - } - return charCodes; - } - - function getCharType(template, index) { - return template[index % template.length]; - } - - function getPasswordChar(charType, index) { - var passwordsChars = { - V: "AEIOUY", - C: "BCDFGHJKLMNPQRSTVWXZ", - v: "aeiouy", - c: "bcdfghjklmnpqrstvwxz", - A: "AEIOUYBCDFGHJKLMNPQRSTVWXZ", - a: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz", - n: "0123456789", - s: "@&%?,=[]_:-+*$#!'^~;()/.", - x: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!'^~;()/." - }; - var passwordChar = passwordsChars[charType]; - return passwordChar[index % passwordChar.length]; - } - }.call(this, require("buffer").Buffer)); + name: "AES-CTR", + length: keylen * 8 }, - { "./pbkdf2": 49, buffer: 5, "create-hmac": 11, "lodash.assign": 18 } - ], - 51: [ - function(require, module, exports) { - var pbkdf2 = require("./pbkdf2"); - var bigInt = require("big-integer"); - var assign = require("lodash.assign"); - - module.exports = { - generatePassword: generatePassword, - _calcEntropy: calcEntropy, - _consumeEntropy: consumeEntropy, - _getSetOfCharacters: getSetOfCharacters, - _getConfiguredRules: getConfiguredRules, - _insertStringPseudoRandomly: insertStringPseudoRandomly, - _getOneCharPerRule: getOneCharPerRule, - _renderPassword: renderPassword - }; - - var defaultOptions = { - version: 2, - lowercase: true, - numbers: true, - uppercase: true, - symbols: true, - keylen: 32, - digest: "sha256", - length: 16, - counter: 1, - iterations: 100000 - }; - - function generatePassword(site, login, masterPassword, options) { - var _options = assign({}, defaultOptions, options); - return calcEntropy( - site, - login, - masterPassword, - _options - ).then(function(entropy) { - return renderPassword(entropy, _options); - }); - } - - function calcEntropy(site, login, masterPassword, passwordProfile) { - var salt = site + login + passwordProfile.counter.toString(16); - return pbkdf2( - masterPassword, - salt, - passwordProfile.iterations, - passwordProfile.keylen, - passwordProfile.digest - ); - } - - var characterSubsets = { - lowercase: "abcdefghijklmnopqrstuvwxyz", - uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - numbers: "0123456789", - symbols: "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" - }; - - function getSetOfCharacters(rules) { - if (typeof rules === "undefined") { - return ( - characterSubsets.lowercase + - characterSubsets.uppercase + - characterSubsets.numbers + - characterSubsets.symbols - ); - } - var setOfChars = ""; - rules.forEach(function(rule) { - setOfChars += characterSubsets[rule]; - }); - return setOfChars; - } + true, + ["encrypt", "decrypt"] + ); + }) + .then(function(derivedKey) { + return window.crypto.subtle + .exportKey("raw", derivedKey) + .then(function(keyArray) { + return new Buffer(keyArray).toString("hex"); + }); + }); +} + +function pbkdf2Browserified(password, salt, iterations, keylen, digest) { + return new Promise(function(resolve, reject) { + pbkdf2.pbkdf2(password, salt, iterations, keylen, digest, function( + error, + key + ) { + if (error) { + reject("error in pbkdf2"); + } else { + resolve(key.toString("hex")); + } + }); + }); +} + +module.exports = shouldUseNative() ? pbkdf2WebCrypto : pbkdf2Browserified; + +},{"buffer/":5,"es6-promise":12,"pbkdf2":19}],50:[function(require,module,exports){ +(function (Buffer){ +var pbkdf2 = require("./pbkdf2"); +var assign = require("lodash.assign"); +var createHMAC = require("create-hmac"); + +module.exports = { + generatePassword: generatePassword, + _renderPassword: renderPassword, + _createHmac: createHmac, + _deriveEncryptedLogin: deriveEncryptedLogin, + _getPasswordTemplate: getPasswordTemplate, + _prettyPrint: prettyPrint, + _string2charCodes: string2charCodes, + _getCharType: getCharType, + _getPasswordChar: getPasswordChar +}; + +var defaultOptions = { + version: 1, + lowercase: true, + numbers: true, + uppercase: true, + symbols: true, + keylen: 32, + digest: "sha256", + length: 12, + counter: 1, + iterations: 8192 +}; + +function generatePassword(site, login, masterPassword, options) { + var _options = assign({}, defaultOptions, options); + return pbkdf2( + masterPassword, + login, + _options.iterations, + _options.keylen, + "sha256" + ).then(function(encryptedLogin) { + return renderPassword(encryptedLogin, site, _options).then(function( + generatedPassword + ) { + return generatedPassword; + }); + }); +} + +function renderPassword(encryptedLogin, site, passwordOptions) { + return deriveEncryptedLogin( + encryptedLogin, + site, + passwordOptions + ).then(function(derivedEncryptedLogin) { + var template = + passwordOptions.template || getPasswordTemplate(passwordOptions); + return prettyPrint(derivedEncryptedLogin, template); + }); +} + +function createHmac(encryptedLogin, salt) { + return new Promise(function(resolve) { + resolve( + createHMAC("sha256", new Buffer(encryptedLogin)) + .update(salt) + .digest("hex") + ); + }); +} - function consumeEntropy( - generatedPassword, - quotient, - setOfCharacters, - maxLength - ) { - if (generatedPassword.length >= maxLength) { - return { value: generatedPassword, entropy: quotient }; - } - var longDivision = quotient.divmod(setOfCharacters.length); - generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy( - generatedPassword, - longDivision.quotient, - setOfCharacters, - maxLength - ); - } +function deriveEncryptedLogin(encryptedLogin, site, options) { + var _options = options !== undefined ? options : {}; + var length = _options.length || 12; + var counter = _options.counter || 1; - function insertStringPseudoRandomly( - generatedPassword, - entropy, - string - ) { - for (var i = 0; i < string.length; i++) { - var longDivision = entropy.divmod(generatedPassword.length); - generatedPassword = - generatedPassword.slice(0, longDivision.remainder) + - string[i] + - generatedPassword.slice(longDivision.remainder); - entropy = longDivision.quotient; - } - return generatedPassword; - } + var salt = site + counter.toString(); + return createHmac(encryptedLogin, salt).then(function(derivedHash) { + return derivedHash.substring(0, length); + }); +} + +function getPasswordTemplate(passwordTypes) { + var templates = { + lowercase: "vc", + uppercase: "VC", + numbers: "n", + symbols: "s" + }; + var returnedTemplate = ""; + Object.keys(templates).forEach(function(template) { + if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) { + returnedTemplate += templates[template]; + } + }); + return returnedTemplate; +} - function getOneCharPerRule(entropy, rules) { - var oneCharPerRules = ""; - rules.forEach(function(rule) { - var password = consumeEntropy( - "", - entropy, - characterSubsets[rule], - 1 - ); - oneCharPerRules += password.value; - entropy = password.entropy; - }); - return { value: oneCharPerRules, entropy: entropy }; - } +function prettyPrint(hash, template) { + var password = ""; - function getConfiguredRules(passwordProfile) { - return [ - "lowercase", - "uppercase", - "numbers", - "symbols" - ].filter(function(rule) { - return passwordProfile[rule]; - }); - } + string2charCodes(hash).forEach(function(charCode, index) { + var charType = getCharType(template, index); + password += getPasswordChar(charType, charCode); + }); + return password; +} - function renderPassword(entropy, passwordProfile) { - var rules = getConfiguredRules(passwordProfile); - var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy( - "", - bigInt(entropy, 16), - setOfCharacters, - passwordProfile.length - rules.length - ); - var charactersToAdd = getOneCharPerRule(password.entropy, rules); - return insertStringPseudoRandomly( - password.value, - charactersToAdd.entropy, - charactersToAdd.value - ); - } - }, - { "./pbkdf2": 49, "big-integer": 2, "lodash.assign": 18 } - ] - }, - {}, - [48] - )(48); -}); +function string2charCodes(text) { + var charCodes = []; + for (var i = 0; i < text.length; i++) { + charCodes.push(text.charCodeAt(i)); + } + return charCodes; +} + +function getCharType(template, index) { + return template[index % template.length]; +} + +function getPasswordChar(charType, index) { + var passwordsChars = { + V: "AEIOUY", + C: "BCDFGHJKLMNPQRSTVWXZ", + v: "aeiouy", + c: "bcdfghjklmnpqrstvwxz", + A: "AEIOUYBCDFGHJKLMNPQRSTVWXZ", + a: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz", + n: "0123456789", + s: "@&%?,=[]_:-+*$#!'^~;()/.", + x: "AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!'^~;()/." + }; + var passwordChar = passwordsChars[charType]; + return passwordChar[index % passwordChar.length]; +} + +}).call(this,require("buffer").Buffer) +},{"./pbkdf2":49,"buffer":5,"create-hmac":11,"lodash.assign":18}],51:[function(require,module,exports){ +var pbkdf2 = require("./pbkdf2"); +var bigInt = require("big-integer"); +var assign = require("lodash.assign"); + +module.exports = { + generatePassword: generatePassword, + _calcEntropy: calcEntropy, + _consumeEntropy: consumeEntropy, + _getSetOfCharacters: getSetOfCharacters, + _getConfiguredRules: getConfiguredRules, + _insertStringPseudoRandomly: insertStringPseudoRandomly, + _getOneCharPerRule: getOneCharPerRule, + _renderPassword: renderPassword +}; + +var defaultOptions = { + version: 2, + lowercase: true, + numbers: true, + uppercase: true, + symbols: true, + keylen: 32, + digest: "sha256", + length: 16, + counter: 1, + iterations: 100000 +}; + +function generatePassword(site, login, masterPassword, options) { + var _options = assign({}, defaultOptions, options); + return calcEntropy(site, login, masterPassword, _options).then(function( + entropy + ) { + return renderPassword(entropy, _options); + }); +} + +function calcEntropy(site, login, masterPassword, passwordProfile) { + var salt = site + login + passwordProfile.counter.toString(16); + return pbkdf2( + masterPassword, + salt, + passwordProfile.iterations, + passwordProfile.keylen, + passwordProfile.digest + ); +} + +var characterSubsets = { + lowercase: "abcdefghijklmnopqrstuvwxyz", + uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + numbers: "0123456789", + symbols: "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" +}; + +function getSetOfCharacters(rules) { + if (typeof rules === "undefined") { + return ( + characterSubsets.lowercase + + characterSubsets.uppercase + + characterSubsets.numbers + + characterSubsets.symbols + ); + } + var setOfChars = ""; + rules.forEach(function(rule) { + setOfChars += characterSubsets[rule]; + }); + return setOfChars; +} + +function consumeEntropy( + generatedPassword, + quotient, + setOfCharacters, + maxLength +) { + if (generatedPassword.length >= maxLength) { + return { value: generatedPassword, entropy: quotient }; + } + var longDivision = quotient.divmod(setOfCharacters.length); + generatedPassword += setOfCharacters[longDivision.remainder]; + return consumeEntropy( + generatedPassword, + longDivision.quotient, + setOfCharacters, + maxLength + ); +} + +function insertStringPseudoRandomly(generatedPassword, entropy, string) { + for (var i = 0; i < string.length; i++) { + var longDivision = entropy.divmod(generatedPassword.length); + generatedPassword = + generatedPassword.slice(0, longDivision.remainder) + + string[i] + + generatedPassword.slice(longDivision.remainder); + entropy = longDivision.quotient; + } + return generatedPassword; +} + +function getOneCharPerRule(entropy, rules) { + var oneCharPerRules = ""; + rules.forEach(function(rule) { + var password = consumeEntropy("", entropy, characterSubsets[rule], 1); + oneCharPerRules += password.value; + entropy = password.entropy; + }); + return { value: oneCharPerRules, entropy: entropy }; +} + +function getConfiguredRules(passwordProfile) { + return ["lowercase", "uppercase", "numbers", "symbols"].filter(function( + rule + ) { + return passwordProfile[rule]; + }); +} + +function renderPassword(entropy, passwordProfile) { + var rules = getConfiguredRules(passwordProfile); + var setOfCharacters = getSetOfCharacters(rules); + var password = consumeEntropy( + "", + bigInt(entropy, 16), + setOfCharacters, + passwordProfile.length - rules.length + ); + var charactersToAdd = getOneCharPerRule(password.entropy, rules); + return insertStringPseudoRandomly( + password.value, + charactersToAdd.entropy, + charactersToAdd.value + ); +} + +},{"./pbkdf2":49,"big-integer":2,"lodash.assign":18}]},{},[48])(48) +}); \ No newline at end of file diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js new file mode 100644 index 0000000..dd06e66 --- /dev/null +++ b/dist/lesspass.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).LessPass=t()}}(function(){return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var f=r[s]={exports:{}};e[s][0].call(f.exports,function(t){var r=e[s][1][t];return i(r||t)},f,f.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function i(t){return 3*t.length/4-n(t)}function o(t){var e,r,i,o,s,a,u=t.length;s=n(t),a=new l(3*u/4-s),i=s>0?u-4:u;var h=0;for(e=0,r=0;e>16&255,a[h++]=o>>8&255,a[h++]=255&o;return 2===s?(o=f[t.charCodeAt(e)]<<2|f[t.charCodeAt(e+1)]>>4,a[h++]=255&o):1===s&&(o=f[t.charCodeAt(e)]<<10|f[t.charCodeAt(e+1)]<<4|f[t.charCodeAt(e+2)]>>2,a[h++]=o>>8&255,a[h++]=255&o),a}function s(t){return h[t>>18&63]+h[t>>12&63]+h[t>>6&63]+h[63&t]}function a(t,e,r){for(var n,i=[],o=e;ou?u:s+16383));return 1===n?(e=t[r-1],i+=h[e>>2],i+=h[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=h[e>>10],i+=h[e>>4&63],i+=h[e<<2&63],i+="="),o.push(i),o.join("")}r.byteLength=i,r.toByteArray=o,r.fromByteArray=u;for(var h=[],f=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,d=c.length;p0?Math.floor(t):Math.ceil(t)}function l(t,e){var r,n,i=t.length,o=e.length,s=new Array(i),a=0,u=Z;for(n=0;n=u?1:0,s[n]=r-a*u;for(;n0&&s.push(a),s}function c(t,e){return t.length>=e.length?l(t,e):l(e,t)}function p(t,e){var r,n,i=t.length,o=new Array(i),s=Z;for(n=0;n0;)o[n++]=e%s,e=Math.floor(e/s);return o}function d(t,e){var r,n,i=t.length,o=e.length,s=new Array(i),a=0,h=Z;for(r=0;r=0?o=d(t,e):(o=d(e,t),n=!n),o=a(o),"number"==typeof o?(n&&(o=-o),new i(o)):new r(o,n)}function v(t,e,n){var o,s,u=t.length,h=new Array(u),f=-e,l=Z;for(o=0;o0;)o[n++]=a%s,a=Math.floor(a/s);return o}function b(t,e){for(var r=[];e-- >0;)r.push(0);return r.concat(t)}function _(t,e){var r=Math.max(t.length,e.length);if(r<=30)return y(t,e);r=Math.ceil(r/2);var n=t.slice(r),i=t.slice(0,r),o=e.slice(r),s=e.slice(0,r),a=_(i,s),h=_(n,o),f=c(c(a,b(d(d(_(c(i,n),c(s,o)),a),h),r)),b(h,2*r));return u(f),f}function m(t,e){return-.012*t-.012*e+15e-6*t*e>0}function E(t,e,n){return t=0;n--){for(r=p-1,y[n+c]!==g&&(r=Math.floor((y[n+c]*p+y[n+c-1])/g)),i=0,o=0,u=b.length,s=0;sf&&(i=(i+1)*p),r=Math.ceil(i/o);do{if(s=w(e,r),M(s,c)<=0)break;r--}while(r);l.push(r),c=d(c,s)}return l.reverse(),[a(l),a(c)]}function A(t,e){var r,n,i,o,s=t.length,a=h(s),u=Z;for(i=0,r=s-1;r>=0;--r)i=(o=i*u+t[r])-(n=f(o/e))*e,a[r]=0|n;return[a,0|i]}function k(t,n){var o,u,h=W(n),l=t.value,c=h.value;if(0===c)throw new Error("Cannot divide by zero");if(t.isSmall)return h.isSmall?[new i(f(l/c)),new i(l%c)]:[e[0],t];if(h.isSmall){if(1===c)return[t,e[0]];if(-1==c)return[t.negate(),e[0]];var p=Math.abs(c);if(pe.length?1:-1;for(var r=t.length-1;r>=0;r--)if(t[r]!==e[r])return t[r]>e[r]?1:-1;return 0}function L(t){var e=t.abs();return!e.isUnit()&&(!!(e.equals(2)||e.equals(3)||e.equals(5))||!(e.isEven()||e.isDivisibleBy(3)||e.isDivisibleBy(5))&&(!!e.lesser(25)||void 0))}function C(t){return("number"==typeof t||"string"==typeof t)&&+Math.abs(t)<=Z||t instanceof r&&t.value.length<=1}function T(t,e,r){e=W(e);for(var i=t.isNegative(),o=e.isNegative(),s=i?t.not():t,a=o?e.not():e,u=[],h=[],f=!1,l=!1;!f||!l;)s.isZero()?(f=!0,u.push(i?1:0)):i?u.push(s.isEven()?1:0):u.push(s.isEven()?0:1),a.isZero()?(l=!0,h.push(o?1:0)):o?h.push(a.isEven()?1:0):h.push(a.isEven()?0:1),s=s.over(2),a=a.over(2);for(var c=[],p=0;p=0;h--){var l=u?o.value[h]:Z,c=f(Math.random()*l);s.unshift(c),c=0;i--)o=o.add(t[i].times(s)),s=s.times(r);return n?o.negate():o}function N(t){var e=t.value;return"number"==typeof e&&(e=[e]),1===e.length&&e[0]<=35?"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e[0]):"<"+e+">"}function D(t,e){if((e=n(e)).isZero()){if(t.isZero())return"0";throw new Error("Cannot convert nonzero numbers to base 0.")}if(e.equals(-1))return t.isZero()?"0":t.isNegative()?new Array(1-t).join("10"):"1"+new Array(+t).join("01");var r="";if(t.isNegative()&&e.isPositive()&&(r="-",t=t.abs()),e.equals(1))return t.isZero()?"0":r+new Array(+t+1).join(1);for(var i,o=[],s=t;s.isNegative()||s.compareAbs(e)>=0;){s=(i=s.divmod(e)).quotient;var a=i.remainder;a.isNegative()&&(a=e.minus(a).abs(),s=s.next()),o.push(N(a))}return o.push(N(s)),r+o.reverse().join("")}function z(t){if(o(+t)){var e=+t;if(e===f(e))return new i(e);throw"Invalid integer: "+t}var n="-"===t[0];n&&(t=t.slice(1));var s=t.split(/e/i);if(s.length>2)throw new Error("Invalid integer: "+s.join("e"));if(2===s.length){var a=s[1];if("+"===a[0]&&(a=a.slice(1)),(a=+a)!==f(a)||!o(a))throw new Error("Invalid integer: "+a+" is not a valid exponent.");var h=s[0],l=h.indexOf(".");if(l>=0&&(a-=h.length-l-1,h=h.slice(0,l)+h.slice(l+1)),a<0)throw new Error("Cannot include negative exponent part for integers");t=h+=new Array(a+1).join("0")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error("Invalid integer: "+t);for(var c=[],p=t.length,d=H,g=p-d;p>0;)c.push(+t.slice(g,p)),(g-=d)<0&&(g=0),p-=d;return u(c),new r(c,n)}function F(t){if(o(t)){if(t!==f(t))throw new Error(t+" is not an integer.");return new i(t)}return z(t.toString())}function W(t){return"number"==typeof t?F(t):"string"==typeof t?z(t):t}var Z=1e7,H=7,Y=9007199254740992,K=s(Y),V=Math.log(Y);r.prototype=Object.create(e.prototype),i.prototype=Object.create(e.prototype),r.prototype.add=function(t){var e=W(t);if(this.sign!==e.sign)return this.subtract(e.negate());var n=this.value,i=e.value;return e.isSmall?new r(p(n,Math.abs(i)),this.sign):new r(c(n,i),this.sign)},r.prototype.plus=r.prototype.add,i.prototype.add=function(t){var e=W(t),n=this.value;if(n<0!==e.sign)return this.subtract(e.negate());var a=e.value;if(e.isSmall){if(o(n+a))return new i(n+a);a=s(Math.abs(a))}return new r(p(a,Math.abs(n)),n<0)},i.prototype.plus=i.prototype.add,r.prototype.subtract=function(t){var e=W(t);if(this.sign!==e.sign)return this.add(e.negate());var r=this.value,n=e.value;return e.isSmall?v(r,Math.abs(n),this.sign):g(r,n,this.sign)},r.prototype.minus=r.prototype.subtract,i.prototype.subtract=function(t){var e=W(t),r=this.value;if(r<0!==e.sign)return this.add(e.negate());var n=e.value;return e.isSmall?new i(r-n):v(n,Math.abs(r),r>=0)},i.prototype.minus=i.prototype.subtract,r.prototype.negate=function(){return new r(this.value,!this.sign)},i.prototype.negate=function(){var t=this.sign,e=new i(-this.value);return e.sign=!t,e},r.prototype.abs=function(){return new r(this.value,!1)},i.prototype.abs=function(){return new i(Math.abs(this.value))},r.prototype.multiply=function(t){var n,i=W(t),o=this.value,a=i.value,u=this.sign!==i.sign;if(i.isSmall){if(0===a)return e[0];if(1===a)return this;if(-1===a)return this.negate();if((n=Math.abs(a))n?1:-1):-1},r.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=W(t),r=this.value,n=e.value;return this.sign!==e.sign?e.sign?1:-1:e.isSmall?this.sign?-1:1:M(r,n)*(this.sign?-1:1)},r.prototype.compareTo=r.prototype.compare,i.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=W(t),r=this.value,n=e.value;return e.isSmall?r==n?0:r>n?1:-1:r<0!==e.sign?r<0?-1:1:r<0?1:-1},i.prototype.compareTo=i.prototype.compare,r.prototype.equals=function(t){return 0===this.compare(t)},i.prototype.eq=i.prototype.equals=r.prototype.eq=r.prototype.equals,r.prototype.notEquals=function(t){return 0!==this.compare(t)},i.prototype.neq=i.prototype.notEquals=r.prototype.neq=r.prototype.notEquals,r.prototype.greater=function(t){return this.compare(t)>0},i.prototype.gt=i.prototype.greater=r.prototype.gt=r.prototype.greater,r.prototype.lesser=function(t){return this.compare(t)<0},i.prototype.lt=i.prototype.lesser=r.prototype.lt=r.prototype.lesser,r.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},i.prototype.geq=i.prototype.greaterOrEquals=r.prototype.geq=r.prototype.greaterOrEquals,r.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},i.prototype.leq=i.prototype.lesserOrEquals=r.prototype.leq=r.prototype.lesserOrEquals,r.prototype.isEven=function(){return 0==(1&this.value[0])},i.prototype.isEven=function(){return 0==(1&this.value)},r.prototype.isOdd=function(){return 1==(1&this.value[0])},i.prototype.isOdd=function(){return 1==(1&this.value)},r.prototype.isPositive=function(){return!this.sign},i.prototype.isPositive=function(){return this.value>0},r.prototype.isNegative=function(){return this.sign},i.prototype.isNegative=function(){return this.value<0},r.prototype.isUnit=function(){return!1},i.prototype.isUnit=function(){return 1===Math.abs(this.value)},r.prototype.isZero=function(){return!1},i.prototype.isZero=function(){return 0===this.value},r.prototype.isDivisibleBy=function(t){var r=W(t),n=r.value;return 0!==n&&(1===n||(2===n?this.isEven():this.mod(r).equals(e[0])))},i.prototype.isDivisibleBy=r.prototype.isDivisibleBy,r.prototype.isPrime=function(){var t=L(this);if(void 0!==t)return t;for(var r,i,o,s,a=this.abs(),u=a.prev(),h=[2,3,5,7,11,13,17,19],f=u;f.isEven();)f=f.divide(2);for(o=0;o-Y?new i(t-1):new r(K,!0)};for(var J=[1];J[J.length-1]<=Z;)J.push(2*J[J.length-1]);var X=J.length,G=J[X-1];r.prototype.shiftLeft=function(t){if(!C(t))throw new Error(String(t)+" is too large for shifting.");if((t=+t)<0)return this.shiftRight(-t);for(var e=this;t>=X;)e=e.multiply(G),t-=X-1;return e.multiply(J[t])},i.prototype.shiftLeft=r.prototype.shiftLeft,r.prototype.shiftRight=function(t){var e;if(!C(t))throw new Error(String(t)+" is too large for shifting.");if((t=+t)<0)return this.shiftLeft(-t);for(var r=this;t>=X;){if(r.isZero())return r;r=(e=k(r,G))[1].isNegative()?e[0].prev():e[0],t-=X-1}return e=k(r,J[t]),e[1].isNegative()?e[0].prev():e[0]},i.prototype.shiftRight=r.prototype.shiftRight,r.prototype.not=function(){return this.negate().prev()},i.prototype.not=r.prototype.not,r.prototype.and=function(t){return T(this,t,function(t,e){return t&e})},i.prototype.and=r.prototype.and,r.prototype.or=function(t){return T(this,t,function(t,e){return t|e})},i.prototype.or=r.prototype.or,r.prototype.xor=function(t){return T(this,t,function(t,e){return t^e})},i.prototype.xor=r.prototype.xor;var Q=1<<30,$=(Z&-Z)*(Z&-Z)|Q,tt=function(t,e){var r=t.length;if(2<=e&&e<=36&&r<=V/Math.log(e))return new i(parseInt(t,e));e=W(e);var n,o=[],s="-"===t[0];for(n=s?1:0;n"!==t[n]);o.push(W(t.slice(h+1,n)))}}return U(o,e,s)};r.prototype.toString=function(t){if(void 0===t&&(t=10),10!==t)return D(this,t);for(var e,r=this.value,n=r.length,i=String(r[--n]);--n>=0;)e=String(r[n]),i+="0000000".slice(e.length)+e;return(this.sign?"-":"")+i},i.prototype.toString=function(t){return void 0===t&&(t=10),10!=t?D(this,t):String(this.value)},r.prototype.valueOf=function(){return+this.toString()},r.prototype.toJSNumber=r.prototype.valueOf,i.prototype.valueOf=function(){return this.value},i.prototype.toJSNumber=i.prototype.valueOf;for(var et=0;et<1e3;et++)e[et]=new i(et),et>0&&(e[-et]=new i(-et));return e.one=e[1],e.zero=e[0],e.minusOne=e[-1],e.max=R,e.min=I,e.gcd=O,e.lcm=q,e.isInstance=function(t){return t instanceof r||t instanceof i},e.randBetween=P,e.fromArray=function(t,e,r){return U(t.map(W),W(e||10),r)},e}();void 0!==e&&e.hasOwnProperty("exports")&&(e.exports=n)},{}],3:[function(t,e,r){},{}],4:[function(t,e,r){(function(e){"use strict";var n=t("buffer"),i=n.Buffer,o=n.SlowBuffer,s=n.kMaxLength||2147483647;r.alloc=function(t,e,r){if("function"==typeof i.alloc)return i.alloc(t,e,r);if("number"==typeof r)throw new TypeError("encoding must not be number");if("number"!=typeof t)throw new TypeError("size must be a number");if(t>s)throw new RangeError("size is too large");var n=r,o=e;void 0===o&&(n=void 0,o=0);var a=new i(t);if("string"==typeof o)for(var u=new i(o,n),h=u.length,f=-1;++fs)throw new RangeError("size is too large");return new i(t)},r.from=function(t,r,n){if("function"==typeof i.from&&(!e.Uint8Array||Uint8Array.from!==i.from))return i.from(t,r,n);if("number"==typeof t)throw new TypeError('"value" argument must not be a number');if("string"==typeof t)return new i(t,r);if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer){var o=r;if(1===arguments.length)return new i(t);void 0===o&&(o=0);var s=n;if(void 0===s&&(s=t.byteLength-o),o>=t.byteLength)throw new RangeError("'offset' is out of bounds");if(s>t.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(t.slice(o,o+s))}if(i.isBuffer(t)){var a=new i(t.length);return t.copy(a,0,0,t.length),a}if(t){if(Array.isArray(t)||"undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return new i(t);if("Buffer"===t.type&&Array.isArray(t.data))return new i(t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},r.allocUnsafeSlow=function(t){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(t);if("number"!=typeof t)throw new TypeError("size must be a number");if(t>=s)throw new RangeError("size is too large");return new o(t)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{buffer:5}],5:[function(t,e,r){"use strict";function n(t){if(t>J)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=i.prototype,e}function i(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return u(t)}return o(t,e,r)}function o(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return t instanceof ArrayBuffer?l(t,e,r):"string"==typeof t?h(t,e):c(t)}function s(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function a(t,e,r){return s(t),t<=0?n(t):void 0!==e?"string"==typeof r?n(t).fill(e,r):n(t).fill(e):n(t)}function u(t){return s(t),n(t<0?0:0|p(t))}function h(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!i.isEncoding(e))throw new TypeError('"encoding" must be a valid string encoding');var r=0|g(t,e),o=n(r),s=o.write(t,e);return s!==r&&(o=o.slice(0,s)),o}function f(t){for(var e=t.length<0?0:0|p(t.length),r=n(e),i=0;i=J)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+J.toString(16)+" bytes");return 0|t}function d(t){return+t!=t&&(t=0),i.alloc(+t)}function g(t,e){if(i.isBuffer(t))return t.length;if(H(t)||t instanceof ArrayBuffer)return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return D(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(t).length;default:if(n)return D(t).length;e=(""+e).toLowerCase(),n=!0}}function v(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,e>>>=0,r<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return k(this,e,r);case"ascii":return L(this,e,r);case"latin1":case"binary":return C(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function y(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function w(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Y(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=i.from(e,n)),i.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){function o(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}var s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}var h;if(i){var f=-1;for(h=r;ha&&(r=a-u),h=r;h>=0;h--){for(var l=!0,c=0;ci&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s239?4:o>223?3:o>191?2:1;if(i+a<=r){var u,h,f,l;switch(a){case 1:o<128&&(s=o);break;case 2:128==(192&(u=t[i+1]))&&(l=(31&o)<<6|63&u)>127&&(s=l);break;case 3:u=t[i+1],h=t[i+2],128==(192&u)&&128==(192&h)&&(l=(15&o)<<12|(63&u)<<6|63&h)>2047&&(l<55296||l>57343)&&(s=l);break;case 4:u=t[i+1],h=t[i+2],f=t[i+3],128==(192&u)&&128==(192&h)&&128==(192&f)&&(l=(15&o)<<18|(63&u)<<12|(63&h)<<6|63&f)>65535&&l<1114112&&(s=l)}}null===s?(s=65533,a=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|1023&s),n.push(s),i+=a}return M(n)}function M(t){var e=t.length;if(e<=X)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function I(t,e,r,n,o,s){if(!i.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function O(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function q(t,e,r,n,i){return e=+e,r>>>=0,i||O(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),V.write(t,e,r,n,23,4),r+4}function P(t,e,r,n,i){return e=+e,r>>>=0,i||O(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),V.write(t,e,r,n,52,8),r+8}function U(t){if((t=t.trim().replace(G,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}function N(t){return t<16?"0"+t.toString(16):t.toString(16)}function D(t,e){e=e||1/0;for(var r,n=t.length,i=null,o=[],s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function z(t){for(var e=[],r=0;r>8,i=r%256,o.push(i),o.push(n);return o}function W(t){return K.toByteArray(U(t))}function Z(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function H(t){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(t)}function Y(t){return t!==t}var K=t("base64-js"),V=t("ieee754");r.Buffer=i,r.SlowBuffer=d,r.INSPECT_MAX_BYTES=50;var J=2147483647;r.kMaxLength=J,i.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(t,e,r){return o(t,e,r)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(t,e,r){return a(t,e,r)},i.allocUnsafe=function(t){return u(t)},i.allocUnsafeSlow=function(t){return u(t)},i.isBuffer=function(t){return null!=t&&!0===t._isBuffer},i.compare=function(t,e){if(!i.isBuffer(t)||!i.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,o=0,s=Math.min(r,n);o0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},i.prototype.compare=function(t,e,r,n,o){if(!i.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,o>>>=0,this===t)return 0;for(var s=o-n,a=r-e,u=Math.min(s,a),h=this.slice(n,o),f=t.slice(e,r),l=0;l>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return m(this,t,e,r);case"ascii":return E(this,t,e,r);case"latin1":case"binary":return S(this,t,e,r);case"base64":return x(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var X=4096;i.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||R(t,e,this.length);for(var n=this[t],i=1,o=0;++o>>=0,e>>>=0,r||R(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},i.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},i.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},i.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},i.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},i.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},i.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);for(var n=this[t],i=1,o=0;++o=i&&(n-=Math.pow(2,8*e)),n},i.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},i.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},i.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},i.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},i.prototype.readFloatLE=function(t,e){return t>>>=0,e||R(t,4,this.length),V.read(this,t,!0,23,4)},i.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),V.read(this,t,!1,23,4)},i.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),V.read(this,t,!0,52,8)},i.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),V.read(this,t,!1,52,8)},i.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||I(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,n||I(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},i.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,1,255,0),this[e]=255&t,e+1},i.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},i.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},i.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},i.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},i.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);I(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},i.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);I(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},i.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},i.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},i.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},i.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},i.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},i.prototype.writeFloatLE=function(t,e,r){return q(this,t,e,!0,r)},i.prototype.writeFloatBE=function(t,e,r){return q(this,t,e,!1,r)},i.prototype.writeDoubleLE=function(t,e,r){return P(this,t,e,!0,r)},i.prototype.writeDoubleBE=function(t,e,r){return P(this,t,e,!1,r)},i.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0);var s;if("number"==typeof t)for(s=e;s>5]|=128<>>9<<4)]=e;for(var r=1732584193,n=-271733879,i=-1732584194,f=271733878,l=0;l>16)+(e>>16)+(r>>16)<<16|65535&r}function f(t,e){return t<>>32-e}var l=t("./helpers");e.exports=function(t){return l.hash(t,n,16)}},{"./helpers":9}],11:[function(t,e,r){(function(r){"use strict";function n(t,e){s.call(this),t=t.toLowerCase(),"string"==typeof e&&(e=new r(e));var n="sha512"===t||"sha384"===t?128:64;this._alg=t,this._key=e,e.length>n?e=i(t).update(e).digest():e.length0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,o,a;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],o=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(r)){for(a=o;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],14:[function(t,e,r){r.read=function(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,f=-7,l=r?i-1:0,c=r?-1:1,p=t[e+l];for(l+=c,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[e+l],l+=c,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+l],l+=c,f-=8);if(0===o)o=1-h;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)},r.write=function(t,e,r,n,i,o){var s,a,u,h=8*o-i-1,f=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+l>=1?c/u:c*Math.pow(2,1-l))*u>=2&&(s++,u/=2),s+l>=f?(a=0,s=f):s+l>=1?(a=(e*u-1)*Math.pow(2,i),s+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}},{}],15:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],16:[function(t,e,r){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function i(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&n(t.slice(0,0))}e.exports=function(t){return null!=t&&(n(t)||i(t)||!!t._isBuffer)}},{}],17:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],18:[function(t,e,r){function n(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function i(t,e){for(var r=-1,n=Array(t);++r-1&&t%1==0&&t-1&&t%1==0&&t<=E}function b(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function _(t){return!!t&&"object"==typeof t}function m(t){return g(t)?o(t):a(t)}var E=9007199254740991,S="[object Arguments]",x="[object Function]",B="[object GeneratorFunction]",A=/^(?:0|[1-9]\d*)$/,k=Object.prototype,M=k.hasOwnProperty,L=k.toString,C=k.propertyIsEnumerable,T=function(t,e){return function(r){return t(e(r))}}(Object.keys,Object),j=Math.max,R=!C.call({valueOf:1},"valueOf"),I=Array.isArray,O=function(t){return u(function(e,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,s=i>2?r[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,s&&l(r[0],r[1],s)&&(o=i<3?void 0:o,i=1),e=Object(e);++n=6?"utf-8":"binary"}r.pbkdf2Sync=function(t,e,r,a,u){n.isBuffer(t)||(t=new n(t,s)),n.isBuffer(e)||(e=new n(e,s)),o(r,a),u=u||"sha1";var h,f=1,l=new n(a),c=new n(e.length+4);e.copy(c,0,0,e.length);for(var p,d,g=1;g<=f;g++){c.writeUInt32BE(g,e.length);var v=i(u,t).update(c).digest();h||(h=v.length,d=new n(h),p=a-((f=Math.ceil(a/h))-1)*h),v.copy(d,0,0,h);for(var y=1;yn||e!==e)throw new TypeError("Bad key length")}},{}],21:[function(t,e,r){(function(t){"use strict";function r(e,r,n,i){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var o,s,a=arguments.length;switch(a){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick(function(){e.call(null,r)});case 3:return t.nextTick(function(){e.call(null,r,n)});case 4:return t.nextTick(function(){e.call(null,r,n,i)});default:for(o=new Array(a-1),s=0;s1)for(var r=1;r0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var h;!e.decoder||i||n||(r=e.decoder.write(r),h=!e.objectMode&&0===r.length),i||(e.reading=!1),h||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&c(t))),d(t,e)}else i||(e.reading=!1);return a(e)}function a(t){return!t.ended&&(t.needReadable||t.length=z?t=z:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function h(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=u(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function f(t,e){var r=null;return R.isBuffer(e)||"string"==typeof e||null===e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function l(t,e){if(!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,c(t)}}function c(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(P("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?L(p,t):p(t))}function p(t){P("emit readable"),t.emit("readable"),_(t)}function d(t,e){e.readingMore||(e.readingMore=!0,L(g,t,e))}function g(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=E(t,e.buffer,e.decoder),r}function E(t,e,r){var n;return to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}function x(t,e){var r=I.allocUnsafe(t),n=e.head,i=1;for(n.data.copy(r),t-=n.data.length;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}function B(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,L(A,e,t))}function A(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function k(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return P("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?B(this):c(this),null;if(0===(t=h(t,e))&&e.ended)return 0===e.length&&B(this),null;var n=e.needReadable;P("need readable",n),(0===e.length||e.length-t0?m(t,e):null,null===i?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&B(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},o.prototype.pipe=function(t,e){function i(t){P("onunpipe"),t===c&&s()}function o(){P("onend"),t.end()}function s(){P("cleanup"),t.removeListener("close",h),t.removeListener("finish",f),t.removeListener("drain",g),t.removeListener("error",u),t.removeListener("unpipe",i),c.removeListener("end",o),c.removeListener("end",s),c.removeListener("data",a),y=!0,!p.awaitDrain||t._writableState&&!t._writableState.needDrain||g()}function a(e){P("ondata"),w=!1,!1!==t.write(e)||w||((1===p.pipesCount&&p.pipes===t||p.pipesCount>1&&-1!==k(p.pipes,t))&&!y&&(P("false write response, pause",c._readableState.awaitDrain),c._readableState.awaitDrain++,w=!0),c.pause())}function u(e){P("onerror",e),l(),t.removeListener("error",u),0===T(t,"error")&&t.emit("error",e)}function h(){t.removeListener("finish",f),l()}function f(){P("onfinish"),t.removeListener("close",h),l()}function l(){P("unpipe"),c.unpipe(t)}var c=this,p=this._readableState;switch(p.pipesCount){case 0:p.pipes=t;break;case 1:p.pipes=[p.pipes,t];break;default:p.pipes.push(t)}p.pipesCount+=1,P("pipe count=%d opts=%j",p.pipesCount,e);var d=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr?o:s;p.endEmitted?L(d):c.once("end",d),t.on("unpipe",i);var g=v(c);t.on("drain",g);var y=!1,w=!1;return c.on("data",a),n(t,"error",u),t.once("close",h),t.once("finish",f),t.emit("pipe",c),p.flowing||(P("pipe resume"),c.resume()),t},o.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this),this);if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1?setImmediate:x;s.WritableState=o;var A=t("core-util-is");A.inherits=t("inherits");var k={deprecate:t("util-deprecate")},M=t("./internal/streams/stream"),L=t("buffer").Buffer,C=t("buffer-shims");A.inherits(s,M),o.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(o.prototype,"buffer",{get:k.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(t){}}();var T;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(T=Function.prototype[Symbol.hasInstance],Object.defineProperty(s,Symbol.hasInstance,{value:function(t){return!!T.call(this,t)||t&&t._writableState instanceof o}})):T=function(t){return t instanceof this},s.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},s.prototype.write=function(t,e,r){var i=this._writableState,o=!1,s=L.isBuffer(t);return"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=n),i.ended?a(this,r):(s||u(this,i,t,r))&&(i.pendingcb++,o=f(this,i,s,t,e,r)),o},s.prototype.cork=function(){this._writableState.corked++},s.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||y(this,t))},s.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},s.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},s.prototype._writev=null,s.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||m(this,n,r)}}).call(this,t("_process"))},{"./_stream_duplex":24,"./internal/streams/stream":30,_process:22,buffer:5,"buffer-shims":4,"core-util-is":7,inherits:15,"process-nextick-args":21,"util-deprecate":47}],29:[function(t,e,r){"use strict";function n(){this.head=null,this.tail=null,this.length=0}t("buffer").Buffer;var i=t("buffer-shims");e.exports=n,n.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},n.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},n.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},n.prototype.clear=function(){this.head=this.tail=null,this.length=0},n.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},n.prototype.concat=function(t){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var e=i.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e}},{buffer:5,"buffer-shims":4}],30:[function(t,e,r){e.exports=t("events").EventEmitter},{events:13}],31:[function(t,e,r){"use strict";function n(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function i(t){var e=n(t);if("string"!=typeof e&&(w.isEncoding===_||!_(t)))throw new Error("Unknown encoding: "+t);return e||t}function o(t){this.encoding=i(t);var e;switch(this.encoding){case"utf16le":this.text=c,this.end=p,e=4;break;case"utf8":this.fillLast=h,e=4;break;case"base64":this.text=d,this.end=g,e=3;break;default:return this.write=v,void(this.end=y)}this.lastNeed=0,this.lastTotal=0,this.lastChar=b.allocUnsafe(e)}function s(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:-1}function a(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:t.lastNeed=i-3),i):0)}function u(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�".repeat(r);if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�".repeat(r+1);if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�".repeat(r+2)}}function h(t){var e=this.lastTotal-this.lastNeed,r=u(this,t,e);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function f(t,e){var r=a(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function l(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�".repeat(this.lastTotal-this.lastNeed):e}function c(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function p(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function d(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function g(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function v(t){return t.toString(this.encoding)}function y(t){return t&&t.length?this.write(t):""}var w=t("buffer").Buffer,b=t("buffer-shims"),_=w.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};r.StringDecoder=o,o.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>>5]|=t[r]<<24-n%32;return e}function n(t){for(var e=[],r=0;r<32*t.length;r+=8)e.push(t[r>>>5]>>>24-r%32&255);return e}function i(t,e,r){for(var n=0;n<16;n++){var i=r+n,l=e[i];e[i]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}var w,b,_,m,E,S,x,B,A,k;S=w=t[0],x=b=t[1],B=_=t[2],A=m=t[3],k=E=t[4];var M;for(n=0;n<80;n+=1)M=w+e[r+c[n]]|0,M+=n<16?o(b,_,m)+v[0]:n<32?s(b,_,m)+v[1]:n<48?a(b,_,m)+v[2]:n<64?u(b,_,m)+v[3]:h(b,_,m)+v[4],M=(M=f(M|=0,d[n]))+E|0,w=E,E=m,m=f(_,10),_=b,b=M,M=S+e[r+p[n]]|0,M+=n<16?h(x,B,A)+y[0]:n<32?u(x,B,A)+y[1]:n<48?a(x,B,A)+y[2]:n<64?s(x,B,A)+y[3]:o(x,B,A)+y[4],M=(M=f(M|=0,g[n]))+k|0,S=k,k=A,A=f(B,10),B=x,x=M;M=t[1]+_+A|0,t[1]=t[2]+m+k|0,t[2]=t[3]+E+S|0,t[3]=t[4]+w+x|0,t[4]=t[0]+b+B|0,t[0]=M}function o(t,e,r){return t^e^r}function s(t,e,r){return t&e|~t&r}function a(t,e,r){return(t|~e)^r}function u(t,e,r){return t&r|e&~r}function h(t,e,r){return t^(e|~r)}function f(t,e){return t<>>32-e}function l(e){var o=[1732584193,4023233417,2562383102,271733878,3285377520];"string"==typeof e&&(e=new t(e,"utf8"));var s=r(e),a=8*e.length,u=8*e.length;s[a>>>5]|=128<<24-a%32,s[14+(a+64>>>9<<4)]=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8);for(var h=0;h>>24)|4278255360&(f<<24|f>>>8)}var l=n(o);return new t(l)}var c=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],p=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],d=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],g=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],v=[0,1518500249,1859775393,2400959708,2840853838],y=[1352829926,1548603684,1836072691,2053994217,0];e.exports=l}).call(this,t("buffer").Buffer)},{buffer:5}],37:[function(t,e,r){(function(t){function r(e,r){this._block=new t(e),this._finalSize=r,this._blockSize=e,this._len=0,this._s=0}r.prototype.update=function(e,r){"string"==typeof e&&(e=new t(e,r=r||"utf8"));for(var n=this._len+=e.length,i=this._s||0,o=0,s=this._block;i=8*this._finalSize&&(this._update(this._block),this._block.fill(0)),this._block.writeInt32BE(e,this._blockSize-4);var r=this._update(this._block)||this._hash();return t?r.toString(t):r},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=r}).call(this,t("buffer").Buffer)},{buffer:5}],38:[function(t,e,r){(r=e.exports=function(t){t=t.toLowerCase();var e=r[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e}).sha=t("./sha"),r.sha1=t("./sha1"),r.sha224=t("./sha224"),r.sha256=t("./sha256"),r.sha384=t("./sha384"),r.sha512=t("./sha512")},{"./sha":39,"./sha1":40,"./sha224":41,"./sha256":42,"./sha384":43,"./sha512":44}],39:[function(t,e,r){(function(r){function n(){this.init(),this._w=f,u.call(this,64,56)}function i(t){return t<<5|t>>>27}function o(t){return t<<30|t>>>2}function s(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}var a=t("inherits"),u=t("./hash"),h=[1518500249,1859775393,-1894007588,-899497514],f=new Array(80);a(n,u),n.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},n.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,a=0|this._c,u=0|this._d,f=0|this._e,l=0;l<16;++l)e[l]=t.readInt32BE(4*l);for(;l<80;++l)e[l]=e[l-3]^e[l-8]^e[l-14]^e[l-16];for(var c=0;c<80;++c){var p=~~(c/20),d=i(r)+s(p,n,a,u)+f+e[c]+h[p]|0;f=u,u=a,a=o(n),n=r,r=d}this._a=r+this._a|0,this._b=n+this._b|0,this._c=a+this._c|0,this._d=u+this._d|0,this._e=f+this._e|0},n.prototype._hash=function(){var t=new r(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t},e.exports=n}).call(this,t("buffer").Buffer)},{"./hash":37,buffer:5,inherits:15}],40:[function(t,e,r){(function(r){function n(){this.init(),this._w=l,h.call(this,64,56)}function i(t){return t<<1|t>>>31}function o(t){return t<<5|t>>>27}function s(t){return t<<30|t>>>2}function a(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}var u=t("inherits"),h=t("./hash"),f=[1518500249,1859775393,-1894007588,-899497514],l=new Array(80);u(n,h),n.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},n.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,u=0|this._c,h=0|this._d,l=0|this._e,c=0;c<16;++c)e[c]=t.readInt32BE(4*c);for(;c<80;++c)e[c]=i(e[c-3]^e[c-8]^e[c-14]^e[c-16]);for(var p=0;p<80;++p){var d=~~(p/20),g=o(r)+a(d,n,u,h)+l+e[p]+f[d]|0;l=h,h=u,u=s(n),n=r,r=g}this._a=r+this._a|0,this._b=n+this._b|0,this._c=u+this._c|0,this._d=h+this._d|0,this._e=l+this._e|0},n.prototype._hash=function(){var t=new r(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t},e.exports=n}).call(this,t("buffer").Buffer)},{"./hash":37,buffer:5,inherits:15}],41:[function(t,e,r){(function(r){function n(){this.init(),this._w=a,s.call(this,64,56)}var i=t("inherits"),o=t("./sha256"),s=t("./hash"),a=new Array(64);i(n,o),n.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},n.prototype._hash=function(){var t=new r(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t},e.exports=n}).call(this,t("buffer").Buffer)},{"./hash":37,"./sha256":42,buffer:5,inherits:15}],42:[function(t,e,r){(function(r){function n(){this.init(),this._w=p,l.call(this,64,56)}function i(t,e,r){return r^t&(e^r)}function o(t,e,r){return t&e|r&(t|e)}function s(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function a(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function u(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function h(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}var f=t("inherits"),l=t("./hash"),c=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=new Array(64);f(n,l),n.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},n.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,f=0|this._c,l=0|this._d,p=0|this._e,d=0|this._f,g=0|this._g,v=0|this._h,y=0;y<16;++y)e[y]=t.readInt32BE(4*y);for(;y<64;++y)e[y]=h(e[y-2])+e[y-7]+u(e[y-15])+e[y-16]|0;for(var w=0;w<64;++w){var b=v+a(p)+i(p,d,g)+c[w]+e[w]|0,_=s(r)+o(r,n,f)|0;v=g,g=d,d=p,p=l+b|0,l=f,f=n,n=r,r=b+_|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=f+this._c|0,this._d=l+this._d|0,this._e=p+this._e|0,this._f=d+this._f|0,this._g=g+this._g|0,this._h=v+this._h|0},n.prototype._hash=function(){var t=new r(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t},e.exports=n}).call(this,t("buffer").Buffer)},{"./hash":37,buffer:5,inherits:15}],43:[function(t,e,r){(function(r){function n(){this.init(),this._w=a,s.call(this,128,112)}var i=t("inherits"),o=t("./sha512"),s=t("./hash"),a=new Array(160);i(n,o),n.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},n.prototype._hash=function(){function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}var e=new r(48);return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=n}).call(this,t("buffer").Buffer)},{"./hash":37,"./sha512":44,buffer:5,inherits:15}],44:[function(t,e,r){(function(r){function n(){this.init(),this._w=v,d.call(this,128,112)}function i(t,e,r){return r^t&(e^r)}function o(t,e,r){return t&e|r&(t|e)}function s(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function a(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function u(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function h(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function f(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function l(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function c(t,e){return t>>>0>>0?1:0}var p=t("inherits"),d=t("./hash"),g=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],v=new Array(160);p(n,d),n.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},n.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,p=0|this._ch,d=0|this._dh,v=0|this._eh,y=0|this._fh,w=0|this._gh,b=0|this._hh,_=0|this._al,m=0|this._bl,E=0|this._cl,S=0|this._dl,x=0|this._el,B=0|this._fl,A=0|this._gl,k=0|this._hl,M=0;M<32;M+=2)e[M]=t.readInt32BE(4*M),e[M+1]=t.readInt32BE(4*M+4);for(;M<160;M+=2){var L=e[M-30],C=e[M-30+1],T=u(L,C),j=h(C,L),R=f(L=e[M-4],C=e[M-4+1]),I=l(C,L),O=e[M-14],q=e[M-14+1],P=e[M-32],U=e[M-32+1],N=j+q|0,D=T+O+c(N,j)|0;D=(D=D+R+c(N=N+I|0,I)|0)+P+c(N=N+U|0,U)|0,e[M]=D,e[M+1]=N}for(var z=0;z<160;z+=2){D=e[z],N=e[z+1];var F=o(r,n,p),W=o(_,m,E),Z=s(r,_),H=s(_,r),Y=a(v,x),K=a(x,v),V=g[z],J=g[z+1],X=i(v,y,w),G=i(x,B,A),Q=k+K|0,$=b+Y+c(Q,k)|0;$=($=($=$+X+c(Q=Q+G|0,G)|0)+V+c(Q=Q+J|0,J)|0)+D+c(Q=Q+N|0,N)|0;var tt=H+W|0,et=Z+F+c(tt,H)|0;b=w,k=A,w=y,A=B,y=v,B=x,v=d+$+c(x=S+Q|0,S)|0,d=p,S=E,p=n,E=m,n=r,m=_,r=$+et+c(_=Q+tt|0,Q)|0}this._al=this._al+_|0,this._bl=this._bl+m|0,this._cl=this._cl+E|0,this._dl=this._dl+S|0,this._el=this._el+x|0,this._fl=this._fl+B|0,this._gl=this._gl+A|0,this._hl=this._hl+k|0,this._ah=this._ah+r+c(this._al,_)|0,this._bh=this._bh+n+c(this._bl,m)|0,this._ch=this._ch+p+c(this._cl,E)|0,this._dh=this._dh+d+c(this._dl,S)|0,this._eh=this._eh+v+c(this._el,x)|0,this._fh=this._fh+y+c(this._fl,B)|0,this._gh=this._gh+w+c(this._gl,A)|0,this._hh=this._hh+b+c(this._hl,k)|0},n.prototype._hash=function(){function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}var e=new r(64);return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=n}).call(this,t("buffer").Buffer)},{"./hash":37,buffer:5,inherits:15}],45:[function(t,e,r){function n(){i.call(this)}e.exports=n;var i=t("events").EventEmitter;t("inherits")(n,i),n.Readable=t("readable-stream/readable.js"),n.Writable=t("readable-stream/writable.js"),n.Duplex=t("readable-stream/duplex.js"),n.Transform=t("readable-stream/transform.js"),n.PassThrough=t("readable-stream/passthrough.js"),n.Stream=n,n.prototype.pipe=function(t,e){function r(e){t.writable&&!1===t.write(e)&&h.pause&&h.pause()}function n(){h.readable&&h.resume&&h.resume()}function o(){f||(f=!0,t.end())}function s(){f||(f=!0,"function"==typeof t.destroy&&t.destroy())}function a(t){if(u(),0===i.listenerCount(this,"error"))throw t}function u(){h.removeListener("data",r),t.removeListener("drain",n),h.removeListener("end",o),h.removeListener("close",s),h.removeListener("error",a),t.removeListener("error",a),h.removeListener("end",u),h.removeListener("close",u),t.removeListener("close",u)}var h=this;h.on("data",r),t.on("drain",n),t._isStdio||e&&!1===e.end||(h.on("end",o),h.on("close",s));var f=!1;return h.on("error",a),t.on("error",a),h.on("end",u),h.on("close",u),t.on("close",u),t.emit("pipe",h),t}},{events:13,inherits:15,"readable-stream/duplex.js":23,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],46:[function(t,e,r){function n(t){if(t&&!u(t))throw new Error("Unknown encoding: "+t)}function i(t){return t.toString(this.encoding)}function o(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function s(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}var a=t("buffer").Buffer,u=a.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},h=r.StringDecoder=function(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),n(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=s;break;default:return void(this.write=i)}this.charBuffer=new a(6),this.charReceived=0,this.charLength=0};h.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var n=(e+=t.toString(this.encoding,0,n)).length-1,i=e.charCodeAt(n);if(i>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},h.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},h.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e}},{buffer:5}],47:[function(t,e,r){(function(t){function r(t,e){function r(){if(!i){if(n("throwDeprecation"))throw new Error(e);n("traceDeprecation")?console.trace(e):console.warn(e),i=!0}return t.apply(this,arguments)}if(n("noDeprecation"))return t;var i=!1;return r}function n(e){try{if(!t.localStorage)return!1}catch(t){return!1}var r=t.localStorage[e];return null!=r&&"true"===String(r).toLowerCase()}e.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],48:[function(t,e,r){var n=t("./v1"),i=t("./v2"),o=t("create-hmac"),s=t("buffer/").Buffer,a=t("es6-promise").Promise;e.exports={generatePassword:function(t,e,r,o){return void 0!==o&&1===o.version?n.generatePassword(t,e,r,o):i.generatePassword(t,e,r,o)},createFingerprint:function(t){return new a(function(e){e(o("sha256",new s(t)).digest("hex"))})}}},{"./v1":50,"./v2":51,"buffer/":5,"create-hmac":11,"es6-promise":12}],49:[function(t,e,r){function n(t,e,r,n,i){var o={sha1:"SHA-1","sha-1":"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha512:"SHA-512","sha-512":"SHA-512"};return window.crypto.subtle.importKey("raw",new s(t),"PBKDF2",!1,["deriveKey"]).then(function(t){var a={name:"PBKDF2",salt:new s(e),iterations:r,hash:o[i.toLowerCase()]};return window.crypto.subtle.deriveKey(a,t,{name:"AES-CTR",length:8*n},!0,["encrypt","decrypt"])}).then(function(t){return window.crypto.subtle.exportKey("raw",t).then(function(t){return new s(t).toString("hex")})})}function i(t,e,r,n,i){return new a(function(s,a){o.pbkdf2(t,e,r,n,i,function(t,e){t?a("error in pbkdf2"):s(e.toString("hex"))})})}var o=t("pbkdf2"),s=t("buffer/").Buffer,a=t("es6-promise").Promise;e.exports=function(){return!("undefined"==typeof window||!window.crypto||!window.crypto.subtle)}()?n:i},{"buffer/":5,"es6-promise":12,pbkdf2:19}],50:[function(t,e,r){(function(r){function n(t,e,r,n){var o=p({},g,n);return c(r,e,o.iterations,o.keylen,"sha256").then(function(e){return i(e,t,o).then(function(t){return t})})}function i(t,e,r){return s(t,e,r).then(function(t){return u(t,r.template||a(r))})}function o(t,e){return new Promise(function(n){n(d("sha256",new r(t)).update(e).digest("hex"))})}function s(t,e,r){var n=void 0!==r?r:{},i=n.length||12;return o(t,e+(n.counter||1).toString()).then(function(t){return t.substring(0,i)})}function a(t){var e={lowercase:"vc",uppercase:"VC",numbers:"n",symbols:"s"},r="";return Object.keys(e).forEach(function(n){t.hasOwnProperty(n)&&t[n]&&(r+=e[n])}),r}function u(t,e){var r="";return h(t).forEach(function(t,n){var i=f(e,n);r+=l(i,t)}),r}function h(t){for(var e=[],r=0;r=n)return{value:t,entropy:e};var i=e.divmod(r.length);return t+=r[i.remainder],s(t,i.quotient,r,n)}function a(t,e,r){for(var n=0;n?@[\\]^_`{|}~"}},{"./pbkdf2":49,"big-integer":2,"lodash.assign":18}]},{},[48])(48)}); \ No newline at end of file diff --git a/example/index.html b/example/index.html index 4644d0e..bf06e23 100644 --- a/example/index.html +++ b/example/index.html @@ -4,7 +4,7 @@ - + - - diff --git a/package-lock.json b/package-lock.json index 4e8d916..5dfa374 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "7.0.1", + "version": "8.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 6e45e38..cc5d710 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lesspass", - "version": "7.0.1", + "version": "8.0.0", "description": "LessPass node module used to generate LessPass passwords", "keywords": [ "crypto", From 3262938209752e19b723f1538f05d1cc50344bf0 Mon Sep 17 00:00:00 2001 From: Guillaume Vincent Date: Thu, 9 Nov 2017 00:22:37 +0100 Subject: [PATCH 124/124] Use lesspass render password in core --- dist/lesspass.js | 240 ++-- dist/lesspass.min.js | 2 +- package-lock.json | 2748 +++++++++++++++++++---------------------- package.json | 14 +- src/lesspass.js | 126 +- test/entropy.tests.js | 40 +- test/renderPassword.tests.js | 99 -- test/setOfCharacters.tests.js | 78 -- 8 files changed, 1455 insertions(+), 1892 deletions(-) delete mode 100644 test/renderPassword.tests.js delete mode 100644 test/setOfCharacters.tests.js diff --git a/dist/lesspass.js b/dist/lesspass.js index 066cccf..4cbce6f 100644 --- a/dist/lesspass.js +++ b/dist/lesspass.js @@ -1039,14 +1039,31 @@ var bigInt = (function (undefined) { } var parseBase = function (text, base) { var length = text.length; + var i; + var absBase = Math.abs(base); + for(var i = 0; i < length; i++) { + var c = text[i].toLowerCase(); + if(c === "-") continue; + if(/[a-z0-9]/.test(c)) { + if(/[0-9]/.test(c) && +c >= absBase) { + if(c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } else if(c.charCodeAt(0) - 87 >= absBase) { + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } if (2 <= base && base <= 36) { if (length <= LOG_MAX_INT / Math.log(base)) { + var result = parseInt(text, base); + if(isNaN(result)) { + throw new Error(c + " is not a valid digit in base " + base + "."); + } return new SmallInteger(parseInt(text, base)); } } base = parseValue(base); var digits = []; - var i; var isNegative = text[0] === "-"; for (i = isNegative ? 1 : 0; i < text.length; i++) { var c = text[i].toLowerCase(), @@ -1127,11 +1144,13 @@ var bigInt = (function (undefined) { var sign = this.sign ? "-" : ""; return sign + str; }; + SmallInteger.prototype.toString = function (radix) { if (radix === undefined) radix = 10; if (radix != 10) return toBase(this, radix); return String(this.value); }; + BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function() { return this.toString(); } BigInteger.prototype.valueOf = function () { return +this.toString(); @@ -1235,6 +1254,112 @@ if ( typeof define === "function" && define.amd ) { } },{}],2:[function(require,module,exports){ +var consumeEntropy = require('./entropy').consumeEntropy; + +var _characterSubsets = { + lowercase: "abcdefghijklmnopqrstuvwxyz", + uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + digits: "0123456789", + symbols: "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" +}; + +function getSetOfCharacters(rules) { + if (typeof(rules) === "undefined") { + return ( + _characterSubsets.lowercase + + _characterSubsets.uppercase + + _characterSubsets.digits + + _characterSubsets.symbols + ); + } + var setOfChars = ""; + rules.forEach(function(rule) { + setOfChars += _characterSubsets[rule]; + }); + return setOfChars; +} + +function getOneCharPerRule(entropy, rules) { + var oneCharPerRules = ""; + rules.forEach(function(rule) { + var password = consumeEntropy("", entropy, _characterSubsets[rule], 1); + oneCharPerRules += password.value; + entropy = password.entropy; + }); + return {value: oneCharPerRules, entropy: entropy}; +} + +function getRules(options) { + return ["lowercase", "uppercase", "digits", "symbols"].filter(function(rule) { + return options[rule]; + }); +} + +function insertStringPseudoRandomly(generatedPassword, entropy, string) { + for (var i = 0; i < string.length; i++) { + var longDivision = entropy.divmod(generatedPassword.length); + generatedPassword = + generatedPassword.slice(0, longDivision.remainder) + + string[i] + + generatedPassword.slice(longDivision.remainder); + entropy = longDivision.quotient; + } + return generatedPassword; +} + +module.exports = { + getSetOfCharacters: getSetOfCharacters, + getOneCharPerRule: getOneCharPerRule, + insertStringPseudoRandomly: insertStringPseudoRandomly, + getRules: getRules, + characterSubsets: _characterSubsets +}; + +},{"./entropy":3}],3:[function(require,module,exports){ +function _consumeEntropy(generatedPassword, + quotient, + setOfCharacters, + maxLength) { + if (generatedPassword.length >= maxLength) { + return {value: generatedPassword, entropy: quotient}; + } + var longDivision = quotient.divmod(setOfCharacters.length); + generatedPassword += setOfCharacters[longDivision.remainder]; + return _consumeEntropy( + generatedPassword, + longDivision.quotient, + setOfCharacters, + maxLength + ); +} + +module.exports = { + consumeEntropy: _consumeEntropy +}; + +},{}],4:[function(require,module,exports){ +var bigInt = require("big-integer"); +var chars = require("./chars"); +var consumeEntropy = require("./entropy").consumeEntropy; + +module.exports = function renderPassword(entropy, options) { + var rules = chars.getRules(options); + var setOfCharacters = chars.getSetOfCharacters(rules); + var password = consumeEntropy( + "", + bigInt(entropy, 16), + setOfCharacters, + options.length - rules.length + ); + var charactersToAdd = chars.getOneCharPerRule(password.entropy, rules); + return chars.insertStringPseudoRandomly( + password.value, + charactersToAdd.entropy, + charactersToAdd.value + ); +}; + +},{"./chars":2,"./entropy":3,"big-integer":1}],5:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -3445,7 +3570,7 @@ function stubFalse() { module.exports = merge; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],3:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ (function () { 'use strict'; @@ -3551,7 +3676,7 @@ window.Unibabel = { }()); -},{}],4:[function(require,module,exports){ +},{}],7:[function(require,module,exports){ (function () { 'use strict'; @@ -3599,7 +3724,7 @@ window.Unibabel.bufferToHex = bufferToHex; }()); -},{}],5:[function(require,module,exports){ +},{}],8:[function(require,module,exports){ require("unibabel"); require("unibabel/unibabel.hex"); @@ -3632,11 +3757,11 @@ module.exports = function(digest, string, salt) { }); }; -},{"unibabel":3,"unibabel/unibabel.hex":4}],6:[function(require,module,exports){ +},{"unibabel":6,"unibabel/unibabel.hex":7}],9:[function(require,module,exports){ var hmac = require("./hmac"); var pbkdf2 = require("./pbkdf2"); -var bigInt = require("big-integer"); var merge = require("lodash.merge"); +var renderPassword = require("lesspass-render-password"); var defaultProfile = { site: '', @@ -3661,18 +3786,12 @@ module.exports = { generatePassword: generatePassword, createFingerprint: createFingerprint, isSupported: isSupported, - _calcEntropy: calcEntropy, - _consumeEntropy: consumeEntropy, - _getSetOfCharacters: getSetOfCharacters, - _getConfiguredRules: getConfiguredRules, - _insertStringPseudoRandomly: insertStringPseudoRandomly, - _getOneCharPerRule: getOneCharPerRule, - _renderPassword: renderPassword + _calcEntropy: _calcEntropy }; function generatePassword(profile, masterPassword) { var _profile = merge({}, defaultProfile, profile); - return calcEntropy(_profile, masterPassword) + return _calcEntropy(_profile, masterPassword) .then(function(entropy) { return renderPassword(entropy, _profile.options); }); @@ -3687,7 +3806,7 @@ function isSupported() { var simpleProfile = merge({}, defaultProfile, {crypto: {iterations: 1}}); return generatePassword(simpleProfile, 'LessPass') .then(function(generatedPassword) { - return generatedPassword == "n'LTsjPA#3E$e*2'"; + return generatedPassword === "n'LTsjPA#3E$e*2'"; }); } catch (e) { console.error(e); @@ -3695,7 +3814,7 @@ function isSupported() { } } -function calcEntropy(profile, masterPassword) { +function _calcEntropy(profile, masterPassword) { var salt = profile.site + profile.login + profile.options.counter.toString(16); return pbkdf2( masterPassword, @@ -3706,92 +3825,7 @@ function calcEntropy(profile, masterPassword) { ); } -var characterSubsets = { - lowercase: "abcdefghijklmnopqrstuvwxyz", - uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - digits: "0123456789", - symbols: "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" -}; - -function getSetOfCharacters(rules) { - if (typeof rules === "undefined") { - return ( - characterSubsets.lowercase + - characterSubsets.uppercase + - characterSubsets.digits + - characterSubsets.symbols - ); - } - var setOfChars = ""; - rules.forEach(function(rule) { - setOfChars += characterSubsets[rule]; - }); - return setOfChars; -} - -function consumeEntropy(generatedPassword, - quotient, - setOfCharacters, - maxLength) { - if (generatedPassword.length >= maxLength) { - return {value: generatedPassword, entropy: quotient}; - } - var longDivision = quotient.divmod(setOfCharacters.length); - generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy( - generatedPassword, - longDivision.quotient, - setOfCharacters, - maxLength - ); -} - -function insertStringPseudoRandomly(generatedPassword, entropy, string) { - for (var i = 0; i < string.length; i++) { - var longDivision = entropy.divmod(generatedPassword.length); - generatedPassword = - generatedPassword.slice(0, longDivision.remainder) + - string[i] + - generatedPassword.slice(longDivision.remainder); - entropy = longDivision.quotient; - } - return generatedPassword; -} - -function getOneCharPerRule(entropy, rules) { - var oneCharPerRules = ""; - rules.forEach(function(rule) { - var password = consumeEntropy("", entropy, characterSubsets[rule], 1); - oneCharPerRules += password.value; - entropy = password.entropy; - }); - return {value: oneCharPerRules, entropy: entropy}; -} - -function getConfiguredRules(passwordProfile) { - return ["lowercase", "uppercase", "digits", "symbols"].filter(function(rule) { - return passwordProfile[rule]; - }); -} - -function renderPassword(entropy, passwordProfile) { - var rules = getConfiguredRules(passwordProfile); - var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy( - "", - bigInt(entropy, 16), - setOfCharacters, - passwordProfile.length - rules.length - ); - var charactersToAdd = getOneCharPerRule(password.entropy, rules); - return insertStringPseudoRandomly( - password.value, - charactersToAdd.entropy, - charactersToAdd.value - ); -} - -},{"./hmac":5,"./pbkdf2":7,"big-integer":1,"lodash.merge":2}],7:[function(require,module,exports){ +},{"./hmac":8,"./pbkdf2":10,"lesspass-render-password":4,"lodash.merge":5}],10:[function(require,module,exports){ require("unibabel"); require("unibabel/unibabel.hex"); @@ -3835,5 +3869,5 @@ module.exports = function(password, salt, iterations, keylen, digest) { }); }; -},{"unibabel":3,"unibabel/unibabel.hex":4}]},{},[6])(6) +},{"unibabel":6,"unibabel/unibabel.hex":7}]},{},[9])(9) }); \ No newline at end of file diff --git a/dist/lesspass.min.js b/dist/lesspass.min.js index c633f1a..87ff911 100644 --- a/dist/lesspass.min.js +++ b/dist/lesspass.min.js @@ -1 +1 @@ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).LessPass=t()}}(function(){return function t(r,e,n){function o(u,a){if(!e[u]){if(!r[u]){var s="function"==typeof require&&require;if(!a&&s)return s(u,!0);if(i)return i(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var c=e[u]={exports:{}};r[u][0].call(c.exports,function(t){var e=r[u][1][t];return o(e||t)},c,c.exports,t,r,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u0?Math.floor(t):Math.ceil(t)}function p(t,r){var e,n,o=t.length,i=r.length,u=new Array(o),a=0,s=D;for(n=0;n=s?1:0,u[n]=e-a*s;for(;n0&&u.push(a),u}function l(t,r){return t.length>=r.length?p(t,r):p(r,t)}function h(t,r){var e,n,o=t.length,i=new Array(o),u=D;for(n=0;n0;)i[n++]=r%u,r=Math.floor(r/u);return i}function v(t,r){var e,n,o=t.length,i=r.length,u=new Array(o),a=0,f=D;for(e=0;e=0?i=v(t,r):(i=v(r,t),n=!n),"number"==typeof(i=a(i))?(n&&(i=-i),new o(i)):new e(i,n)}function g(t,r,n){var i,u,s=t.length,f=new Array(s),c=-r,p=D;for(i=0;i0;)i[n++]=a%u,a=Math.floor(a/u);return i}function w(t,r){for(var e=[];r-- >0;)e.push(0);return e.concat(t)}function m(t,r){var e=Math.max(t.length,r.length);if(e<=30)return d(t,r);e=Math.ceil(e/2);var n=t.slice(e),o=t.slice(0,e),i=r.slice(e),u=r.slice(0,e),a=m(o,u),f=m(n,i),c=l(l(a,w(v(v(m(l(o,n),l(u,i)),a),f),e)),w(f,2*e));return s(c),c}function _(t,r){return-.012*t-.012*r+15e-6*t*r>0}function A(t,r,n){return t=0;n--){for(e=h-1,d[n+l]!==y&&(e=Math.floor((d[n+l]*h+d[n+l-1])/y)),o=0,i=0,s=w.length,u=0;uc&&(o=(o+1)*h),e=Math.ceil(o/i);do{if(u=b(r,e),q(u,l)<=0)break;e--}while(e);p.push(e),l=v(l,u)}return p.reverse(),[a(p),a(l)]}function O(t,r){var e,n,o,i,u=t.length,a=f(u),s=D;for(o=0,e=u-1;e>=0;--e)o=(i=o*s+t[e])-(n=c(i/r))*r,a[e]=0|n;return[a,0|o]}function M(t,n){var i,s,f=R(n),p=t.value,l=f.value;if(0===l)throw new Error("Cannot divide by zero");if(t.isSmall)return f.isSmall?[new o(c(p/l)),new o(p%l)]:[r[0],t];if(f.isSmall){if(1===l)return[t,r[0]];if(-1==l)return[t.negate(),r[0]];var h=Math.abs(l);if(hr.length?1:-1;for(var e=t.length-1;e>=0;e--)if(t[e]!==r[e])return t[e]>r[e]?1:-1;return 0}function x(t){var r=t.abs();return!r.isUnit()&&(!!(r.equals(2)||r.equals(3)||r.equals(5))||!(r.isEven()||r.isDivisibleBy(3)||r.isDivisibleBy(5))&&(!!r.lesser(25)||void 0))}function P(t){return("number"==typeof t||"string"==typeof t)&&+Math.abs(t)<=D||t instanceof e&&t.value.length<=1}function U(t,r,e){r=R(r);for(var o=t.isNegative(),i=r.isNegative(),u=o?t.not():t,a=i?r.not():r,s=[],f=[],c=!1,p=!1;!c||!p;)u.isZero()?(c=!0,s.push(o?1:0)):o?s.push(u.isEven()?1:0):s.push(u.isEven()?0:1),a.isZero()?(p=!0,f.push(i?1:0)):i?f.push(a.isEven()?1:0):f.push(a.isEven()?0:1),u=u.over(2),a=a.over(2);for(var l=[],h=0;h=0;o--)i=i.add(t[o].times(u)),u=u.times(e);return n?i.negate():i}function N(t){var r=t.value;return"number"==typeof r&&(r=[r]),1===r.length&&r[0]<=35?"0123456789abcdefghijklmnopqrstuvwxyz".charAt(r[0]):"<"+r+">"}function k(t,r){if((r=n(r)).isZero()){if(t.isZero())return"0";throw new Error("Cannot convert nonzero numbers to base 0.")}if(r.equals(-1))return t.isZero()?"0":t.isNegative()?new Array(1-t).join("10"):"1"+new Array(+t).join("01");var e="";if(t.isNegative()&&r.isPositive()&&(e="-",t=t.abs()),r.equals(1))return t.isZero()?"0":e+new Array(+t+1).join(1);for(var o,i=[],u=t;u.isNegative()||u.compareAbs(r)>=0;){u=(o=u.divmod(r)).quotient;var a=o.remainder;a.isNegative()&&(a=r.minus(a).abs(),u=u.next()),i.push(N(a))}return i.push(N(u)),e+i.reverse().join("")}function Z(t){if(i(+t)){var r=+t;if(r===c(r))return new o(r);throw"Invalid integer: "+t}var n="-"===t[0];n&&(t=t.slice(1));var u=t.split(/e/i);if(u.length>2)throw new Error("Invalid integer: "+u.join("e"));if(2===u.length){var a=u[1];if("+"===a[0]&&(a=a.slice(1)),(a=+a)!==c(a)||!i(a))throw new Error("Invalid integer: "+a+" is not a valid exponent.");var f=u[0],p=f.indexOf(".");if(p>=0&&(a-=f.length-p-1,f=f.slice(0,p)+f.slice(p+1)),a<0)throw new Error("Cannot include negative exponent part for integers");t=f+=new Array(a+1).join("0")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error("Invalid integer: "+t);for(var l=[],h=t.length,v=F,y=h-v;h>0;)l.push(+t.slice(y,h)),(y-=v)<0&&(y=0),h-=v;return s(l),new e(l,n)}function L(t){if(i(t)){if(t!==c(t))throw new Error(t+" is not an integer.");return new o(t)}return Z(t.toString())}function R(t){return"number"==typeof t?L(t):"string"==typeof t?Z(t):t}var D=1e7,F=7,$=9007199254740992,z=u($),K=Math.log($);e.prototype=Object.create(r.prototype),o.prototype=Object.create(r.prototype),e.prototype.add=function(t){var r=R(t);if(this.sign!==r.sign)return this.subtract(r.negate());var n=this.value,o=r.value;return r.isSmall?new e(h(n,Math.abs(o)),this.sign):new e(l(n,o),this.sign)},e.prototype.plus=e.prototype.add,o.prototype.add=function(t){var r=R(t),n=this.value;if(n<0!==r.sign)return this.subtract(r.negate());var a=r.value;if(r.isSmall){if(i(n+a))return new o(n+a);a=u(Math.abs(a))}return new e(h(a,Math.abs(n)),n<0)},o.prototype.plus=o.prototype.add,e.prototype.subtract=function(t){var r=R(t);if(this.sign!==r.sign)return this.add(r.negate());var e=this.value,n=r.value;return r.isSmall?g(e,Math.abs(n),this.sign):y(e,n,this.sign)},e.prototype.minus=e.prototype.subtract,o.prototype.subtract=function(t){var r=R(t),e=this.value;if(e<0!==r.sign)return this.add(r.negate());var n=r.value;return r.isSmall?new o(e-n):g(n,Math.abs(e),e>=0)},o.prototype.minus=o.prototype.subtract,e.prototype.negate=function(){return new e(this.value,!this.sign)},o.prototype.negate=function(){var t=this.sign,r=new o(-this.value);return r.sign=!t,r},e.prototype.abs=function(){return new e(this.value,!1)},o.prototype.abs=function(){return new o(Math.abs(this.value))},e.prototype.multiply=function(t){var n,o=R(t),i=this.value,a=o.value,s=this.sign!==o.sign;if(o.isSmall){if(0===a)return r[0];if(1===a)return this;if(-1===a)return this.negate();if((n=Math.abs(a))n?1:-1):-1},e.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var r=R(t),e=this.value,n=r.value;return this.sign!==r.sign?r.sign?1:-1:r.isSmall?this.sign?-1:1:q(e,n)*(this.sign?-1:1)},e.prototype.compareTo=e.prototype.compare,o.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var r=R(t),e=this.value,n=r.value;return r.isSmall?e==n?0:e>n?1:-1:e<0!==r.sign?e<0?-1:1:e<0?1:-1},o.prototype.compareTo=o.prototype.compare,e.prototype.equals=function(t){return 0===this.compare(t)},o.prototype.eq=o.prototype.equals=e.prototype.eq=e.prototype.equals,e.prototype.notEquals=function(t){return 0!==this.compare(t)},o.prototype.neq=o.prototype.notEquals=e.prototype.neq=e.prototype.notEquals,e.prototype.greater=function(t){return this.compare(t)>0},o.prototype.gt=o.prototype.greater=e.prototype.gt=e.prototype.greater,e.prototype.lesser=function(t){return this.compare(t)<0},o.prototype.lt=o.prototype.lesser=e.prototype.lt=e.prototype.lesser,e.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},o.prototype.geq=o.prototype.greaterOrEquals=e.prototype.geq=e.prototype.greaterOrEquals,e.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},o.prototype.leq=o.prototype.lesserOrEquals=e.prototype.leq=e.prototype.lesserOrEquals,e.prototype.isEven=function(){return 0==(1&this.value[0])},o.prototype.isEven=function(){return 0==(1&this.value)},e.prototype.isOdd=function(){return 1==(1&this.value[0])},o.prototype.isOdd=function(){return 1==(1&this.value)},e.prototype.isPositive=function(){return!this.sign},o.prototype.isPositive=function(){return this.value>0},e.prototype.isNegative=function(){return this.sign},o.prototype.isNegative=function(){return this.value<0},e.prototype.isUnit=function(){return!1},o.prototype.isUnit=function(){return 1===Math.abs(this.value)},e.prototype.isZero=function(){return!1},o.prototype.isZero=function(){return 0===this.value},e.prototype.isDivisibleBy=function(t){var e=R(t),n=e.value;return 0!==n&&(1===n||(2===n?this.isEven():this.mod(e).equals(r[0])))},o.prototype.isDivisibleBy=e.prototype.isDivisibleBy,e.prototype.isPrime=function(){var t=x(this);if(void 0!==t)return t;for(var e,o,i,u,a=this.abs(),s=a.prev(),f=[2,3,5,7,11,13,17,19],c=s;c.isEven();)c=c.divide(2);for(i=0;i-$?new o(t-1):new e(z,!0)};for(var J=[1];J[J.length-1]<=D;)J.push(2*J[J.length-1]);var V=J.length,W=J[V-1];e.prototype.shiftLeft=function(t){if(!P(t))throw new Error(String(t)+" is too large for shifting.");if((t=+t)<0)return this.shiftRight(-t);for(var r=this;t>=V;)r=r.multiply(W),t-=V-1;return r.multiply(J[t])},o.prototype.shiftLeft=e.prototype.shiftLeft,e.prototype.shiftRight=function(t){var r;if(!P(t))throw new Error(String(t)+" is too large for shifting.");if((t=+t)<0)return this.shiftLeft(-t);for(var e=this;t>=V;){if(e.isZero())return e;e=(r=M(e,W))[1].isNegative()?r[0].prev():r[0],t-=V-1}return(r=M(e,J[t]))[1].isNegative()?r[0].prev():r[0]},o.prototype.shiftRight=e.prototype.shiftRight,e.prototype.not=function(){return this.negate().prev()},o.prototype.not=e.prototype.not,e.prototype.and=function(t){return U(this,t,function(t,r){return t&r})},o.prototype.and=e.prototype.and,e.prototype.or=function(t){return U(this,t,function(t,r){return t|r})},o.prototype.or=e.prototype.or,e.prototype.xor=function(t){return U(this,t,function(t,r){return t^r})},o.prototype.xor=e.prototype.xor;var G=1<<30,Q=(D&-D)*(D&-D)|G,X=function(t,r){var e=t.length;if(2<=r&&r<=36&&e<=K/Math.log(r))return new o(parseInt(t,r));r=R(r);var n,i=[],u="-"===t[0];for(n=u?1:0;n"!==t[n]);i.push(R(t.slice(f+1,n)))}}return H(i,r,u)};e.prototype.toString=function(t){if(void 0===t&&(t=10),10!==t)return k(this,t);for(var r,e=this.value,n=e.length,o=String(e[--n]);--n>=0;)r=String(e[n]),o+="0000000".slice(r.length)+r;return(this.sign?"-":"")+o},o.prototype.toString=function(t){return void 0===t&&(t=10),10!=t?k(this,t):String(this.value)},e.prototype.valueOf=function(){return+this.toString()},e.prototype.toJSNumber=e.prototype.valueOf,o.prototype.valueOf=function(){return this.value},o.prototype.toJSNumber=o.prototype.valueOf;for(var Y=0;Y<1e3;Y++)r[Y]=new o(Y),Y>0&&(r[-Y]=new o(-Y));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=B,r.min=C,r.gcd=I,r.lcm=function(t,r){return t=R(t).abs(),r=R(r).abs(),t.divide(I(t,r)).multiply(r)},r.isInstance=function(t){return t instanceof e||t instanceof o},r.randBetween=function(t,r){var n=C(t=R(t),r=R(r)),i=B(t,r).subtract(n);if(i.isSmall)return n.add(Math.round(Math.random()*i));for(var u=[],s=!0,f=i.value.length-1;f>=0;f--){var p=s?i.value[f]:D,l=c(Math.random()*p);u.unshift(l),l-1&&t%1==0&&t-1&&t%1==0&&t<=dt}function ft(t){var r=typeof t;return!!t&&("object"==r||"function"==r)}function ct(t){return!!t&&"object"==typeof t}function pt(t){if(!ct(t)||pr.call(t)!=Et||p(t))return!1;var r=gr(t);if(null===r)return!0;var e=fr.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&sr.call(e)==cr}function lt(t){return D(t,vt(t))}function ht(t){return it(t)?w(t):q(t)}function vt(t){return it(t)?w(t,!0):x(t)}var yt=200,gt="__lodash_hash_undefined__",dt=9007199254740991,bt="[object Arguments]",wt="[object Boolean]",mt="[object Date]",_t="[object Function]",At="[object GeneratorFunction]",St="[object Map]",jt="[object Number]",Et="[object Object]",Ot="[object RegExp]",Mt="[object Set]",qt="[object String]",xt="[object Symbol]",Pt="[object WeakMap]",Ut="[object ArrayBuffer]",Tt="[object DataView]",Bt="[object Float32Array]",Ct="[object Float64Array]",It="[object Int8Array]",Ht="[object Int16Array]",Nt="[object Int32Array]",kt="[object Uint8Array]",Zt="[object Uint8ClampedArray]",Lt="[object Uint16Array]",Rt="[object Uint32Array]",Dt=/[\\^$.*+?()[\]{}|]/g,Ft=/\w*$/,$t=/^\[object .+?Constructor\]$/,zt=/^(?:0|[1-9]\d*)$/,Kt={};Kt[Bt]=Kt[Ct]=Kt[It]=Kt[Ht]=Kt[Nt]=Kt[kt]=Kt[Zt]=Kt[Lt]=Kt[Rt]=!0,Kt[bt]=Kt["[object Array]"]=Kt[Ut]=Kt[wt]=Kt[Tt]=Kt[mt]=Kt["[object Error]"]=Kt[_t]=Kt[St]=Kt[jt]=Kt[Et]=Kt[Ot]=Kt[Mt]=Kt[qt]=Kt[Pt]=!1;var Jt={};Jt[bt]=Jt["[object Array]"]=Jt[Ut]=Jt[Tt]=Jt[wt]=Jt[mt]=Jt[Bt]=Jt[Ct]=Jt[It]=Jt[Ht]=Jt[Nt]=Jt[St]=Jt[jt]=Jt[Et]=Jt[Ot]=Jt[Mt]=Jt[qt]=Jt[xt]=Jt[kt]=Jt[Zt]=Jt[Lt]=Jt[Rt]=!0,Jt["[object Error]"]=Jt[_t]=Jt[Pt]=!1;var Vt="object"==typeof t&&t&&t.Object===Object&&t,Wt="object"==typeof self&&self&&self.Object===Object&&self,Gt=Vt||Wt||Function("return this")(),Qt="object"==typeof e&&e&&!e.nodeType&&e,Xt=Qt&&"object"==typeof r&&r&&!r.nodeType&&r,Yt=Xt&&Xt.exports===Qt,tr=Yt&&Vt.process,rr=function(){try{return tr&&tr.binding("util")}catch(t){}}(),er=rr&&rr.isTypedArray,nr=Array.prototype,or=Function.prototype,ir=Object.prototype,ur=Gt["__core-js_shared__"],ar=function(){var t=/[^.]+$/.exec(ur&&ur.keys&&ur.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),sr=or.toString,fr=ir.hasOwnProperty,cr=sr.call(Object),pr=ir.toString,lr=RegExp("^"+sr.call(fr).replace(Dt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),hr=Yt?Gt.Buffer:void 0,vr=Gt.Symbol,yr=Gt.Uint8Array,gr=h(Object.getPrototypeOf,Object),dr=Object.create,br=ir.propertyIsEnumerable,wr=nr.splice,mr=Object.getOwnPropertySymbols,_r=hr?hr.isBuffer:void 0,Ar=h(Object.keys,Object),Sr=Math.max,jr=K(Gt,"DataView"),Er=K(Gt,"Map"),Or=K(Gt,"Promise"),Mr=K(Gt,"Set"),qr=K(Gt,"WeakMap"),xr=K(Object,"create"),Pr=et(jr),Ur=et(Er),Tr=et(Or),Br=et(Mr),Cr=et(qr),Ir=vr?vr.prototype:void 0,Hr=Ir?Ir.valueOf:void 0;y.prototype.clear=function(){this.__data__=xr?xr(null):{}},y.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},y.prototype.get=function(t){var r=this.__data__;if(xr){var e=r[t];return e===gt?void 0:e}return fr.call(r,t)?r[t]:void 0},y.prototype.has=function(t){var r=this.__data__;return xr?void 0!==r[t]:fr.call(r,t)},y.prototype.set=function(t,r){return this.__data__[t]=xr&&void 0===r?gt:r,this},g.prototype.clear=function(){this.__data__=[]},g.prototype.delete=function(t){var r=this.__data__,e=A(r,t);return!(e<0||(e==r.length-1?r.pop():wr.call(r,e,1),0))},g.prototype.get=function(t){var r=this.__data__,e=A(r,t);return e<0?void 0:r[e][1]},g.prototype.has=function(t){return A(this.__data__,t)>-1},g.prototype.set=function(t,r){var e=this.__data__,n=A(e,t);return n<0?e.push([t,r]):e[n][1]=r,this},d.prototype.clear=function(){this.__data__={hash:new y,map:new(Er||g),string:new y}},d.prototype.delete=function(t){return z(this,t).delete(t)},d.prototype.get=function(t){return z(this,t).get(t)},d.prototype.has=function(t){return z(this,t).has(t)},d.prototype.set=function(t,r){return z(this,t).set(t,r),this},b.prototype.clear=function(){this.__data__=new g},b.prototype.delete=function(t){return this.__data__.delete(t)},b.prototype.get=function(t){return this.__data__.get(t)},b.prototype.has=function(t){return this.__data__.has(t)},b.prototype.set=function(t,r){var e=this.__data__;if(e instanceof g){var n=e.__data__;if(!Er||n.length1?e[o-1]:void 0,u=o>2?e[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,u&&Q(e[0],e[1],u)&&(i=o<3?void 0:i,o=1),r=Object(r);++n=n)return{value:t,entropy:r};var o=r.divmod(e.length);return t+=e[o.remainder],u(t,o.quotient,e,n)}function a(t,r,e){for(var n=0;n?@[\\]^_`{|}~"}},{"./hmac":5,"./pbkdf2":7,"big-integer":1,"lodash.merge":2}],7:[function(t,r,e){t("unibabel"),t("unibabel/unibabel.hex"),r.exports=function(t,r,e,n,o){var i={sha1:"SHA-1","sha-1":"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha512:"SHA-512","sha-512":"SHA-512"};return window.crypto.subtle.importKey("raw",Unibabel.utf8ToBuffer(t),"PBKDF2",!1,["deriveKey"]).then(function(t){var u={name:"PBKDF2",salt:Unibabel.utf8ToBuffer(r),iterations:e,hash:i[o.toLowerCase()]};return window.crypto.subtle.deriveKey(u,t,{name:"AES-CTR",length:8*n},!0,["encrypt","decrypt"])}).then(function(t){return window.crypto.subtle.exportKey("raw",t).then(function(t){return Unibabel.bufferToHex(new Uint8Array(t))})})}},{unibabel:3,"unibabel/unibabel.hex":4}]},{},[6])(6)}); \ No newline at end of file +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).LessPass=t()}}(function(){return function t(r,e,n){function o(u,a){if(!e[u]){if(!r[u]){var s="function"==typeof require&&require;if(!a&&s)return s(u,!0);if(i)return i(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var c=e[u]={exports:{}};r[u][0].call(c.exports,function(t){var e=r[u][1][t];return o(e||t)},c,c.exports,t,r,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u0?Math.floor(t):Math.ceil(t)}function p(t,r){var e,n,o=t.length,i=r.length,u=new Array(o),a=0,s=H;for(n=0;n=s?1:0,u[n]=e-a*s;for(;n0&&u.push(a),u}function l(t,r){return t.length>=r.length?p(t,r):p(r,t)}function h(t,r){var e,n,o=t.length,i=new Array(o),u=H;for(n=0;n0;)i[n++]=r%u,r=Math.floor(r/u);return i}function v(t,r){var e,n,o=t.length,i=r.length,u=new Array(o),a=0,f=H;for(e=0;e0;)i[n++]=a%u,a=Math.floor(a/u);return i}function b(t,r){for(var e=[];r-- >0;)e.push(0);return e.concat(t)}function w(t,r){var e=Math.max(t.length,r.length);if(e<=30)return g(t,r);e=Math.ceil(e/2);var n=t.slice(e),o=t.slice(0,e),i=r.slice(e),u=r.slice(0,e),a=w(o,u),f=w(n,i),c=l(l(a,b(v(v(w(l(o,n),l(u,i)),a),f),e)),b(f,2*e));return s(c),c}function m(t,r,n){return t=0;--e)o=(i=o*s+t[e])-(n=c(i/r))*r,a[e]=0|n;return[a,0|o]}function A(t,n){var i,p,l=N(n),h=t.value,y=l.value;if(0===y)throw new Error("Cannot divide by zero");if(t.isSmall)return l.isSmall?[new o(c(h/y)),new o(h%y)]:[r[0],t];if(l.isSmall){if(1===y)return[t,r[0]];if(-1==y)return[t.negate(),r[0]];var g=Math.abs(y);if(g=0;n--){for(e=h-1,b[n+l]!==y&&(e=Math.floor((b[n+l]*h+b[n+l-1])/y)),o=0,i=0,s=w.length,u=0;uc&&(o=(o+1)*h),e=Math.ceil(o/i);do{if(u=d(r,e),j(u,l)<=0)break;e--}while(e);p.push(e),l=v(l,u)}return p.reverse(),[a(p),a(l)]}(h,y))[0];var m=t.sign!==l.sign,_=i[1],A=t.sign;return"number"==typeof p?(m&&(p=-p),p=new o(p)):p=new e(p,m),"number"==typeof _?(A&&(_=-_),_=new o(_)):_=new e(_,A),[p,_]}function j(t,r){if(t.length!==r.length)return t.length>r.length?1:-1;for(var e=t.length-1;e>=0;e--)if(t[e]!==r[e])return t[e]>r[e]?1:-1;return 0}function E(t){var r=t.abs();return!r.isUnit()&&(!!(r.equals(2)||r.equals(3)||r.equals(5))||!(r.isEven()||r.isDivisibleBy(3)||r.isDivisibleBy(5))&&(!!r.lesser(25)||void 0))}function O(t){return("number"==typeof t||"string"==typeof t)&&+Math.abs(t)<=H||t instanceof e&&t.value.length<=1}function M(t,r,e){r=N(r);for(var o=t.isNegative(),i=r.isNegative(),u=o?t.not():t,a=i?r.not():r,s=[],f=[],c=!1,p=!1;!c||!p;)u.isZero()?(c=!0,s.push(o?1:0)):o?s.push(u.isEven()?1:0):s.push(u.isEven()?0:1),a.isZero()?(p=!0,f.push(i?1:0)):i?f.push(a.isEven()?1:0):f.push(a.isEven()?0:1),u=u.over(2),a=a.over(2);for(var l=[],h=0;h=0;o--)i=i.add(t[o].times(u)),u=u.times(e);return n?i.negate():i}function B(t){var r=t.value;return"number"==typeof r&&(r=[r]),1===r.length&&r[0]<=35?"0123456789abcdefghijklmnopqrstuvwxyz".charAt(r[0]):"<"+r+">"}function C(t,r){if((r=n(r)).isZero()){if(t.isZero())return"0";throw new Error("Cannot convert nonzero numbers to base 0.")}if(r.equals(-1))return t.isZero()?"0":t.isNegative()?new Array(1-t).join("10"):"1"+new Array(+t).join("01");var e="";if(t.isNegative()&&r.isPositive()&&(e="-",t=t.abs()),r.equals(1))return t.isZero()?"0":e+new Array(+t+1).join(1);for(var o,i=[],u=t;u.isNegative()||u.compareAbs(r)>=0;){u=(o=u.divmod(r)).quotient;var a=o.remainder;a.isNegative()&&(a=r.minus(a).abs(),u=u.next()),i.push(B(a))}return i.push(B(u)),e+i.reverse().join("")}function I(t){if(i(+t)){var r=+t;if(r===c(r))return new o(r);throw"Invalid integer: "+t}var n="-"===t[0];n&&(t=t.slice(1));var u=t.split(/e/i);if(u.length>2)throw new Error("Invalid integer: "+u.join("e"));if(2===u.length){var a=u[1];if("+"===a[0]&&(a=a.slice(1)),(a=+a)!==c(a)||!i(a))throw new Error("Invalid integer: "+a+" is not a valid exponent.");var f=u[0],p=f.indexOf(".");if(p>=0&&(a-=f.length-p-1,f=f.slice(0,p)+f.slice(p+1)),a<0)throw new Error("Cannot include negative exponent part for integers");t=f+=new Array(a+1).join("0")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error("Invalid integer: "+t);for(var l=[],h=t.length,v=R,y=h-v;h>0;)l.push(+t.slice(y,h)),(y-=v)<0&&(y=0),h-=v;return s(l),new e(l,n)}function N(t){return"number"==typeof t?function(t){if(i(t)){if(t!==c(t))throw new Error(t+" is not an integer.");return new o(t)}return I(t.toString())}(t):"string"==typeof t?I(t):t}var H=1e7,R=7,k=9007199254740992,L=u(k),Z=Math.log(k);e.prototype=Object.create(r.prototype),o.prototype=Object.create(r.prototype),e.prototype.add=function(t){var r=N(t);if(this.sign!==r.sign)return this.subtract(r.negate());var n=this.value,o=r.value;return r.isSmall?new e(h(n,Math.abs(o)),this.sign):new e(l(n,o),this.sign)},e.prototype.plus=e.prototype.add,o.prototype.add=function(t){var r=N(t),n=this.value;if(n<0!==r.sign)return this.subtract(r.negate());var a=r.value;if(r.isSmall){if(i(n+a))return new o(n+a);a=u(Math.abs(a))}return new e(h(a,Math.abs(n)),n<0)},o.prototype.plus=o.prototype.add,e.prototype.subtract=function(t){var r=N(t);if(this.sign!==r.sign)return this.add(r.negate());var n=this.value,i=r.value;return r.isSmall?y(n,Math.abs(i),this.sign):function(t,r,n){var i;return j(t,r)>=0?i=v(t,r):(i=v(r,t),n=!n),"number"==typeof(i=a(i))?(n&&(i=-i),new o(i)):new e(i,n)}(n,i,this.sign)},e.prototype.minus=e.prototype.subtract,o.prototype.subtract=function(t){var r=N(t),e=this.value;if(e<0!==r.sign)return this.add(r.negate());var n=r.value;return r.isSmall?new o(e-n):y(n,Math.abs(e),e>=0)},o.prototype.minus=o.prototype.subtract,e.prototype.negate=function(){return new e(this.value,!this.sign)},o.prototype.negate=function(){var t=this.sign,r=new o(-this.value);return r.sign=!t,r},e.prototype.abs=function(){return new e(this.value,!1)},o.prototype.abs=function(){return new o(Math.abs(this.value))},e.prototype.multiply=function(t){var n,o=N(t),i=this.value,a=o.value,s=this.sign!==o.sign;if(o.isSmall){if(0===a)return r[0];if(1===a)return this;if(-1===a)return this.negate();if((n=Math.abs(a))0}(i.length,a.length)?new e(w(i,a),s):new e(g(i,a),s)},e.prototype.times=e.prototype.multiply,o.prototype._multiplyBySmall=function(t){return i(t.value*this.value)?new o(t.value*this.value):m(Math.abs(t.value),u(Math.abs(this.value)),this.sign!==t.sign)},e.prototype._multiplyBySmall=function(t){return 0===t.value?r[0]:1===t.value?this:-1===t.value?this.negate():m(Math.abs(t.value),this.value,this.sign!==t.sign)},o.prototype.multiply=function(t){return N(t)._multiplyBySmall(this)},o.prototype.times=o.prototype.multiply,e.prototype.square=function(){return new e(_(this.value),!1)},o.prototype.square=function(){var t=this.value*this.value;return i(t)?new o(t):new e(_(u(Math.abs(this.value))),!1)},e.prototype.divmod=function(t){var r=A(this,t);return{quotient:r[0],remainder:r[1]}},o.prototype.divmod=e.prototype.divmod,e.prototype.divide=function(t){return A(this,t)[0]},o.prototype.over=o.prototype.divide=e.prototype.over=e.prototype.divide,e.prototype.mod=function(t){return A(this,t)[1]},o.prototype.remainder=o.prototype.mod=e.prototype.remainder=e.prototype.mod,e.prototype.pow=function(t){var e,n,u,a=N(t),s=this.value,f=a.value;if(0===f)return r[1];if(0===s)return r[0];if(1===s)return r[1];if(-1===s)return a.isEven()?r[1]:r[-1];if(a.sign)return r[0];if(!a.isSmall)throw new Error("The exponent "+a.toString()+" is too large.");if(this.isSmall&&i(e=Math.pow(s,f)))return new o(c(e));for(n=this,u=r[1];;){if(!0&f&&(u=u.times(n),--f),0===f)break;f/=2,n=n.square()}return u},o.prototype.pow=e.prototype.pow,e.prototype.modPow=function(t,e){if(t=N(t),(e=N(e)).isZero())throw new Error("Cannot take modPow with modulus 0");for(var n=r[1],o=this.mod(e);t.isPositive();){if(o.isZero())return r[0];t.isOdd()&&(n=n.multiply(o).mod(e)),t=t.divide(2),o=o.square().mod(e)}return n},o.prototype.modPow=e.prototype.modPow,e.prototype.compareAbs=function(t){var r=N(t),e=this.value,n=r.value;return r.isSmall?1:j(e,n)},o.prototype.compareAbs=function(t){var r=N(t),e=Math.abs(this.value),n=r.value;return r.isSmall?(n=Math.abs(n),e===n?0:e>n?1:-1):-1},e.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var r=N(t),e=this.value,n=r.value;return this.sign!==r.sign?r.sign?1:-1:r.isSmall?this.sign?-1:1:j(e,n)*(this.sign?-1:1)},e.prototype.compareTo=e.prototype.compare,o.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var r=N(t),e=this.value,n=r.value;return r.isSmall?e==n?0:e>n?1:-1:e<0!==r.sign?e<0?-1:1:e<0?1:-1},o.prototype.compareTo=o.prototype.compare,e.prototype.equals=function(t){return 0===this.compare(t)},o.prototype.eq=o.prototype.equals=e.prototype.eq=e.prototype.equals,e.prototype.notEquals=function(t){return 0!==this.compare(t)},o.prototype.neq=o.prototype.notEquals=e.prototype.neq=e.prototype.notEquals,e.prototype.greater=function(t){return this.compare(t)>0},o.prototype.gt=o.prototype.greater=e.prototype.gt=e.prototype.greater,e.prototype.lesser=function(t){return this.compare(t)<0},o.prototype.lt=o.prototype.lesser=e.prototype.lt=e.prototype.lesser,e.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},o.prototype.geq=o.prototype.greaterOrEquals=e.prototype.geq=e.prototype.greaterOrEquals,e.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},o.prototype.leq=o.prototype.lesserOrEquals=e.prototype.leq=e.prototype.lesserOrEquals,e.prototype.isEven=function(){return 0==(1&this.value[0])},o.prototype.isEven=function(){return 0==(1&this.value)},e.prototype.isOdd=function(){return 1==(1&this.value[0])},o.prototype.isOdd=function(){return 1==(1&this.value)},e.prototype.isPositive=function(){return!this.sign},o.prototype.isPositive=function(){return this.value>0},e.prototype.isNegative=function(){return this.sign},o.prototype.isNegative=function(){return this.value<0},e.prototype.isUnit=function(){return!1},o.prototype.isUnit=function(){return 1===Math.abs(this.value)},e.prototype.isZero=function(){return!1},o.prototype.isZero=function(){return 0===this.value},e.prototype.isDivisibleBy=function(t){var e=N(t),n=e.value;return 0!==n&&(1===n||(2===n?this.isEven():this.mod(e).equals(r[0])))},o.prototype.isDivisibleBy=e.prototype.isDivisibleBy,e.prototype.isPrime=function(){var t=E(this);if(void 0!==t)return t;for(var e,o,i,u,a=this.abs(),s=a.prev(),f=[2,3,5,7,11,13,17,19],c=s;c.isEven();)c=c.divide(2);for(i=0;i-k?new o(t-1):new e(L,!0)};for(var D=[1];D[D.length-1]<=H;)D.push(2*D[D.length-1]);var F=D.length,$=D[F-1];e.prototype.shiftLeft=function(t){if(!O(t))throw new Error(String(t)+" is too large for shifting.");if((t=+t)<0)return this.shiftRight(-t);for(var r=this;t>=F;)r=r.multiply($),t-=F-1;return r.multiply(D[t])},o.prototype.shiftLeft=e.prototype.shiftLeft,e.prototype.shiftRight=function(t){var r;if(!O(t))throw new Error(String(t)+" is too large for shifting.");if((t=+t)<0)return this.shiftLeft(-t);for(var e=this;t>=F;){if(e.isZero())return e;e=(r=A(e,$))[1].isNegative()?r[0].prev():r[0],t-=F-1}return(r=A(e,D[t]))[1].isNegative()?r[0].prev():r[0]},o.prototype.shiftRight=e.prototype.shiftRight,e.prototype.not=function(){return this.negate().prev()},o.prototype.not=e.prototype.not,e.prototype.and=function(t){return M(this,t,function(t,r){return t&r})},o.prototype.and=e.prototype.and,e.prototype.or=function(t){return M(this,t,function(t,r){return t|r})},o.prototype.or=e.prototype.or,e.prototype.xor=function(t){return M(this,t,function(t,r){return t^r})},o.prototype.xor=e.prototype.xor;var z=1<<30,K=(H&-H)*(H&-H)|z,J=function(t,r){for(var e=t.length,n=Math.abs(r),i=0;i=n){if("1"===f&&1===n)continue;throw new Error(f+" is not a valid digit in base "+r+".")}if(f.charCodeAt(0)-87>=n)throw new Error(f+" is not a valid digit in base "+r+".")}}if(2<=r&&r<=36&&e<=Z/Math.log(r)){var u=parseInt(t,r);if(isNaN(u))throw new Error(f+" is not a valid digit in base "+r+".");return new o(parseInt(t,r))}r=N(r);var a=[],s="-"===t[0];for(i=s?1:0;i"!==t[i]);a.push(N(t.slice(p+1,i)))}}return T(a,r,s)};e.prototype.toString=function(t){if(void 0===t&&(t=10),10!==t)return C(this,t);for(var r,e=this.value,n=e.length,o=String(e[--n]);--n>=0;)r=String(e[n]),o+="0000000".slice(r.length)+r;return(this.sign?"-":"")+o},o.prototype.toString=function(t){return void 0===t&&(t=10),10!=t?C(this,t):String(this.value)},e.prototype.toJSON=o.prototype.toJSON=function(){return this.toString()},e.prototype.valueOf=function(){return+this.toString()},e.prototype.toJSNumber=e.prototype.valueOf,o.prototype.valueOf=function(){return this.value},o.prototype.toJSNumber=o.prototype.valueOf;for(var V=0;V<1e3;V++)r[V]=new o(V),V>0&&(r[-V]=new o(-V));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=q,r.min=P,r.gcd=U,r.lcm=function(t,r){return t=N(t).abs(),r=N(r).abs(),t.divide(U(t,r)).multiply(r)},r.isInstance=function(t){return t instanceof e||t instanceof o},r.randBetween=function(t,r){var n=P(t=N(t),r=N(r)),i=q(t,r).subtract(n);if(i.isSmall)return n.add(Math.round(Math.random()*i));for(var u=[],s=!0,f=i.value.length-1;f>=0;f--){var p=s?i.value[f]:H,l=c(Math.random()*p);u.unshift(l),l?@[\\]^_`{|}~"};r.exports={getSetOfCharacters:function(t){if(void 0===t)return o.lowercase+o.uppercase+o.digits+o.symbols;var r="";return t.forEach(function(t){r+=o[t]}),r},getOneCharPerRule:function(t,r){var e="";return r.forEach(function(r){var i=n("",t,o[r],1);e+=i.value,t=i.entropy}),{value:e,entropy:t}},insertStringPseudoRandomly:function(t,r,e){for(var n=0;n=o)return{value:t,entropy:r};var i=r.divmod(e.length);return t+=e[i.remainder],n(t,i.quotient,e,o)}r.exports={consumeEntropy:n}},{}],4:[function(t,r,e){var n=t("big-integer"),o=t("./chars"),i=t("./entropy").consumeEntropy;r.exports=function(t,r){var e=o.getRules(r),u=o.getSetOfCharacters(e),a=i("",n(t,16),u,r.length-e.length),s=o.getOneCharPerRule(a.entropy,e);return o.insertStringPseudoRandomly(a.value,s.entropy,s.value)}},{"./chars":2,"./entropy":3,"big-integer":1}],5:[function(t,r,e){(function(t){function n(t,r){for(var e=-1,n=t?t.length:0;++e-1&&t%1==0&&t-1&&t%1==0&&t<=k}function C(t){var r=typeof t;return!!t&&("object"==r||"function"==r)}function I(t){return!!t&&"object"==typeof t}function N(t){return P(t)?h(t):function(t){if(!O(t))return Ft(t);var r=[];for(var e in Object(t))Pt.call(t,e)&&"constructor"!=e&&r.push(e);return r}(t)}var H=200,R="__lodash_hash_undefined__",k=9007199254740991,L="[object Arguments]",Z="[object Boolean]",D="[object Date]",F="[object Function]",$="[object GeneratorFunction]",z="[object Map]",K="[object Number]",J="[object Object]",V="[object RegExp]",W="[object Set]",G="[object String]",Q="[object Symbol]",X="[object WeakMap]",Y="[object ArrayBuffer]",tt="[object DataView]",rt="[object Float32Array]",et="[object Float64Array]",nt="[object Int8Array]",ot="[object Int16Array]",it="[object Int32Array]",ut="[object Uint8Array]",at="[object Uint8ClampedArray]",st="[object Uint16Array]",ft="[object Uint32Array]",ct=/\w*$/,pt=/^\[object .+?Constructor\]$/,lt=/^(?:0|[1-9]\d*)$/,ht={};ht[rt]=ht[et]=ht[nt]=ht[ot]=ht[it]=ht[ut]=ht[at]=ht[st]=ht[ft]=!0,ht[L]=ht["[object Array]"]=ht[Y]=ht[Z]=ht[tt]=ht[D]=ht["[object Error]"]=ht[F]=ht[z]=ht[K]=ht[J]=ht[V]=ht[W]=ht[G]=ht[X]=!1;var vt={};vt[L]=vt["[object Array]"]=vt[Y]=vt[tt]=vt[Z]=vt[D]=vt[rt]=vt[et]=vt[nt]=vt[ot]=vt[it]=vt[z]=vt[K]=vt[J]=vt[V]=vt[W]=vt[G]=vt[Q]=vt[ut]=vt[at]=vt[st]=vt[ft]=!0,vt["[object Error]"]=vt[F]=vt[X]=!1;var yt="object"==typeof t&&t&&t.Object===Object&&t,gt="object"==typeof self&&self&&self.Object===Object&&self,dt=yt||gt||Function("return this")(),bt="object"==typeof e&&e&&!e.nodeType&&e,wt=bt&&"object"==typeof r&&r&&!r.nodeType&&r,mt=wt&&wt.exports===bt,_t=mt&&yt.process,St=function(){try{return _t&&_t.binding("util")}catch(t){}}(),At=St&&St.isTypedArray,jt=Array.prototype,Et=Function.prototype,Ot=Object.prototype,Mt=dt["__core-js_shared__"],xt=function(){var t=/[^.]+$/.exec(Mt&&Mt.keys&&Mt.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),qt=Et.toString,Pt=Ot.hasOwnProperty,Ut=qt.call(Object),Tt=Ot.toString,Bt=RegExp("^"+qt.call(Pt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ct=mt?dt.Buffer:void 0,It=dt.Symbol,Nt=dt.Uint8Array,Ht=a(Object.getPrototypeOf,Object),Rt=Object.create,kt=Ot.propertyIsEnumerable,Lt=jt.splice,Zt=Object.getOwnPropertySymbols,Dt=Ct?Ct.isBuffer:void 0,Ft=a(Object.keys,Object),$t=Math.max,zt=j(dt,"DataView"),Kt=j(dt,"Map"),Jt=j(dt,"Promise"),Vt=j(dt,"Set"),Wt=j(dt,"WeakMap"),Gt=j(Object,"create"),Qt=M(zt),Xt=M(Kt),Yt=M(Jt),tr=M(Vt),rr=M(Wt),er=It?It.prototype:void 0,nr=er?er.valueOf:void 0;f.prototype.clear=function(){this.__data__=Gt?Gt(null):{}},f.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},f.prototype.get=function(t){var r=this.__data__;if(Gt){var e=r[t];return e===R?void 0:e}return Pt.call(r,t)?r[t]:void 0},f.prototype.has=function(t){var r=this.__data__;return Gt?void 0!==r[t]:Pt.call(r,t)},f.prototype.set=function(t,r){return this.__data__[t]=Gt&&void 0===r?R:r,this},c.prototype.clear=function(){this.__data__=[]},c.prototype.delete=function(t){var r=this.__data__,e=g(r,t);return!(e<0||(e==r.length-1?r.pop():Lt.call(r,e,1),0))},c.prototype.get=function(t){var r=this.__data__,e=g(r,t);return e<0?void 0:r[e][1]},c.prototype.has=function(t){return g(this.__data__,t)>-1},c.prototype.set=function(t,r){var e=this.__data__,n=g(e,t);return n<0?e.push([t,r]):e[n][1]=r,this},p.prototype.clear=function(){this.__data__={hash:new f,map:new(Kt||c),string:new f}},p.prototype.delete=function(t){return A(this,t).delete(t)},p.prototype.get=function(t){return A(this,t).get(t)},p.prototype.has=function(t){return A(this,t).has(t)},p.prototype.set=function(t,r){return A(this,t).set(t,r),this},l.prototype.clear=function(){this.__data__=new c},l.prototype.delete=function(t){return this.__data__.delete(t)},l.prototype.get=function(t){return this.__data__.get(t)},l.prototype.has=function(t){return this.__data__.has(t)},l.prototype.set=function(t,r){var e=this.__data__;if(e instanceof c){var n=e.__data__;if(!Kt||n.length1?e[o-1]:void 0,u=o>2?e[2]:void 0;for(i=t.length>3&&"function"==typeof i?(o--,i):void 0,u&&function(t,r,e){if(!C(e))return!1;var n=typeof r;return!!("number"==n?P(e)&&E(r,e.length):"string"==n&&r in e)&&x(e[r],t)}(e[0],e[1],u)&&(i=o<3?void 0:i,o=1),r=Object(r);++n dist/lesspass.js && npm run minify", "minify": "uglifyjs --output dist/lesspass.min.js --compress --mangle -- dist/lesspass.js", @@ -31,20 +31,20 @@ "test:browser": "npm run build && karma start test/karma.conf.js" }, "dependencies": { - "big-integer": "^1.6.22", + "lesspass-render-password": "^0.1.0", "lodash.merge": "^4.6.0", - "unibabel": "^2.1.4" + "unibabel": "2.1.4" }, "devDependencies": { "browserify": "^14.3.0", - "husky": "^0.13.3", + "husky": "^0.14.3", "karma": "^1.6.0", "karma-browserify": "^5.1.1", "karma-chrome-launcher": "^2.0.0", "karma-firefox-launcher": "^1.0.1", "karma-mocha": "^1.3.0", - "lint-staged": "^3.4.1", - "mocha": "^3.3.0", + "lint-staged": "^4.3.0", + "mocha": "^4.0.1", "prettier": "^1.2.2", "uglify-js": "^3.0.1" }, diff --git a/src/lesspass.js b/src/lesspass.js index f50b0e1..4795303 100644 --- a/src/lesspass.js +++ b/src/lesspass.js @@ -1,11 +1,11 @@ var hmac = require("./hmac"); var pbkdf2 = require("./pbkdf2"); -var bigInt = require("big-integer"); var merge = require("lodash.merge"); +var renderPassword = require("lesspass-render-password"); var defaultProfile = { - site: '', - login: '', + site: "", + login: "", options: { uppercase: true, lowercase: true, @@ -15,7 +15,7 @@ var defaultProfile = { counter: 1 }, crypto: { - method: 'pbkdf2', + method: "pbkdf2", iterations: 100000, keylen: 32, digest: "sha256" @@ -26,21 +26,14 @@ module.exports = { generatePassword: generatePassword, createFingerprint: createFingerprint, isSupported: isSupported, - _calcEntropy: calcEntropy, - _consumeEntropy: consumeEntropy, - _getSetOfCharacters: getSetOfCharacters, - _getConfiguredRules: getConfiguredRules, - _insertStringPseudoRandomly: insertStringPseudoRandomly, - _getOneCharPerRule: getOneCharPerRule, - _renderPassword: renderPassword + _calcEntropy: _calcEntropy }; function generatePassword(profile, masterPassword) { var _profile = merge({}, defaultProfile, profile); - return calcEntropy(_profile, masterPassword) - .then(function(entropy) { - return renderPassword(entropy, _profile.options); - }); + return _calcEntropy(_profile, masterPassword).then(function(entropy) { + return renderPassword(entropy, _profile.options); + }); } function createFingerprint(str) { @@ -49,19 +42,23 @@ function createFingerprint(str) { function isSupported() { try { - var simpleProfile = merge({}, defaultProfile, {crypto: {iterations: 1}}); - return generatePassword(simpleProfile, 'LessPass') - .then(function(generatedPassword) { - return generatedPassword == "n'LTsjPA#3E$e*2'"; - }); + var simpleProfile = merge({}, defaultProfile, { + crypto: { iterations: 1 } + }); + return generatePassword(simpleProfile, "LessPass").then(function( + generatedPassword + ) { + return generatedPassword === "n'LTsjPA#3E$e*2'"; + }); } catch (e) { console.error(e); return Promise.resolve(false); } } -function calcEntropy(profile, masterPassword) { - var salt = profile.site + profile.login + profile.options.counter.toString(16); +function _calcEntropy(profile, masterPassword) { + var salt = + profile.site + profile.login + profile.options.counter.toString(16); return pbkdf2( masterPassword, salt, @@ -70,88 +67,3 @@ function calcEntropy(profile, masterPassword) { profile.crypto.digest ); } - -var characterSubsets = { - lowercase: "abcdefghijklmnopqrstuvwxyz", - uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - digits: "0123456789", - symbols: "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" -}; - -function getSetOfCharacters(rules) { - if (typeof rules === "undefined") { - return ( - characterSubsets.lowercase + - characterSubsets.uppercase + - characterSubsets.digits + - characterSubsets.symbols - ); - } - var setOfChars = ""; - rules.forEach(function(rule) { - setOfChars += characterSubsets[rule]; - }); - return setOfChars; -} - -function consumeEntropy(generatedPassword, - quotient, - setOfCharacters, - maxLength) { - if (generatedPassword.length >= maxLength) { - return {value: generatedPassword, entropy: quotient}; - } - var longDivision = quotient.divmod(setOfCharacters.length); - generatedPassword += setOfCharacters[longDivision.remainder]; - return consumeEntropy( - generatedPassword, - longDivision.quotient, - setOfCharacters, - maxLength - ); -} - -function insertStringPseudoRandomly(generatedPassword, entropy, string) { - for (var i = 0; i < string.length; i++) { - var longDivision = entropy.divmod(generatedPassword.length); - generatedPassword = - generatedPassword.slice(0, longDivision.remainder) + - string[i] + - generatedPassword.slice(longDivision.remainder); - entropy = longDivision.quotient; - } - return generatedPassword; -} - -function getOneCharPerRule(entropy, rules) { - var oneCharPerRules = ""; - rules.forEach(function(rule) { - var password = consumeEntropy("", entropy, characterSubsets[rule], 1); - oneCharPerRules += password.value; - entropy = password.entropy; - }); - return {value: oneCharPerRules, entropy: entropy}; -} - -function getConfiguredRules(passwordProfile) { - return ["lowercase", "uppercase", "digits", "symbols"].filter(function(rule) { - return passwordProfile[rule]; - }); -} - -function renderPassword(entropy, passwordProfile) { - var rules = getConfiguredRules(passwordProfile); - var setOfCharacters = getSetOfCharacters(rules); - var password = consumeEntropy( - "", - bigInt(entropy, 16), - setOfCharacters, - passwordProfile.length - rules.length - ); - var charactersToAdd = getOneCharPerRule(password.entropy, rules); - return insertStringPseudoRandomly( - password.value, - charactersToAdd.entropy, - charactersToAdd.value - ); -} diff --git a/test/entropy.tests.js b/test/entropy.tests.js index be7d3f6..c18c296 100644 --- a/test/entropy.tests.js +++ b/test/entropy.tests.js @@ -1,6 +1,5 @@ var assert = require("assert"); var LessPass = require("../src/lesspass"); -var bigInt = require("big-integer"); describe("entropy", function() { it("calc entropy pbkdf2 with default params (100000 iterations, 32 bytes length, sha256 digest)", function() { @@ -11,20 +10,21 @@ describe("entropy", function() { counter: 1 }, crypto: { - method: 'pbkdf2', + method: "pbkdf2", iterations: 100000, keylen: 32, digest: "sha256" } }; const masterPassword = "password"; - return LessPass._calcEntropy(profile, masterPassword) - .then(function(entropy) { - assert.equal( - "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e", - entropy - ); - }); + return LessPass._calcEntropy(profile, masterPassword).then(function( + entropy + ) { + assert.equal( + "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e", + entropy + ); + }); }); it("calc entropy with different options (8192 iterations, 16 bytes length, sha512 digest)", function() { const profile = { @@ -34,17 +34,18 @@ describe("entropy", function() { counter: 1 }, crypto: { - method: 'pbkdf2', + method: "pbkdf2", iterations: 8192, keylen: 16, digest: "sha512" } }; const masterPassword = "password"; - return LessPass._calcEntropy(profile, masterPassword) - .then(function(entropy) { - assert.equal("fff211c16a4e776b3574c6a5c91fd252", entropy); - }); + return LessPass._calcEntropy(profile, masterPassword).then(function( + entropy + ) { + assert.equal("fff211c16a4e776b3574c6a5c91fd252", entropy); + }); }); it("calc entropy different if counter different 1", function() { const profile = { @@ -54,7 +55,7 @@ describe("entropy", function() { counter: 1 }, crypto: { - method: 'pbkdf2', + method: "pbkdf2", iterations: 100000, keylen: 32, digest: "sha256" @@ -67,7 +68,7 @@ describe("entropy", function() { counter: 2 }, crypto: { - method: 'pbkdf2', + method: "pbkdf2", iterations: 100000, keylen: 32, digest: "sha256" @@ -75,15 +76,10 @@ describe("entropy", function() { }; const promises = [ LessPass._calcEntropy(profile, "password"), - LessPass._calcEntropy(profile2, "password"), + LessPass._calcEntropy(profile2, "password") ]; Promise.all(promises).then(values => { assert.notEqual(values[0], values[1]); }); }); - it("consume entropy", function() { - var password = LessPass._consumeEntropy("", bigInt(4 * 4 + 2), "abcd", 2); - assert.equal("ca", password.value); - assert.equal(1, password.entropy); - }); }); diff --git a/test/renderPassword.tests.js b/test/renderPassword.tests.js deleted file mode 100644 index 499875a..0000000 --- a/test/renderPassword.tests.js +++ /dev/null @@ -1,99 +0,0 @@ -const assert = require("assert"); -const LessPass = require("../src/lesspass"); -const bigInt = require("big-integer"); - -describe("LessPass LessPass", function() { - const defaultPasswordProfile = { - length: 16, - lowercase: true, - uppercase: true, - digits: true, - symbols: true - }; - it("render password use remainder of long division beetween entropy and set of chars length as an index", function() { - const entropy = - "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; - assert.equal("W", LessPass._renderPassword(entropy, defaultPasswordProfile)[0]); - }); - it("render password use quotient as second entropy recursively", function() { - const entropy = - "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; - assert.equal("H", LessPass._renderPassword(entropy, defaultPasswordProfile)[1]); - }); - it("render password has default length of 16", function() { - const entropy = - "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; - assert.equal( - 16, - LessPass._renderPassword(entropy, defaultPasswordProfile).length - ); - }); - it("render password can specify length", function() { - const entropy = - "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; - const passwordProfile = { - length: 20, - lowercase: true, - uppercase: true, - digits: true, - symbols: true - }; - assert.equal(20, LessPass._renderPassword(entropy, passwordProfile).length); - }); - it("include one char per set of characters", function() { - const password = LessPass._insertStringPseudoRandomly( - "123456", - bigInt(7 * 6 + 2), - "uT" - ); - assert.equal("T12u3456", password); - }); - it("render password return at least one char in every characters set", function() { - const entropy = - "dc33d431bce2b01182c613382483ccdb0e2f66482cbba5e9d07dab34acc7eb1e"; - const passwordProfile = { - length: 6, - lowercase: true, - uppercase: true, - digits: true, - symbols: true - }; - const generatedPassword = LessPass._renderPassword(entropy, passwordProfile); - let passwordLength = generatedPassword.length; - let lowercaseOk = false; - let uppercaseOk = false; - let digitsOk = false; - let symbolsOk = false; - while (passwordLength--) { - if ( - "abcdefghijklmnopqrstuvwxyz".indexOf( - generatedPassword[passwordLength] - ) !== -1 - ) { - lowercaseOk = true; - } - if ( - "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( - generatedPassword[passwordLength] - ) !== -1 - ) { - uppercaseOk = true; - } - if ("0123456789".indexOf(generatedPassword[passwordLength]) !== -1) { - digitsOk = true; - } - if ( - "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".indexOf( - generatedPassword[passwordLength] - ) !== -1 - ) { - symbolsOk = true; - } - } - assert.equal(6, generatedPassword.length); - assert( - lowercaseOk && uppercaseOk && digitsOk && symbolsOk, - "there is no at least one char in every characters set" - ); - }); -}); diff --git a/test/setOfCharacters.tests.js b/test/setOfCharacters.tests.js deleted file mode 100644 index e1597f3..0000000 --- a/test/setOfCharacters.tests.js +++ /dev/null @@ -1,78 +0,0 @@ -var assert = require("assert"); -var LessPass = require("../src/lesspass"); -var bigInt = require("big-integer"); - -describe("set of characters", function() { - it("get default set of characters", function() { - var setOfCharacters = LessPass._getSetOfCharacters(); - assert.equal( - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", - setOfCharacters - ); - assert.equal(26 * 2 + 10 + 32, setOfCharacters.length); - }); - it("get default set of characters concat rules in order", function() { - var setOfCharacters = LessPass._getSetOfCharacters([ - "lowercase", - "uppercase", - "digits" - ]); - assert.equal( - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", - setOfCharacters - ); - assert.equal(26 * 2 + 10, setOfCharacters.length); - }); - it("get set of characters only lowercase", function() { - var setOfCharacters = LessPass._getSetOfCharacters(["lowercase"]); - assert.equal("abcdefghijklmnopqrstuvwxyz", setOfCharacters); - assert.equal(26, setOfCharacters.length); - }); - it("get set of characters only uppercase", function() { - var setOfCharacters = LessPass._getSetOfCharacters(["uppercase"]); - assert.equal("ABCDEFGHIJKLMNOPQRSTUVWXYZ", setOfCharacters); - assert.equal(26, setOfCharacters.length); - }); - it("get set of characters only digits", function() { - var setOfCharacters = LessPass._getSetOfCharacters(["digits"]); - assert.equal("0123456789", setOfCharacters); - assert.equal(10, setOfCharacters.length); - }); - it("get set of characters only symbols", function() { - var setOfCharacters = LessPass._getSetOfCharacters(["symbols"]); - assert.equal("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", setOfCharacters); - assert.equal(32, setOfCharacters.length); - }); - it("generate one char per rules", function() { - var oneCharPerSetOfCharacters = LessPass._getOneCharPerRule(bigInt(26 * 26), [ - "lowercase", - "uppercase" - ]); - assert.equal("aA", oneCharPerSetOfCharacters.value); - assert.equal(2, oneCharPerSetOfCharacters.value.length); - assert.equal(1, oneCharPerSetOfCharacters.entropy); - }); - it("configured rules", function() { - assert.deepEqual( - ["uppercase"], - LessPass._getConfiguredRules({ uppercase: true }) - ); - assert.deepEqual( - ["lowercase", "uppercase"], - LessPass._getConfiguredRules({ uppercase: true, lowercase: true }) - ); - assert.deepEqual( - ["lowercase"], - LessPass._getConfiguredRules({ lowercase: true, symbols: false }) - ); - assert.deepEqual( - ["lowercase", "uppercase", "digits", "symbols"], - LessPass._getConfiguredRules({ - lowercase: true, - uppercase: true, - symbols: true, - digits: true - }) - ); - }); -});