Initial commit
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2cc3e2a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+dist/
+npm-debug.log
+bower_components/
+nbproject/
+test/coverage.html
+mocha.json
diff --git a/Gruntfile.js b/Gruntfile.js
new file mode 100644
index 0000000..8562817
--- /dev/null
+++ b/Gruntfile.js
@@ -0,0 +1,48 @@
+module.exports = function(grunt) {
+	grunt.initConfig({
+		pkg: grunt.file.readJSON('package.json'),
+		concat: {
+		    options: {
+				separator: ';'
+			},
+			mergeJs: {
+				src: ['bower_components/amcl/js/DBIG.js','bower_components/amcl/js/BIG.js', 'bower_components/amcl/js/FP.js', 'bower_components/amcl/js/ROM.js', 'bower_components/amcl/js/HASH.js', 'bower_components/amcl/js/RAND.js', 'bower_components/amcl/js/AES.js', 'bower_components/amcl/js/GPM.js', 'bower_components/amcl/js/ECP.js', 'bower_components/amcl/js/FP2.js', 'bower_components/amcl/js/ECP2.js', 'bower_components/amcl/js/FP4.js', 'bower_components/amcl/js/FP12.js', 'bower_components/amcl/js/PAIR.js', 'bower_components/amcl/js/MPIN.js', 'bower_components/amcl/js/MPINAuth.js', 'lib/mpin.js'],
+				dest: './dist/mpinjs.js'
+			}
+		},
+		bgShell: {
+			createDir: {
+				cmd: "mkdir -p ./dist",
+				options: {
+	            	stdout: true
+				}
+			},
+			test: {
+				cmd: 'mocha',
+				options: {
+					stdout: true
+				}
+			},
+			testCoverage: {
+				cmd: 'mocha test --require blanket --reporter html-cov > test/coverage.html',
+				options: {
+					stdout: true
+				}
+			},
+			bowerInstall: {
+				cmd: 'bower install --allow-root',
+				options: {
+					stdout: true
+				}
+			}
+		}
+	});
+	
+	grunt.loadNpmTasks('grunt-bg-shell');
+	grunt.loadNpmTasks('grunt-contrib-concat');
+
+	grunt.registerTask('build',  ['bgShell:createDir', 'bgShell:bowerInstall', 'concat']);
+	grunt.registerTask('chk',  ['bgShell:createDir', 'bgShell:bowerInstall', 'concat']);
+	grunt.registerTask('test',  ['bgShell:test']);
+	grunt.registerTask('testCover',  ['bgShell:testCoverage']);
+};
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..2518265
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,200 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License. 
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..e7c2e4e
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,5 @@
+Milagro MFA JavaScript Client Library
+Copyright 2015 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..7bdcacf
--- /dev/null
+++ b/README.md
@@ -0,0 +1,83 @@
+# Headless M-Pin Client Library
+
+## Requirement for build & testing
+
+1. Nodejs
+2. Grunt
+3. Mocha
+4. Bower
+
+## Installation
+
+```bash
+$ git clone
+$ cd project_folder
+$ npm install
+$ grunt build
+```
+
+## Simple usage example
+
+- Registration
+
+```js
+var mpin = mpinjs({server: <serverIP-and-port>});
+
+mpin.init(<callback>);
+
+mpin.makeNewUser(<userId>);
+
+mpin.startRegistration(<userId>, <callback>);
+
+/* Wait for end-user to confirm identity */
+
+mpin.confirmRegistration(<userId>, <callback>);
+
+/* If successful, read desired user secret (PIN or password) */
+
+mpin.finishRegistration(<userId>, <user-secret>);
+
+```
+- Authentication
+
+```js
+mpin.startAuthentication(<userId>, <callback>);
+
+/* If successful, read user secret (PIN or password) */
+
+mpin.finishAuthentication(<userId>, <user-secret>, <callback>);
+```
+
+- Authentication with a mobile device
+
+```js
+mpin.getAccessNumber(<callback>);
+
+/* Display Access number to end user */
+
+mpin.waitForMobileAuth(<timeout-sec>, <retry-period-sec>, <callback>);
+
+/*
+   If successfull - Authentication completed
+   If exits with timeout, then no successfull authentication from mobile device was completed
+   If one needs to cancel the waiting for authentication from the mobile device, call cancelMobileAuth()
+*/
+```
+
+## Running Tests
+
+Install development dependencies:
+
+```bash
+$ npm install
+```
+
+Then:
+
+```bash
+$ npm test
+```
+
+Actively tested with node:
+
+  - 0.10.4
diff --git a/bower.json b/bower.json
new file mode 100644
index 0000000..57b92b0
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,18 @@
+{
+	"name": "mpinjs",
+	"version": "1.0.0",
+	"description": "Mpin lib front-end project",
+	"authors": [
+		"MIRACL"
+	],
+	"dependencies": {
+		"amcl": "https://github.com/miracl/mpin-crypto.git"
+	},
+	"ignore": [
+		"**/*",
+		"!lib/mpin.js"
+	],
+	"moduleType": "globals",
+	"main": "lib/mpin.js",
+	"homepage": "www.miracl.com"
+}
diff --git a/example/exampleJquery.html b/example/exampleJquery.html
new file mode 100644
index 0000000..5db8efe
--- /dev/null
+++ b/example/exampleJquery.html
@@ -0,0 +1,265 @@
+<!DOCTYPE html>

+<!--

+To change this license header, choose License Headers in Project Properties.

+To change this template file, choose Tools | Templates

+and open the template in the editor.

+-->

+<html>

+  <head>

+    <title>Mpin JS SDK</title>

+    <meta charset="UTF-8">

+    <meta name="viewport" content="width=device-width, initial-scale=1.0">

+		<script src="../dist/mpinjs.js" type="text/javascript"></script>

+		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js" type="text/javascript"></script>

+

+		<style>

+			fieldset {

+				margin: 0 auto;

+				width: 50%;

+			}

+

+			.notActivate {

+				color: red;

+				cursor: pointer;

+			}

+

+			.smallInput {

+				width: 100px;

+			}

+		</style>

+

+		<script type="text/javascript">

+      $(document).ready(function () {

+

+        //// MPIN init

+        window.mpin = mpin = new mpinjs({

+          server: "http://ssodemo.certivox.com"

+        });

+

+        mpin.init(function (err, data) {

+          if (err) {

+            console.error("Wrong setup : ", err);

+          }

+

+          listUsers();

+        });

+

+        function listUsers () {

+          var mpinUsers = mpin.listUsers(), htmlList;

+

+          htmlList = "<ul>";

+          for (var i in mpinUsers) {

+            htmlList += "<li>" + mpinUsers[i].userId + "&nbsp;&nbsp;&nbsp;";

+            htmlList += "<input type='text' placeholder='PIN' size='10' class='userPin'>&nbsp;&nbsp;&nbsp;";

+            if (mpinUsers[i].state === "REGISTERED") {

+              htmlList += "<span class='registered' data-userid='" + mpinUsers[i].userId + "' data-state='" + mpinUsers[i].state + "'>Authenticate</span>";

+              htmlList += "<div style='float: right'><input type='text' placeholder='Access Number' size='10' class='userAN'>&nbsp;&nbsp;&nbsp;";

+              htmlList += "<span class='auth-accnumber' data-userid='" + mpinUsers[i].userId + "'>Authenticate(AN)</span></div>";

+            } else {

+              htmlList += "<span class='setup' data-userid='" + mpinUsers[i].userId + "' data-state='" + mpinUsers[i].state + "'>Setup</span>";

+            }

+            htmlList += "</span></li>";

+          }

+          htmlList += "<ul>";

+

+          $("#mpinUsers").html(htmlList);

+        }

+

+

+        $(document).on('click', ".setup", function (ev) {

+          var thisElem, userId, userPin, state;

+

+          thisElem = $(ev.currentTarget);

+          userId = thisElem.data('userid');

+          userPin = thisElem.prev("input").val();

+          state = thisElem.data('state');

+

+          mpin.startRegistration(userId, function (err3, data3) {

+            mpin.confirmRegistration(userId, function (err, data) {

+              if (err) {

+                console.error("Error :1::", err);

+                return;

+              }

+

+              var finish = mpin.finishRegistration(userId, userPin);

+              if (finish.error) {

+                console.error("Error :::", finish.error);

+                return;

+              }

+

+              thisElem.append(" :: Successful");

+            });

+

+          });

+

+        });

+

+

+        $(document).on('click', ".registered", function (ev) {

+          var userId, userPin, state;

+          userId = $(ev.currentTarget).data('userid');

+          userPin = $(ev.currentTarget).prev("input.userPin").val();

+          state = $(ev.currentTarget).data('state');

+

+          mpin.startAuthentication(userId, function (err, data) {

+            if (err) {

+              console.error("Error :::", err);

+              return;

+            }

+

+            mpin.finishAuthentication(userId, userPin, function (err2, data2) {

+              if (err2) {

+                console.error("Error :::", err2);

+                return;

+              }

+

+              $(ev.currentTarget).append(" :: Successful");

+            });

+          });

+        });

+

+

+        $(document).on('click', ".auth-accnumber", function (ev) {

+          var userId, userPin, userAN;

+          userId = $(ev.currentTarget).data('userid');

+					userPin = $(ev.currentTarget).parents("li").find("input.userPin").val();

+					userAN = $(ev.currentTarget).prev("input.userAN").val();

+					

+					if (!mpin.checkAccessNumber(userAN)) {

+						$(".errAccessNumber").remove();

+						$(ev.currentTarget).prepend("<span style='color: red' class='errAccessNumber'>Invalid Access Number</span>");

+						return;

+					}

+					

+          mpin.startAuthentication(userId, function (err, data) {

+            if (err) {

+              console.error("Error :::", err);

+              return;

+            }

+             mpin.finishAuthenticationAN(userId, userPin, userAN, function (err2, data2) {

+             if (err2) {

+             console.error("Error :::", err2);

+             return;

+             }

+             

+             $(ev.currentTarget).append(" :: Successful");

+             });

+          });

+        });

+

+

+

+

+        $("#regButton").click(function (ev) {

+          var usrId;

+          usrId = $("#mpinUsrId").val();

+

+          if (usrId) {

+            mpin.makeNewUser(usrId);

+            mpin.startRegistration(usrId, function (err, data) {

+              if (err) {

+                return console.error("startRegistration error :::", err);

+              }

+              chkUser(usrId);

+            });

+          }

+

+          ev.stopPropagation();

+        });

+

+

+

+        function chkUser (userId) {

+          var userState = mpin.getUser(userId, "state");

+

+          mpin.confirmRegistration(userId, function (err, data) {

+            //not Active Identity

+            var userElem = $(".usrId[data-userid='" + userId + "']");

+            if (err) {

+              if (userElem.length === 0) {

+                $("#mpinUsersList").append("<li><span class='usrId notActivate' data-userid='" + userId + "'>" + userId + "</span>&nbsp;&nbsp;&nbsp;<input class='smallInput' type='text' placeholder='user Pin'></li>");

+              }

+              return;

+            }

+

+            if (userElem.length === 0) {

+              $("#mpinUsersList").append("<li><span class='usrId notActivate' data-userid='" + userId + "'>" + userId + "</span>&nbsp;&nbsp;&nbsp;<input class='smallInput' type='text' placeholder='user Pin'></li>");

+            }

+

+            var usrPin = userElem.next("input").val();

+            console.log("usrPin :::", usrPin);

+            if (usrPin) {

+              var finish = mpin.finishRegistration(userId, usrPin);

+              if (!finish.error) {

+                userElem.removeClass("notActivate");

+

+                userElem.next("input").remove();

+                userElem.append("&nbsp;&nbsp;&nbsp;>> SETUP DONE");

+

+              } else {

+                console.error("::: OPs something goes wrong.", finish.error);

+              }

+            }

+//						var final = mpin.finishRegistration(userId, 1234);

+            console.log(".: done CONFIRM registration. NOW FINISH");

+          });

+        }

+

+        //live bind click for setup user

+        $(document).on('click', '.usrId', function (ev) {

+          var usrId;

+          usrId = $(this).data('userid');

+

+          chkUser(usrId);

+

+          ev.stopPropagation();

+        });

+

+

+        //// Mobile auth

+        $("#waitMobile").click(function () {

+          var totalTime, requestTime;

+          totalTime = $("#totalTime").val() || 30;

+          requestTime = $("#requestTime").val();

+

+          mpin.getAccessNumber(function (err, data) {

+            $("#mobileStatus").append("Access number: &nbsp;" + data.accessNumber + "<br>");

+            mpin.waitForMobileAuth(totalTime, requestTime, function (err, data) {

+              if (err) {

+                $("#mobileStatus").append(" Pending mobile authentication finish with " + err.type + "<br>");

+                return;

+              }

+              $("#mobileStatus").append(" Login successful");

+            });

+          });

+        });

+

+      });

+		</script>

+

+  </head>

+  <body>

+		<div>Mpin JS SDK </div>

+		<fieldset>

+			<legend>Mpin form:</legend>

+			<input type="text" id="mpinUsrId" placeholder="user id" >

+			<input type="submit" value="Register" id="regButton" style="float:right">

+

+			<h2>Registered users:</h2>

+

+			<div id="mpinUsers"></div>

+			<ul id="mpinUsersList"></ul>

+			<div class="mpinErrors"></div>

+		</fieldset>

+		<br><br>

+		<div style="border: 1px solid grey; margin: 0px auto; width: 50%;">

+

+			Mobile Authentication:<br>

+			<input type="text" id="totalTime" placeholder="Total time in seconds" ><br>

+			<input type="text" id="requestTime" placeholder="per request in seconds" ><br>

+

+			<input type="submit" value="Call" id="waitMobile">

+			<div id="mobileStatus"></div>

+		</div>

+  </body>

+</html>

diff --git a/example/exampleNoJquery.html b/example/exampleNoJquery.html
new file mode 100644
index 0000000..7aab9ce
--- /dev/null
+++ b/example/exampleNoJquery.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>

+<html>

+  <head>

+    <title>Mpinjs example</title>

+    <meta charset="UTF-8">

+    <meta name="viewport" content="width=device-width, initial-scale=1.0">

+		<script src="../dist/mpinjs.js" type="text/javascript"></script>

+  </head>

+  <body>

+		<div>Mpinjs example:</div>

+

+		<span>Setup flow only</span>

+

+		<script type="text/javascript">

+      function step1 () {

+        var usrId = "test@user.de";

+        mpin.makeNewUser(usrId);

+        mpin.startRegistration(usrId, function (err, data) {

+					if (err) {

+						return ;

+					}

+          step2(usrId);

+        });

+      }

+

+      function step2 (userId) {

+        mpin.confirmRegistration(userId, function (err, data) {

+					if (err) {

+						//activate Identity error

+						return ;

+					}

+          step3(userId);

+        });

+      }

+

+      function step3 (userId) {

+        var final = mpin.finishRegistration(userId, 1234);

+				

+      }

+

+      var mpin = new mpinjs({

+        server: "http://192.168.10.63:8005"

+      });

+

+      mpin.init(function (err, data) {

+        step1();

+      });

+

+		</script>

+

+

+  </body>

+</html>

diff --git a/index.js b/index.js
new file mode 100644
index 0000000..e7cdcee
--- /dev/null
+++ b/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/mpin');
\ No newline at end of file
diff --git a/lib/mpin.js b/lib/mpin.js
new file mode 100644
index 0000000..70cb32c
--- /dev/null
+++ b/lib/mpin.js
@@ -0,0 +1,936 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+ 
+ http://www.apache.org/licenses/LICENSE-2.0
+ 
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+
+var mpinjs = (function () {
+  var Mpin, Users = {}, Errors = {}, States = {};
+
+  Errors.missingUserId = {code: 0, type: "MISSING_USERID"};
+  Errors.invalidUserId = {code: 1, type: "INVALID_USERID"};
+  Errors.missingParams = {code: 2, type: "MISSING_PARAMETERS"};
+  Errors.identityNotVerified = {code: 3, type: "IDENTITY_NOT_VERIFIED"};
+  Errors.identityMissing = {code: 4, type: "IDENTITY_MISSING"};
+  Errors.wrongPin = {code: 5, type: "WRONG_PIN"};
+  Errors.wrongFlow = {code: 6, type: "WRONG_FLOW"};
+  Errors.userRevoked = {code: 7, type: "USER_REVOKED"};
+  Errors.timeoutFinish = {code: 8, type: "TIMEOUT_FINISH"};
+  Errors.requestExpired = {code: 9, type: "REQUEST_EXPIRED"};
+  Errors.identityNotAuthorized = {code: 10, type: "IDENTITY_NOT_AUTHORIZED"};
+  Errors.incorrectAccessNumber = {code: 11, type: "INCORRECT_ACCESS_NUMBER"};
+
+  States.invalid = "INVALID";
+  States.start = "STARTED";
+  States.active = "ACTIVATED";
+  States.register = "REGISTERED";
+  States.block = "BLOCKED";
+
+  Mpin = function (options) {
+    if (!options || !options.server) {
+      return new Error("Missing server URL");
+    }
+
+    this.opts = options;
+    this.settings = {};
+
+  };
+
+  Mpin.prototype.storageKey = "mpinjs";
+
+  Mpin.prototype.init = function (cb) {
+    var self = this, _initUrl;
+
+    this.recover();
+    if (this.opts.server.slice(-1) === "/") {
+      _initUrl = this.opts.server;
+    } else {
+      _initUrl = this.opts.server + "/";
+    }
+    _initUrl += this.opts.rpsPrefix || "rps";
+    _initUrl += "/clientSettings";
+
+    this.request({url: _initUrl}, function (err, data) {
+      if (err && cb) {
+        return cb(err, null);
+      }
+
+      self.ready = true;
+      self.settings = data;
+
+      cb && cb(null, true);
+    });
+  };
+
+  Mpin.prototype.makeNewUser = function (userId, deviceId) {
+    if (!userId) {
+      return Errors.missingUserId;
+    }
+
+    this.addToUser(userId, {userId: userId, deviceId: deviceId, state: States.invalid});
+
+    return this;
+  };
+
+  Mpin.prototype.startRegistration = function (userId, cb) {
+    var _reqData = {}, self = this, _userState;
+    if (!userId) {
+      return cb ? cb(Errors.missingUserId, null) : {error: 1};
+    } else if (!this.checkUser(userId)) {
+      return cb(Errors.invalidUserId, null);
+    } else if (!this.settings.registerURL) {
+      return cb({code: Errors.missingParams.code, type: Errors.missingParams.type, message: "Missing registerURL"}, null);
+    }
+
+    //invalid
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.invalid) {
+      return cb(Errors.wrongFlow, null);
+    }
+
+    _reqData.url = this.generateUrl("register");
+    _reqData.type = "PUT";
+    _reqData.data = {
+      userId: userId,
+      mobile: 0
+    };
+
+    if (Users[userId].deviceId) {
+      _reqData.data.deviceName = Users[userId].deviceId;
+    }
+
+    this.request(_reqData, function (err, data) {
+      if (err) {
+        return cb(err, null);
+      }
+
+      self.addToUser(userId, {regOTT: data.regOTT, mpinId: data.mpinId, state: States.start});
+
+      //force activate
+      if (data.active) {
+        self.addToUser(userId, {state: States.active});
+      }
+
+      cb && cb(null, true);
+    });
+  };
+
+  //request cs1 + cs2
+  Mpin.prototype.confirmRegistration = function (userId, cb) {
+    var _cs1Url = "", self = this, _userState;
+    if (!userId) {
+      return cb ? cb(Errors.missingUserId, null) : Errors.missingUserId;
+    } else if (!this.checkUser(userId)) {
+      return cb(Errors.invalidUserId, null);
+    } else if (!this.settings.signatureURL) {
+      return cb({code: Errors.missingParams.code, type: Errors.missingParams.type, message: "Missing signatureURL option."}, null);
+    }
+
+    //started || activated
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.start && _userState !== States.active) {
+      return cb(Errors.wrongFlow, null);
+    }
+
+    //already set.
+    if (Users[userId].csHex) {
+      return cb(null, true);
+    }
+
+    _cs1Url = this.generateUrl('signature', {userId: userId});
+    //req cs1
+    this.request({url: _cs1Url}, function (err, cs1Data) {
+      var _cs2Url = "";
+      if (err) {
+        if (err.status == 401) {
+          return cb(Errors.identityNotVerified, null);
+        } else if (err.status == 400) {
+          return cb(Errors.wrongFlow, null);
+        }
+      }
+
+      _cs2Url = self.settings.certivoxURL + "clientSecret?" + cs1Data.params;
+
+      //req cs2
+      self.request({url: _cs2Url}, function (err, cs2Data) {
+        var csHex;
+
+        csHex = MPINAuth.addShares(cs2Data.clientSecret, cs1Data.clientSecretShare);
+
+        self.addToUser(userId, {csHex: csHex, state: States.active});
+
+        cb(null, true);
+      });
+    });
+  };
+
+  Mpin.prototype.finishRegistration = function (userId, pin) {
+    var _user, token;
+
+    if (!userId) {
+      return Errors.missingUserId;
+    }
+
+    _user = this.getUser(userId);
+
+    if (_user.state !== States.active || !Users[userId].csHex) {
+      return Errors.wrongFlow;
+    }
+
+    if (isNaN(pin)) {
+      pin = this.toHash(pin);
+    }
+
+    token = MPINAuth.calculateMPinToken(Users[userId].mpinId, pin, Users[userId].csHex);
+    delete Users[userId].csHex;
+
+    this.addToUser(userId, {token: token, state: States.register});
+
+    return true;
+  };
+
+  //Put user / mpinId
+  Mpin.prototype.restartRegistration = function (userId, cb) {
+    var _reqData = {}, self = this, _userState;
+
+    if (!userId) {
+      return cb ? cb(Errors.missingUserId, null) : {error: 1};
+    } else if (!this.checkUser(userId)) {
+      return cb(Errors.invalidUserId, null);
+    } else if (!this.settings.registerURL) {
+      return cb({code: Errors.missingParams.code, type: Errors.missingParams.type, message: "Missing registerURL"}, null);
+    }
+
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.start) {
+      return cb(Errors.wrongFlow, null);
+    }
+
+    _reqData.url = this.generateUrl("restart", {userId: userId});
+    _reqData.type = "PUT";
+    _reqData.data = {
+      userId: userId,
+      mobile: 0,
+      regOTT: Users[userId].regOTT
+    };
+
+    this.request(_reqData, function (err, data) {
+      if (err) {
+        return cb(err, null);
+      }
+
+      self.addToUser(userId, {regOTT: data.regOTT, mpinId: data.mpinId});
+
+      //force activate
+      if (data.active) {
+        self.addToUser(userId, {state: States.active});
+      }
+
+      cb && cb(null, true);
+    });
+  };
+
+  Mpin.prototype.startAuthentication = function (userId, cb) {
+    var _tp1Url, self = this, _userState;
+
+    if (!userId) {
+      return cb ? cb(Errors.missingUserId, null) : Errors.missingUserId;
+    } else if (!this.checkUser(userId)) {
+      return cb(Errors.invalidUserId, null);
+    } else if (!this.settings.timePermitsURL || !this.settings.certivoxURL) {
+      return cb({code: Errors.missingParams.code, type: Errors.missingParams.type, message: "Missing timePermitsURL or/and certivoxURL option."}, null);
+    }
+
+    //registered
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.register) {
+      return cb(Errors.wrongFlow, null);
+    }
+
+    //checkUser
+    _tp1Url = this.generateUrl('permit1', {userId: userId});
+    this.request({url: _tp1Url}, function (err, data) {
+      if (err) {
+        if (err.status === 401 || err.status === 403 || err.status === 410) {
+          return cb(Errors.userRevoked, null);
+        }
+
+        return cb(err, null);
+      }
+      var _signature, _tp2Url, _timePermit1, _storageUrl;
+      _signature = data["signature"];
+      _timePermit1 = data["timePermit"];
+
+      self.addToUser(userId, {currentDate: data['date']});
+
+      //check cache if exist
+      if (Users[userId].timePermitCache && Users[userId].timePermitCache.date === data.date) {
+        var _timePermit2 = Users[userId].timePermitCache.timePermit;
+        var timePermitHex = MPINAuth.addShares(_timePermit1, _timePermit2);
+
+        self.addToUser(userId, {timePermitHex: timePermitHex});
+        cb && cb(null, true); //exit with cache permit2
+        return;
+      } else {
+        _storageUrl = self.generateUrl("storage", {date: data.date, storageId: data.storageId});
+
+        self.request({url: _storageUrl}, function (storErr, storData) {
+          if (storErr) {
+            _tp2Url = self.generateUrl('permit2', {userId: userId});
+            _tp2Url += "&signature=" + _signature;
+
+            self._getTimePermit2({userId: userId, permit1: _timePermit1, permit2Url: _tp2Url, date: data.date}, cb); //continue
+
+            return;
+          }
+
+          var _timePermit2 = storData;
+          var timePermitHex = MPINAuth.addShares(_timePermit1, _timePermit2);
+
+          self.addToUser(userId, {timePermitHex: timePermitHex, timePermitCache: {date: data.date, timePermit: _timePermit2}});
+
+          cb && cb(null, true); //exit with storage permit2
+        }, false);
+      }
+    });
+  };
+
+  Mpin.prototype._getTimePermit2 = function (options, cb) {
+    var self = this, _timePermit1 = options.permit1;
+
+    this.request({url: options.permit2Url}, function (err2, data2) {
+      if (err2) {
+        if (err2.status === 401 || err2.status === 403 || err2.status === 410) {
+          return cb(Errors.userRevoked, null);
+        }
+
+        return cb(err2, null);
+      }
+
+      var _timePermit2, timePermitHex, _permitCache = {};
+      _timePermit2 = data2["timePermit"];
+      timePermitHex = MPINAuth.addShares(_timePermit1, _timePermit2);
+
+      _permitCache.date = options.date;
+      _permitCache.timePermit = data2["timePermit"];
+
+      self.addToUser(options.userId, {timePermitHex: timePermitHex, timePermitCache: _permitCache});
+
+      cb && cb(null, true);
+    });
+  };
+
+
+  Mpin.prototype.finishAuthentication = function (userId, pin, cb) {
+    var _userState;
+
+    //registered
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.register) {
+      return cb(Errors.wrongFlow, null);
+    } else if (!Users[userId].timePermitHex) {
+      return cb({code: Errors.wrongFlow.code, type: Errors.wrongFlow.type, message: "Need to call startAuthentication method before this."}, null);
+    }
+
+    this._passRequests({userId: userId, pin: pin}, cb);
+  };
+
+  Mpin.prototype.finishAuthenticationOtp = function (userId, pin, cb) {
+    var _userState;
+
+    //registered
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.register) {
+      return cb(Errors.wrongFlow, null);
+    } else if (!Users[userId].timePermitHex) {
+      return cb({code: Errors.wrongFlow.code, type: Errors.wrongFlow.type, message: "Need to call startAuthentication method before this."}, null);
+    }
+
+    this._passRequests({userId: userId, pin: pin, otp: true}, function (err, data) {
+      if (err) {
+        return cb(err, null);
+      }
+
+      if (!data.expireTime || !data.ttlSeconds || !data.nowTime) {
+        return cb(null, null);
+      }
+
+      data.expireTime = data.expireTime / 1000;
+      data.nowTime = data.nowTime / 1000;
+
+      cb(null, data);
+    });
+
+  };
+
+  Mpin.prototype.finishAuthenticationAN = function (userId, pin, accessNumber, cb) {
+    var _userState;
+
+    //registered
+    _userState = this.getUser(userId, "state");
+    if (_userState !== States.register) {
+      return cb(Errors.wrongFlow, null);
+    } else if (!Users[userId].timePermitHex) {
+      return cb({code: Errors.wrongFlow.code, type: Errors.wrongFlow.type, message: "Need to call startAuthentication method before this."}, null);
+    }
+
+    this._passRequests({userId: userId, pin: pin, accessNumber: accessNumber.toString()}, function (err, data) {
+      if (err) {
+        return cb(err, null);
+      }
+
+      if (!data.expireTime || !data.ttlSeconds || !data.nowTime) {
+        return cb(null, null);
+      }
+
+      data.expireTime = data.expireTime / 1000;
+      data.nowTime = data.nowTime / 1000;
+
+      cb(null, data);
+    });
+
+  };
+
+  Mpin.prototype._passRequests = function (opts, cb) {
+    var userId, pin, otp, accessNumber, self = this, _reqData = {};
+    userId = opts.userId;
+    pin = isNaN(opts.pin) ? this.toHash(opts.pin) : opts.pin;
+
+    otp = opts.otp || false;
+    accessNumber = opts.accessNumber || false;
+
+    _reqData.url = this.generateUrl("pass1");
+    _reqData.type = "POST";
+    _reqData.data = this.getAuthData(userId, pin);
+
+    //  pass1
+    this.request(_reqData, function (pass1Err, pass1Data) {
+      var _req2Data = {}, wid = "0";
+      _req2Data.url = self.generateUrl("pass2");
+      _req2Data.type = "POST";
+
+      accessNumber && (wid = accessNumber);
+      _req2Data.data = MPINAuth.pass2Request(pass1Data.y, otp, wid);
+
+      _req2Data.data.mpin_id = Users[userId].mpinId;
+
+      // pass 2
+      self.request(_req2Data, function (pass2Err, pass2Data) {
+        var otpCode;
+        if (pass2Err) {
+          return cb(pass2Err, null);
+        }
+
+        otpCode = pass2Data["OTP"] || false;
+
+        if (pass2Data && pass2Data["OTP"]) {
+          delete pass2Data["OTP"];
+        }
+
+        self._authenticate({userId: userId, mpinResponse: pass2Data, otpCode: otpCode, accessNumber: accessNumber}, cb);
+      });
+    });
+
+  };
+
+  Mpin.prototype._authenticate = function (opts, cb) {
+    var _authData = {}, self = this;
+
+    if (opts.accessNumber) {
+      _authData.url = this.generateUrl("mobileauth");
+    } else {
+      _authData.url = this.generateUrl("auth");
+    }
+
+    _authData.type = "POST";
+    _authData.data = {mpinResponse: opts.mpinResponse};
+
+    this.request(_authData, function (authErr, authData) {
+      if (authErr) {
+        if (authErr.status === 401) {
+          return cb(Errors.wrongPin, null);
+        } else if (authErr.status === 403) {
+          return cb(Errors.identityNotAuthorized, null);
+        } else if (authErr.status === 408) {
+          return cb(Errors.requestExpired, null);
+        } else if (authErr.status === 410) {
+          opts.userId && self.addToUser(opts.userId, {state: States.block});
+          return cb(Errors.wrongPin, null);
+        } else if (authErr.status === 412) {
+          return cb(Errors.incorrectAccessNumber, null);
+        } else {
+          return cb(Errors.wrongPin, null);
+        }
+      }
+
+      if (opts.otpCode && authData) {
+        authData.otp = opts.otpCode;
+      }
+
+      cb && cb(null, authData || null);
+    });
+  };
+
+  Mpin.prototype.checkAccessNumber = function (accessNumber) {
+    accessNumber = accessNumber.toString();
+    if (!this.settings.accessNumberUseCheckSum || accessNumber.length != this.settings.accessNumberDigits) {
+      return true;
+    } else {
+      if (this.settings.cSum === 1) {
+        return this.checkAccessNumberSum2(accessNumber, 6);
+      } else {
+        return this.checkAccessNumberSum(accessNumber);
+      }
+    }
+  };
+
+  Mpin.prototype.checkAccessNumberSum = function (accNumber, accLen) {
+    accLen || (accLen = 1);
+
+    var n = parseInt(accNumber.slice(0, accNumber.length - accLen), 10);
+    var cSum = parseInt(accNumber.slice(accNumber.length - accLen, accNumber.length), 10);
+
+    var p = 99991;
+    var g = 11;
+    var checkSum = ((n * g) % p) % Math.pow(10, accLen);
+
+    return (checkSum === cSum);
+  };
+
+  Mpin.prototype.checkAccessNumberSum2 = function (accNumber, accLen) {
+    var cSum, checksum, x, w, wid, wid_len, g = 11, sum_d = 0;
+    wid = accNumber.toString();
+    wid = wid.substring(0, accNumber.toString().length - 1);
+    w = accLen + 1;
+    sum_d = 0;
+    wid_len = wid.length;
+
+    for (var i = 0; i < wid_len; i++) {
+      x = parseInt(wid[i]);
+      sum_d += (x * w);
+      w -= 1;
+    }
+    checksum = (g - (sum_d % g)) % g;
+    checksum = (checksum === 10) ? 0 : checksum;
+
+    //get last one digit and compare with checksum result
+    cSum = accNumber.substr(-1);
+    cSum = parseInt(cSum);
+    return (cSum === checksum);
+  };
+
+  Mpin.prototype.getAuthData = function (userId, pin) {
+    var _auth = {};
+
+    _auth.mpin = Users[userId].mpinId;
+    _auth.token = Users[userId].token;
+    _auth.timePermit = Users[userId].timePermitHex;
+    _auth.date = Users[userId].currentDate;
+
+    return MPINAuth.pass1Request(_auth.mpin, _auth.token, _auth.timePermit, pin, _auth.date, null);
+  };
+
+  Mpin.prototype.fromHex = function (strData) {
+    if (!strData || strData.length % 2 != 0)
+      return '';
+    strData = strData.toLowerCase();
+    var digits = '0123456789abcdef';
+    var result = '';
+    for (var i = 0; i < strData.length; ) {
+      var a = digits.indexOf(strData.charAt(i++));
+      var b = digits.indexOf(strData.charAt(i++));
+      if (a < 0 || b < 0)
+        return '';
+      result += String.fromCharCode(a * 16 + b);
+    }
+    return result;
+  };
+
+  Mpin.prototype.toHash = function (strData) {
+    var hash = 0;
+    for (var i = 0; i < strData.length; i++) {
+      hash = ((hash << 5) - hash) + strData.charCodeAt(i);
+    }
+    return hash;
+  };
+
+  Mpin.prototype.getAccessNumber = function (cb) {
+    var self = this, _reqData = {};
+
+    _reqData.url = this.generateUrl("getnumber");
+    _reqData.type = "POST";
+
+    this.request(_reqData, function (err, data) {
+      if (err) {
+        return cb(err, null);
+      }
+      self.webOTT = data.webOTT;
+
+      returnData = {
+        accessNumber: data.accessNumber,
+        ttlSeconds: data.ttlSeconds,
+        localTimeStart: data.localTimeStart / 1000,
+        localTimeEnd: data.localTimeEnd / 1000
+      };
+
+      cb && cb(null, returnData);
+    });
+  };
+
+  Mpin.prototype.waitForMobileAuth = function (timeoutSeconds, requestSeconds, cb) {
+    var self = this, _reqData = {};
+    if (!this.webOTT) {
+      return cb({code: Errors.wrongFlow.code, type: Errors.wrongFlow.type, message: "Need to call getAccessNumber method before this."}, null);
+    } else if (!timeoutSeconds) {
+      return cb({code: Errors.missingParams.code, type: Errors.missingParams.type, message: "Missing timeout/expiration period(in seconds)."}, null);
+    }
+
+
+    if (typeof this.timeoutPeriod === "undefined") {
+      this.timeoutPeriod = timeoutSeconds * 1000;
+    }
+
+    _reqData.url = this.generateUrl("getaccess");
+    _reqData.type = "POST";
+    _reqData.data = {webOTT: this.webOTT};
+
+    this.request(_reqData, function (err, data) {
+      var _requestPeriod;
+      if (err) {
+        if (err.status === 401 && self.timeoutPeriod > 0) {
+          _requestPeriod = requestSeconds ? requestSeconds * 1000 : 3000;
+          self.timeoutPeriod -= _requestPeriod;
+
+          self.intervalID2 = setTimeout(function () {
+            self.waitForMobileAuth.call(self, timeoutSeconds, requestSeconds, cb);
+          }, _requestPeriod);
+          return;
+        } else if (self.timeoutPeriod <= 0) {
+          delete self.timeoutPeriod;
+          cb && cb(Errors.timeoutFinish, null);
+          return;
+        }
+      } else {
+        self._authenticate({mpinResponse: data}, cb);
+      }
+    });
+  };
+
+  Mpin.prototype.cancelMobileAuth = function () {
+    if (this.intervalID2) {
+      clearInterval(this.intervalID2);
+    }
+
+    if (this.timeoutPeriod) {
+      delete this.timeoutPeriod;
+    }
+  };
+
+
+  Mpin.prototype.generateUrl = function (type, options) {
+    var url, mpData, mpin_id_bytes, hash_mpin_id_bytes = [], hash_mpin_id_hex;
+
+    switch (type) {
+      case "register":
+        url = this.settings.registerURL;
+        break;
+      case "restart":
+        url = this.settings.registerURL + "/";
+        url += Users[options.userId].mpinId;
+        break;
+      case "signature":
+        url = this.settings.signatureURL + "/";
+        url += Users[options.userId].mpinId;
+        url += "?regOTT=" + Users[options.userId].regOTT;
+        break;
+      case "permit1":
+        url = this.settings.timePermitsURL + "/";
+        url += Users[options.userId].mpinId;
+        break;
+      case "permit2":
+        mpData = this.fromHex(Users[options.userId].mpinId);
+        mpin_id_bytes = MPIN.stringtobytes(mpData);
+        hash_mpin_id_bytes = MPIN.HASH_ID(mpin_id_bytes);
+        hash_mpin_id_hex = MPIN.bytestostring(hash_mpin_id_bytes);
+        url = this.settings.certivoxURL + "timePermit";
+        url += "?app_id=" + this.settings.appID;
+        url += "&mobile=0";
+        url += "&hash_mpin_id=" + hash_mpin_id_hex;
+        break;
+      case "pass1":
+        url = this.settings.mpinAuthServerURL + "/pass1";
+        break;
+      case "pass2":
+        url = this.settings.mpinAuthServerURL + "/pass2";
+        break;
+      case "auth":
+        url = this.settings.authenticateURL;
+        break;
+      case "mobileauth":
+        url = this.settings.mobileAuthenticateURL;
+        break;
+      case "getnumber":
+        url = this.settings.getAccessNumberURL;
+        break;
+      case "getaccess":
+        url = this.settings.accessNumberURL;
+        break;
+      case "storage":
+        url = this.settings.timePermitsStorageURL + "/" + this.settings.appID + "/";
+        url += options.date + "/" + options.storageId;
+        break;
+    }
+
+    return url;
+  };
+
+  Mpin.prototype.listUsers = function () {
+    var listUsers = [];
+    for (var uKey in Users) {
+      listUsers.push({
+        userId: Users[uKey].userId,
+        deviceId: Users[uKey].deviceId || "",
+        state: Users[uKey].state || ""
+      });
+    }
+    return listUsers;
+  };
+
+  Mpin.prototype.checkUser = function (userId) {
+    return (Users[userId]) ? true : false;
+  };
+
+  Mpin.prototype.getUser = function (userId, property) {
+    var _user = {};
+    if (!userId) {
+      return Errors.missingUserId;
+    } else if (!this.checkUser(userId)) {
+      return Errors.invalidUserId;
+    }
+
+    _user = {
+      userId: Users[userId].userId,
+      deviceId: Users[userId].deviceId || "",
+      state: Users[userId].state
+    };
+
+    if (!property) {
+      return _user;
+    } else if (property && _user[property]) {
+      return _user[property];
+    }
+  };
+
+
+  Mpin.prototype.deleteUser = function (userId) {
+    var mpinData = this.getData(), delMpinId;
+
+    if (!userId) {
+      return Errors.missingUserId;
+    } else if (!this.checkUser(userId)) {
+      return Errors.invalidUserId;
+    }
+
+    delMpinId = Users[userId].mpinId;
+
+    //memory
+    delete Users[userId];
+
+    //store
+    delete mpinData.accounts[delMpinId];
+
+    this.storeData(mpinData);
+  };
+
+  Mpin.prototype.addToUser = function (userId, userProps, skipSave) {
+    if (!this.checkUser(userId)) {
+      //create
+      Users[userId] = {};
+    }
+
+    //If mpinId has changed, we need to delete the object withthe previous one
+    if (Users[userId].mpinId && userProps.mpinId && Users[userId].mpinId != userProps.mpinId) {
+      this.deleteData(userId);
+    }
+
+    for (var uKey in userProps) {
+      if (userProps[uKey]) {
+        Users[userId][uKey] = userProps[uKey];
+      }
+    }
+
+    var _save = !skipSave;
+    _save && this.setData(userId, userProps);
+  };
+
+  Mpin.prototype.restore = function () {
+    Users = {};
+  };
+
+  Mpin.prototype.deleteData = function (userId) {
+    var mpinData = this.getData();
+
+    var mpinId = Users[userId].mpinId;
+    if (!mpinData || !mpinData.accounts[mpinId]) {
+      return;
+    }
+
+    delete mpinData.accounts[mpinId];
+
+    this.storeData(mpinData);
+  };
+
+  Mpin.prototype.setData = function (userId, upData) {
+    var mpinData = this.getData();
+
+    if (!mpinData) {
+      mpinData = {
+        version: "4",
+        accounts: {}
+      };
+    }
+
+    var mpinId = upData.mpinId || Users[userId].mpinId;
+
+    if (!mpinId) {
+      return false;
+    }
+
+    //update Default Identity
+    if (!mpinData.accounts[mpinId]) {
+      mpinData.accounts[mpinId] = {};
+    }
+
+    if (upData.regOTT) {
+      mpinData.accounts[mpinId].regOTT = upData.regOTT;
+    }
+
+    if (upData.timePermitHex) {
+      mpinData.accounts[mpinId].MPinPermit = upData.timePermitHex;
+    }
+
+    if (upData.token) {
+      mpinData.accounts[mpinId].token = upData.token;
+    }
+
+    if (upData.state && Users[userId].mpinId) {
+      mpinData.accounts[mpinId].state = upData.state;
+    }
+
+    //cache cache
+    if (upData.timePermitCache) {
+      mpinData.accounts[mpinId].timePermitCache = upData.timePermitCache;
+    }
+
+    this.storeData(mpinData);
+  };
+
+  Mpin.prototype.storeData = function (mpinData, key) {
+    var storageKey = key || this.storageKey;
+    localStorage.setItem(storageKey, JSON.stringify(mpinData));
+  };
+
+  Mpin.prototype.recover = function () {
+    var userId, userData = {}, mpinData = this.getData(), isOldData = false;
+
+    if (!mpinData) {
+      mpinData = this.getData("mpin");
+      isOldData = true;
+    }
+
+    if (mpinData && "accounts" in mpinData) {
+      for (var mpinId in mpinData.accounts) {
+        userId = (JSON.parse(this.fromHex(mpinId))).userID;
+
+        userData = {};
+        userData.userId = userId;
+        userData.mpinId = mpinId;
+
+        mpinData.accounts[mpinId].regOTT && (userData.regOTT = mpinData.accounts[mpinId].regOTT);
+        mpinData.accounts[mpinId].token && (userData.token = mpinData.accounts[mpinId].token);
+        mpinData.accounts[mpinId].MPinPermit && (userData.MPinPermit = mpinData.accounts[mpinId].MPinPermit);
+        mpinData.accounts[mpinId].timePermitCache && (userData.timePermitCache = mpinData.accounts[mpinId].timePermitCache);
+
+        if (isOldData || !mpinData.accounts[mpinId].state) {
+          if (mpinData.accounts[mpinId].token) {
+            userData.state = States.register;
+          } else if (mpinData.accounts[mpinId].regOTT) {
+            userData.state = States.start;
+          } else {
+            userData.state = States.invalid;
+          }
+        } else {
+          userData.state = mpinData.accounts[mpinId].state;
+        }
+
+        //call add To user & skip Save
+        this.addToUser(userId, userData, !isOldData);
+      }
+    }
+
+    if (isOldData && mpinData && "accounts" in mpinData) {
+      delete mpinData.accounts;
+      this.storeData(mpinData, "mpin");
+    }
+  };
+
+  Mpin.prototype.getData = function (getKey) {
+    var localKey, mpinData;
+    localKey = getKey || this.storageKey;
+    mpinData = localStorage.getItem(localKey);
+    mpinData = JSON.parse(mpinData);
+    return mpinData;
+  };
+
+//{url: url, type: "get post put", data: data}
+  Mpin.prototype.request = function (options, cb, jsonResponse) {
+    var _request = new XMLHttpRequest(), _url, _type, _parseJson;
+    _url = options.url || "";
+    _type = options.type || "GET";
+
+    _parseJson = (typeof jsonResponse !== "undefined") ? jsonResponse : true;
+
+    _request.onreadystatechange = function () {
+      if (_request.readyState === 4 && _request.status === 200) {
+        if (_parseJson && _request.responseText) {
+          cb(null, JSON.parse(_request.responseText));
+        } else {
+          cb(null, _request.responseText);
+        }
+      } else if (_request.readyState === 4) {
+        cb({status: _request.status}, null);
+      }
+    };
+
+    _request.open(_type, _url, true);
+    if (options.data) {
+      _request.setRequestHeader("Content-Type", "application/json");
+      _request.send(JSON.stringify(options.data));
+    } else {
+      _request.send();
+    }
+  };
+
+  return Mpin;
+})();
+
+
+//module.exports = mpinjs;
+//http://www.matteoagosti.com/blog/2013/02/24/writing-javascript-modules-for-both-browser-and-node/
+if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
+  module.exports = mpinjs;
+else
+  window.mpinjs = mpinjs;
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..cbe0d8a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,42 @@
+{
+  "name": "mpinjs",
+  "version": "1.0.0",
+  "description": "Mpin frontend library.",
+  "main": "index.js",
+  "scripts": {
+    "test": "mocha -R mocha-bamboo-reporter",
+    "test2": "mocha test --require blanket --reporter html-cov > test/coverage.html"
+  },
+  "repository": {
+    "type": "git",
+    "url": "http://10.10.23.8:7990/scm/mpin/mpinjs.git"
+  },
+  "keywords": [
+    "Mpin",
+    "frontend"
+  ],
+  "author": "Mpin",
+  "license": "ISC",
+  "devDependencies": {
+    "blanket": "^1.2.1",
+    "chai": "^3.4.1",
+    "mocha": "^2.3.4",
+    "sinon": "^1.17.2",
+    "sinon-chai": "^2.8.0"
+  },
+  "config": {
+    "blanket": {
+      "pattern": [
+        "mpin.js"
+      ],
+      "data-cover-never": "node_modules"
+    }
+  },
+  "dependencies": {
+    "bower": "^1.6.5",
+    "grunt": "^0.4.5",
+    "grunt-bg-shell": "^2.3.1",
+    "grunt-contrib-concat": "^0.5.1",
+    "mocha-bamboo-reporter": "^1.1.0"
+  }
+}
diff --git a/test/auth.js b/test/auth.js
new file mode 100644
index 0000000..ab22fe3
--- /dev/null
+++ b/test/auth.js
@@ -0,0 +1,266 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+//if browser
+if (typeof require !== 'undefined') {
+  var expect = require('chai').expect;
+  var sinon = require('sinon');
+  var sinonChai = require('sinon-chai');
+  var mpinjs = require('../index');
+  var inits = require("./init");
+}
+var Errors, testData, testLocalstorage;
+
+Errors = inits.Errors;
+MPINAuth = inits.MPINAuth;
+MPIN = inits.MPIN;
+testData = inits.testData;
+testLocalstorage = inits.testLocalStorage;
+
+////////////////////////////////////////////////////////////authentication
+describe("# startAuthentication", function () {
+  var mpin, spy, serverUrl = "http://192.168.10.63:8005";
+
+  var testLocalstorage = {
+    "accounts": {
+      "7b226d6f62696c65223a20302c2022697373756564223a2022323031362d30322d32332031363a34393a31302e313039363734222c2022757365724944223a20227465737440746573742e636f6d222c202273616c74223a20223162396336353564343665323238373661333631373033353138616636363037227d": {
+        "regOTT": "4ac1cca55c09f6d4e47a253d8cd503b5",
+        "state": "STARTED"
+      }
+    }
+  };
+
+
+  var userId = "test@user.id";
+
+  beforeEach(function (done) {
+    var userPin = "userSecret";
+
+    mpin = new mpinjs({server: testData.serverUrl});
+    spy = sinon.spy();
+
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+    sinon.stub(mpin, "storeData");
+
+    spy = sinon.spy(mpin, "toHash");
+
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);
+    stub.onCall(1).yields(null, testData.mpin);//mpinId
+    stub.onCall(2).yields(null, testData.cs1);//cs1
+    stub.onCall(3).yields(null, testData.cs2);//cs2
+
+    mpin.init(function (err, data) {
+      mpin.makeNewUser(userId);
+      mpin.startRegistration(userId, function (err1, data1) {
+        mpin.confirmRegistration(userId, function (err2, data2) {
+          mpin.finishRegistration(userId, userPin);
+          expect(spy.calledOnce).to.be.true;
+          expect(spy.calledWith(userPin)).to.be.true;
+          done();
+        });
+      });
+    });
+  });
+
+  afterEach(function () {
+    mpin.restore();
+    mpin.request.restore && mpin.request.restore();
+  });
+
+
+  it("should return error type " + Errors.missingUserId + " call without userId", function () {
+    var err = mpin.startAuthentication();
+    expect(err).to.deep.equal({code: 0, type: Errors.missingUserId});
+  });
+
+  it("should return error type " + Errors.userRevoked + " when timePermit1 request return status:401", function (done) {
+    var errData = {status: 500};
+    stub.onCall(4).yields({status: 401}, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(errData, null); //tp2 - return status 401 user Revoke
+    mpin.startAuthentication(userId, function (err, data) {
+      expect(err).to.deep.equal({code: 7, type: Errors.userRevoked});
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.userRevoked + " when timePermit2 request return status:401", function (done) {
+    var errData = {status: 500};
+
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(errData, null); //tp2 - return status 401 user Revoke
+    mpin.startAuthentication(userId, function (err, data) {
+      expect(err).to.deep.equal(errData);
+      done();
+    });
+  });
+
+  it("should return error if have any other errors", function (done) {
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields({status: 401}, null); //tp2 - return status 401 user Revoke
+    mpin.startAuthentication(userId, function (err, data) {
+      expect(err).to.deep.equal({code: 7, type: Errors.userRevoked});
+      done();
+    });
+  });
+
+  it("should be ok ", function (done) {
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(null, testData.tp2); //tp2
+    mpin.startAuthentication(userId, function (err, data) {
+      expect(data).to.be.true;
+      done();
+    });
+  });
+});
+
+describe("# finishAuthentication", function () {
+  var mpin, spy, userId = "test@user.id", userPin = "userPIN";
+
+  beforeEach(function (done) {
+    mpin = new mpinjs({server: testData.serverUrl});
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+    sinon.stub(mpin, "storeData");
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);
+    stub.onCall(1).yields(null, testData.mpin);//mpinId
+    stub.onCall(2).yields(null, testData.cs1);//cs1
+    stub.onCall(3).yields(null, testData.cs2);//cs2
+    done();
+    this.setupFlow = function (cb) {
+      mpin.init(function (err, data) {
+        mpin.makeNewUser(userId);
+        mpin.startRegistration(userId, function (err1, data1) {
+          mpin.confirmRegistration(userId, function (err2, data2) {
+            mpin.finishRegistration(userId, userPin);
+            cb();
+          });
+        });
+      });
+    };
+  });
+
+  afterEach(function () {
+    mpin.restore();
+    mpin.request.restore && mpin.request.restore();
+  });
+
+  it("should return error type " + Errors.wrongFlow + " when call finish Authentication w/o setupFlow", function (done) {
+    mpin.finishAuthentication(userId, "test", function (err, data) {
+      expect(err).to.deep.equal({code: 6, type: Errors.wrongFlow});
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.wrongFlow + " when call finish Authentication w/o startAuthentication", function (done) {
+    this.setupFlow(function () {
+      mpin.finishAuthentication(userId, "test", function (err, data) {
+        expect(err).to.have.deep.property("type", Errors.wrongFlow);
+        done();
+      });
+    });
+  });
+
+  it("should return error type " + Errors.wrongPin + " when auth request fail with 401", function (done) {
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(null, testData.tp2); //tp2
+    stub.onCall(7).yields(null, testData.pass1); //pass1
+    stub.onCall(8).yields(null, testData.pass2); //pass2
+
+    stub.onCall(9).yields({status: 401}, null); //auth
+    this.setupFlow(function () {
+      mpin.startAuthentication(userId, function (err, data) {
+        mpin.finishAuthentication(userId, "test", function (err2, data2) {
+          expect(err2).to.have.deep.property("type", Errors.wrongPin);
+          done();
+        });
+      });
+    });
+  });
+
+  it("should return error type " + Errors.wrongPin + " when auth request fail with 410", function (done) {
+    var authOut = null;
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(null, testData.tp2); //tp2
+    stub.onCall(7).yields(null, testData.pass1); //pass1
+    stub.onCall(8).yields(null, testData.pass2); //pass2
+
+    stub.onCall(9).yields({status: 410}, null); //auth
+    this.setupFlow(function () {
+      mpin.startAuthentication(userId, function (err, data) {
+        mpin.finishAuthentication(userId, "test", function (err2, data2) {
+          expect(err2).to.have.deep.property("type", Errors.wrongPin);
+          done();
+        });
+      });
+    });
+  });
+
+  it("should hash pin if PIN is not an number", function (done) {
+    var authOut = null, spyHash, userPass = "testPass";
+
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(null, testData.tp2); //tp2
+    stub.onCall(7).yields(null, testData.pass1); //pass1
+    stub.onCall(8).yields(null, testData.pass2); //pass2
+
+    stub.onCall(9).yields(null, authOut); //auth
+    this.setupFlow(function () {
+      spyHash = sinon.spy(mpin, "toHash");
+      mpin.startAuthentication(userId, function (err, data) {
+        mpin.finishAuthentication(userId, userPass, function (err2, data2) {
+          expect(spyHash.calledOnce).to.be.true;
+          expect(spyHash.calledWith(userPass)).to.be.true;
+          done();
+        });
+      });
+    });
+  });
+
+  it("should return ok without data when response did not return such", function (done) {
+    var authOut = null;
+    stub.onCall(4).yields(null, testData.tp1);//tp1
+    stub.onCall(5).yields({status: 404}, null);//timePermitStorage
+    stub.onCall(6).yields(null, testData.tp2); //tp2
+    stub.onCall(7).yields(null, testData.pass1); //pass1
+    stub.onCall(8).yields(null, testData.pass2); //pass2
+
+    stub.onCall(9).yields(null, authOut); //auth
+    this.setupFlow(function () {
+      mpin.startAuthentication(userId, function (err, data) {
+        mpin.finishAuthentication(userId, "test", function (err2, data2) {
+          expect(err2).to.be.a('null');
+          expect(data2).to.be.a('null');
+          done();
+        });
+      });
+    });
+  });
+});
\ No newline at end of file
diff --git a/test/index.html b/test/index.html
new file mode 100644
index 0000000..1708549
--- /dev/null
+++ b/test/index.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>

+<!--

+To change this license header, choose License Headers in Project Properties.

+To change this template file, choose Tools | Templates

+and open the template in the editor.

+-->

+<html>

+  <head>

+    <title>MPin js Browser tests</title>

+    <meta charset="UTF-8">

+    <meta name="viewport" content="width=device-width, initial-scale=1.0">

+		<link rel="stylesheet" media="all" href="../node_modules/mocha/mocha.css">

+		<script src="../node_modules/chai/chai.js"></script>

+		<script src="../node_modules/sinon-chai/lib/sinon-chai.js"></script>

+		<script src="../node_modules/mocha/mocha.js"></script>

+		<script src="../node_modules/sinon/pkg/sinon.js"></script>

+		<script src="../dist/mpinjs.js"></script> 

+  </head>

+  <body>

+		<!-- This is where mocha inserts the test results that are styled with the css file above -->

+		<div id="mocha"></div>

+		<!-- This is where any fixtures we need for the test will be inserted into. Naturally, we won't want to cover the mocha test results so we position this bad boy off screen. -->

+		<div id="test" style="position: fixed; top: 0; left: -99999px;"></div>

+

+		<script>

+      mocha.setup('bdd');

+

+      mocha.ui('bdd');

+      mocha.reporter('html');

+      expect = chai.expect;

+

+

+		</script>

+

+		<script src="init.js"></script>

+		<script src="index.js"></script>

+		<script src="auth.js"></script>

+		<script>

+

+      mocha.run();

+		</script>

+  </body>

+</html>

diff --git a/test/index.js b/test/index.js
new file mode 100644
index 0000000..1e836bb
--- /dev/null
+++ b/test/index.js
@@ -0,0 +1,440 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+//if browser
+if (typeof require !== 'undefined') {
+  var expect = require('chai').expect;
+  var sinon = require('sinon');
+  var sinonChai = require('sinon-chai');
+  var mpinjs = require('../index');
+  var inits = require("./init");
+}
+var Errors, testData, testLocalstorage, testLocalStorage2;
+
+Errors = inits.Errors;
+MPINAuth = inits.MPINAuth;
+MPIN = inits.MPIN;
+testData = inits.testData;
+testLocalstorage = inits.testLocalStorage;
+testLocalStorage2 = inits.testLocalStorage2;
+
+
+describe("# Constructor initialization without sever Url.", function () {
+  it("should throw Error", function () {
+    var mpin = new mpinjs();
+    expect(mpin).to.be.an.instanceof(Error);
+  });
+});
+
+//spy cases
+describe("# Normal initialization.", function () {
+  var mpin, spy;
+
+  before(function () {
+    mpin = new mpinjs({server: testData.serverUrl});
+    spy = sinon.spy();
+
+    mpin.request = spy;
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+  });
+
+  it("should call request method once", function () {
+    mpin.init();
+    expect(spy.calledOnce).to.be.true;
+  });
+
+  it("should call request method with settingsUrl params", function () {
+    mpin.init();
+    expect(spy.calledWith({url: testData.serverUrl + "/rps/clientSettings"})).to.be.true;
+  });
+});
+
+describe("# Init method > clientSettings request.", function () {
+  var mpin;
+
+  before(function () {
+    mpin = new mpinjs({server: testData.serverUrl});
+
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+  });
+
+//restore request
+  afterEach(function (done) {
+    mpin.request.restore();
+    done();
+  });
+
+  it("should return error if init response is wrong", function (done) {
+    sinon.stub(mpin, 'request').yields({}, null);
+    mpin.init(function (err, data) {
+      expect(err).to.exist;
+      done();
+    });
+  });
+
+  it("should store init response into internal property", function (done) {
+    sinon.stub(mpin, 'request').yields(null, testData.clientSettings);
+    mpin.init(function (err, data) {
+      expect(data).to.be.true;
+      done();
+    });
+  });
+
+});
+
+describe("# makeNewUser checks.", function () {
+  var mpin;
+
+  before(function () {
+    mpin = new mpinjs({server: testData.serverUrl});
+
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+//    sinon.stub(mpin, "addToUser");
+  });
+
+  after(function () {
+    mpin.restore();
+  });
+
+  it("should makeNewUser return error type " + Errors.missingUserId + " when call without userId", function () {
+    var user = mpin.makeNewUser();
+    expect(user).to.deep.equal({code: 0, type: Errors.missingUserId});
+  });
+
+  it("should store user into internal list", function () {
+    var userId = "test@user.id";
+    mpin.makeNewUser(userId);
+    expect(mpin.checkUser(userId)).to.be.true;
+  });
+});
+
+describe("# startRegistration.", function () {
+  var mpin;
+
+  before(function () {
+    mpin = new mpinjs({server: testData.serverUrl});
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+  });
+
+  after(function () {
+    mpin.restore();
+  });
+
+  it("should return error type " + Errors.missingUserId + ", call without userId", function (done) {
+    mpin.startRegistration(null, function (err, data) {
+      expect(err).to.deep.equal({code: 0, type: Errors.missingUserId});
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.invalidUserId + " if skip makeNewUser method.", function (done) {
+    var userId = "test@user.id";
+    mpin.startRegistration(userId, function (err, data) {
+      expect(err).to.deep.equal({code: 1, type: Errors.invalidUserId});
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.missingParams + " if skip init method.", function (done) {
+    var userId = "test@user.id";
+    mpin.makeNewUser(userId);
+    mpin.startRegistration(userId, function (err, data) {
+      expect(err).to.exist;
+      done();
+    });
+  });
+
+  it("should return OK.", function (done) {
+    var userId = "test@user.id";
+
+    //mock for init method
+    sinon.stub(mpin, 'request').yields(null, testData.clientSettings);
+    mpin.init(function (err, data) {
+      mpin.makeNewUser(userId);
+      mpin.startRegistration(userId, function (err1, data1) {
+        expect(data).to.exist;
+        done();
+      });
+    });
+  });
+});
+
+
+describe("# confirmRegistration.", function () {
+  var mpin;
+  before(function () {
+    mpin = new mpinjs({server: testData.serverUrl});
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+  });
+
+  afterEach(function () {
+    mpin.restore();
+    mpin.request.restore && mpin.request.restore();
+  });
+
+  it("should return error type " + Errors.missingUserId + " call without userId", function (done) {
+    mpin.confirmRegistration(null, function (err, data) {
+      expect(err).to.deep.equal({code: 0, type: Errors.missingUserId});
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.invalidUserId + " if skip makeNewUser method.", function (done) {
+    var userId = "test@user.id";
+    mpin.confirmRegistration(userId, function (err, data) {
+      expect(err).to.have.deep.property('type', Errors.invalidUserId);
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.missingParams + " if skip init method.", function (done) {
+    var userId = "test@user.id";
+    mpin.makeNewUser(userId);
+    mpin.confirmRegistration(userId, function (err, data) {
+      expect(err).to.have.deep.property('type', Errors.missingParams);
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.identityNotVerified + " identity not verify.", function (done) {
+    var userId = "test@user.id", stub;
+
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);
+    stub.onCall(1).yields(null, {});
+    stub.onCall(2).yields({status: 401}, null);
+
+    mpin.init(function (err, data) {
+      mpin.makeNewUser(userId);
+      mpin.startRegistration(userId, function (err1, data1) {
+        mpin.confirmRegistration(userId, function (err2, data2) {
+          expect(err2).to.have.deep.property('type', Errors.identityNotVerified);
+          done();
+        });
+      });
+    });
+  });
+
+  //start REGISTRATION >>> OK
+  it("should return OK", function (done) {
+    var userId = "test@user.id", stub;
+    //define global cripto
+
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);
+    stub.onCall(1).yields(null, {});//mpinId
+    stub.onCall(2).yields(null, testData.cs1);//cs1
+    stub.onCall(3).yields(null, testData.cs2);//cs2
+
+    mpin.init(function (err, data) {
+      mpin.makeNewUser(userId);
+      mpin.startRegistration(userId, function (err1, data1) {
+        mpin.confirmRegistration(userId, function (err2, data2) {
+          expect(data2).to.exist;
+          done();
+        });
+      });
+    });
+  });
+});
+
+
+describe("# finishRegistration", function () {
+  var mpin, spy, userId = "test@user.id";
+
+  beforeEach(function () {
+    mpin = new mpinjs({server: testData.serverUrl});
+
+    sinon.stub(mpin, "getData", function () {
+      return testLocalstorage;
+    });
+
+    sinon.stub(mpin, "storeData");
+  });
+
+  afterEach(function () {
+    mpin.restore();
+    mpin.request.restore && mpin.request.restore();
+  });
+
+  it("should return error type " + Errors.missingUserId + " call without userId", function () {
+    var err = mpin.finishRegistration();
+    expect(err).to.deep.equal({code: 0, type: Errors.missingUserId});
+  });
+
+  it("should call getUser (with userId arguments) to validate user state", function () {
+    spy = sinon.spy(mpin, "getUser");
+    mpin.finishRegistration(userId);
+    expect(spy.calledOnce).to.be.true;
+    expect(spy.calledWith(userId)).to.be.true;
+  });
+
+  it("should return error type " + Errors.wrongFlow + " when didn't activate identity", function () {
+    mpin.makeNewUser(userId);
+    var err2 = mpin.finishRegistration(userId);
+    expect(err2).to.have.deep.property('type', Errors.wrongFlow);
+  });
+
+  it("should hash pin if PIN is not an number", function (done) {
+    var userPin = "userSecret";
+    spy = sinon.spy(mpin, "toHash");
+
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);
+    stub.onCall(1).yields(null, testData.mpin);//mpinId
+    stub.onCall(2).yields(null, testData.cs1);//cs1
+    stub.onCall(3).yields(null, testData.cs2);//cs2
+
+    mpin.init(function (err, data) {
+      mpin.makeNewUser(userId);
+      mpin.startRegistration(userId, function (err1, data1) {
+        mpin.confirmRegistration(userId, function (err2, data2) {
+          mpin.finishRegistration(userId, userPin);
+          expect(spy.calledOnce).to.be.true;
+          expect(spy.calledWith(userPin)).to.be.true;
+          done();
+        });
+      });
+    });
+  });
+
+  it("should save user state register", function (done) {
+    var userPin = "userSecret";
+
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);
+    stub.onCall(1).yields(null, testData.mpin);//mpinId
+    stub.onCall(2).yields(null, testData.cs1);//cs1
+    stub.onCall(3).yields(null, testData.cs2);//cs2
+
+    mpin.init(function (err, data) {
+      mpin.makeNewUser(userId);
+      mpin.startRegistration(userId, function (err1, data1) {
+        mpin.confirmRegistration(userId, function (err2, data2) {
+          spy = sinon.spy(mpin, "addToUser");
+          mpin.finishRegistration(userId, userPin);
+          expect(spy.calledOnce).to.be.true;
+//          expect(spy.calledWith(userId, {token: "token", state: "REGISTERED"})).to.be.true;
+          done();
+        });
+      });
+    });
+  });
+});
+
+
+
+
+
+
+describe("# backward compatibility", function () {
+  var mpin;
+  beforeEach(function (done) {
+    mpin = new mpinjs({server: testData.serverUrl});
+    sinon.stub(mpin, "getData", function () {
+      return testLocalStorage2;
+    });
+    sinon.stub(mpin, 'request').yields(null, testData.clientSettings);
+
+    mpin.init(function (err, data) {
+      done();
+    });
+  });
+
+  it("read all identities and setup proper state", function () {
+    var users;
+    users = mpin.listUsers();
+    expect(users).to.have.length(2);
+    expect(users[0]).to.have.deep.property("state", "STARTED");
+    expect(users[1]).to.have.deep.property("state", "REGISTERED");
+  });
+});
+
+describe("# restartRegistration", function () {
+  var mpin;
+  beforeEach(function (done) {
+    mpin = new mpinjs({server: testData.serverUrl});
+    sinon.stub(mpin, "getData", function () {
+      return testLocalStorage2;
+    });
+    stub = sinon.stub(mpin, 'request');
+    stub.onCall(0).yields(null, testData.clientSettings);//put user
+    
+    mpin.init(function (err, data) {
+      done();
+    });
+  });
+
+  afterEach(function () {
+    mpin.restore();
+    mpin.request.restore && mpin.request.restore();
+  });
+
+  it("should return error type " + Errors.missingUserId + " when call w/o user", function (done) {
+    mpin.restartRegistration(null, function (err, data) {
+      expect(err).to.have.deep.property("type", Errors.missingUserId);
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.invalidUserId + " when call with unexisting user", function (done) {
+    mpin.restartRegistration("nonExistUser", function (err, data) {
+      expect(err).to.have.deep.property("type", Errors.invalidUserId);
+      done();
+    });
+  });
+
+  it("should return error type " + Errors.wrongFlow + " when call userId different state from started", function (done) {
+    mpin.restartRegistration("dddsre@mailinator.com", function (err, data) {
+      expect(err).to.have.deep.property("type", Errors.wrongFlow);
+      done();
+    });
+  });
+
+  it("should return error if request fail", function (done) {
+    sinon.stub(mpin, "storeData");
+
+    stub.onCall(1).yields({status: 401}, null);//put user
+    mpin.restartRegistration("aaa@bbb.com", function (err, data) {
+      expect(err).to.have.deep.property("status", 401);
+      done();
+    });
+  });
+
+  it("should return ok when request is ok", function (done) {
+    sinon.stub(mpin, "storeData");
+
+    stub.onCall(1).yields(null, true);//put user
+    mpin.restartRegistration("aaa@bbb.com", function (err, data) {
+      expect(data).to.be.ok;
+      done();
+    });
+  });
+});
+
diff --git a/test/init.js b/test/init.js
new file mode 100644
index 0000000..4848170
--- /dev/null
+++ b/test/init.js
@@ -0,0 +1,142 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+//if browser
+var inits = function () {
+  var Errors, MPINAuth, MPIN, testData, testLocalStorage, testLocalStorage2;
+
+  Errors = [];
+  Errors.missingUserId = "MISSING_USERID";
+  Errors.invalidUserId = "INVALID_USERID";
+  Errors.missingParams = "MISSING_PARAMETERS";
+  Errors.identityNotVerified = "IDENTITY_NOT_VERIFIED";
+  Errors.identityMissing = "IDENTITY_MISSING";
+  Errors.wrongPin = "WRONG_PIN";
+  Errors.wrongFlow = "WRONG_FLOW";
+  Errors.userRevoked = "USER_REVOKED";
+
+  //overwrite global crypto function
+  MPINAuth = {};
+  MPINAuth.addShares = function () {
+    return "040a23a7e6d381a6dbd8b806013f07d40be36b42723ad3b1d986e4bbbe9ece83f421c504a4258cf87251af4ea7e847e4da46730034fc880f92d885c419716cb944";
+  };
+  MPINAuth.calculateMPinToken = function () {
+    return "04236eb28be98764e379049a2c4371752e7e3adc99a844800b9de2c34d2c70d95b07354c556276cbf79cee9e601807e6166d9bffedc3c1b1909ab5bf63330e2131";
+  };
+  MPINAuth.pass1Request = function () {
+    return {};
+  };
+  MPINAuth.pass2Request = function () {
+    return {};
+  };
+
+  MPIN = {};
+  MPIN.stringtobytes = function () {
+    return "";
+  }
+  MPIN.HASH_ID = function () {
+    return "";
+  }
+  MPIN.bytestostring = function () {
+    return "";
+  }
+
+  testData = {};
+  testData.serverUrl = "http://192.168.10.63:8005";
+  testData.clientSettings = {
+    requestOTP: false,
+    mpinAuthServerURL: "http://192.168.10.63:8011/rps",
+    registerURL: "http://192.168.10.63:8011/rps/user",
+    signatureURL: "http://192.168.10.63:8011/rps/signature",
+    certivoxURL: "https://community-api.certivox.net/v3/",
+    timePermitsURL: "http://192.168.10.63:8011/rps/timePermit"
+  };
+  testData.mpin = {
+    mpinId: "7b226d6f62696c65223a20302c2022697373756564223a2022323031362d30332d31352031333a34323a33362e393437303338222c2022757365724944223a20226d70696e4444222c202273616c74223a20226437373831313162633762653537323662666162633930353435396631643230227d"
+  };
+  testData.cs1 = {
+    clientSecretShare: "0421e379eb45e56ce699f0a7a83b683e84944b63fcc93a2834a4769ea40a28dc3f2064cd9d64846304999e00008b0838e246d3ea06d0013f1080c1027d54630ca9",
+    params: "mobile=0&expires=2015-12-03T12%3A47%3A23Z&app_id=e340a9f240e011e5b23b06df5546c0ed&hash_mpin_id=07a9af5af89d66b969be31d3d4e29c2a0a5ad4d3e30432eed9b3915dbf52230a&signature=33e8e987b07a2d9c9f3d98f68268870ef104cd0e0b9e02ba2c55e8bbf5190913&hash_user_id="
+  };
+  testData.cs2 = {
+    clientSecret: "0409ba1a247561ab16c35df3ad0ca9846db9968fa28757005335dc2ca35188b4f51521ac97d45bbdb3a8d1c0fdfe79ab29031054534df8b7cbac12e67e4e99d685"
+  };
+  testData.tp1 = {
+    "timePermit": "04145085669aa20607c0da730c01c707010e546bb81cf17abc29cacfef8e162b0f097b547c7058f6bd88e55cadc721b5721ee9730bfb10fa239c5bfacdb62fa3f4",
+    "signature": "39f9e16201d05dd3e369d43bd73cf0249e5bac01d5ff2975640d988e4a37b7f5",
+    "date": 16876
+  };
+  testData.tp2 = {
+    "timePermit": "040ff870574cb3c923410fdf33681beacd6ca6eeeb8858150efbf1241da9202c5604977ae285410df0d86a9976611b255a6fcbeeaf22bb398e4859ff3348bb4d87"
+  };
+  testData.pass1 = {
+    "y": "1dacb1f6830de09c0697485159da2ba4ed2908a8e24a85b886ff284306738b31"
+  };
+  testData.pass2 = {
+    "authOTT": "b0784ab9b6759953a3c6da85bdbdbaf3"
+  };
+  testData.auth = {
+    "authOTT": "b0784ab9b6759953a3c6da85bdbdbaf3"
+  };
+
+  testLocalStorage = {
+    "accounts": {
+      "7b226d6f62696c65223a20302c2022697373756564223a2022323031362d30322d32332031363a34393a31302e313039363734222c2022757365724944223a20227465737440746573742e636f6d222c202273616c74223a20223162396336353564343665323238373661333631373033353138616636363037227d": {
+        "regOTT": "4ac1cca55c09f6d4e47a253d8cd503b5",
+        "state": "STARTED"
+      }
+    }
+  };
+
+  testLocalStorage2 = {
+    "defaultIdentity": "7b226d6f62696c65223a20302c2022697373756564223a2022323031362d30322d30332031363a31333a32362e333030393938222c2022757365724944223a2022616161406262622e636f6d222c202273616c74223a20223237386166373433663465373034363764323334313936323262316333616231227d",
+    "version": "0.3",
+    "accounts": {
+      "7b226d6f62696c65223a20302c2022697373756564223a2022323031362d30322d30332031363a31333a32362e333030393938222c2022757365724944223a2022616161406262622e636f6d222c202273616c74223a20223237386166373433663465373034363764323334313936323262316333616231227d": {
+        "MPinPermit": "",
+        "token": "",
+        "regOTT": "b6216da7e3224e07eb4791815bcfcaa6"
+      },
+      "7b226d6f62696c65223a20302c2022697373756564223a2022323031362d30322d30382030383a35383a34302e373737373130222c2022757365724944223a2022646464737265406d61696c696e61746f722e636f6d222c202273616c74223a20223831373539623463313032363666646431616337323231326530643839393932227d": {
+        "MPinPermit": "042235a80c4c24f25a8a61758d3dac87d72b693c989ef95704c2ba51c7f4d98a631c912c9dc48435d9dd1af3dc17fa7d9e2af9beb16cc77bd38150c4697efdf232",
+        "token": "0412e48b124199f683e0ea6b8a1f1b073013dce21610de4b54cac74696e02003b1147d3ad7b4cef542c6ef61726dc4ffba039c90f7edd17cbeafb7c0737b41fc82",
+        "regOTT": "11adb574045ffe27e718d8b4dc665887",
+        "timePermitCache": {
+          "date": 16867,
+          "timePermit": "041c990c4087b5eeb7f4c2dbe5869794c208a22f63f6485a8905b35f542b2136a91cccf0696a6c60b2208ff1d3178da8fa661f7a52dda7db2738bfb1fe8b6cfa4b"
+        }
+      }
+    },
+    "deviceName": "winChrome"
+  };
+
+  return {
+    Errors: Errors,
+    MPINAuth: MPINAuth,
+    MPIN: MPIN,
+    testData: testData,
+    testLocalStorage: testLocalStorage,
+    testLocalStorage2: testLocalStorage2
+  };
+}();
+
+if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
+  module.exports = inits;
+else
+  window.inits = inits;
diff --git a/test/mocha.opts b/test/mocha.opts
new file mode 100644
index 0000000..47d63c7
--- /dev/null
+++ b/test/mocha.opts
@@ -0,0 +1,2 @@
+--recursive
+--timeout 5000
\ No newline at end of file