From ef2e3051f797fd7de85a8829d2f8910dcda4261e Mon Sep 17 00:00:00 2001 From: Ivan Todinov Date: Tue, 10 Nov 2026 09:35:03 +0200 Subject: [PATCH] refactor: replace prototype with class --- src/client.js | 1709 ++++++++++++++++++++++++------------------------- src/crypto.js | 392 ++++++------ src/http.js | 141 ++-- src/users.js | 291 ++++----- 4 files changed, 1268 insertions(+), 1265 deletions(-) diff --git a/src/client.js b/src/client.js index 00ae84e..1570e3b 100644 --- a/src/client.js +++ b/src/client.js @@ -3,1020 +3,1019 @@ import HTTP from "./http.js"; import { parseUriParams } from "./uri.js"; import Users from "./users.js"; -/** - * @class - * @param {Object} options - * @param {string} options.projectUrl - MIRACL Trust Project URL used for communication with the MIRACL Trust API - * @param {string} options.projectId - MIRACL Trust Project ID - * @param {string} options.seed - Hex-encoded random number generator seed - * @param {string} options.deviceName - Name of the current device - * @param {Object} options.userStorage - Storage for saving user data - * @param {bool} options.cors - Enable CORS requests if set to 'true' - * @param {number} options.requestTimeout - Time before an HTTP request times out in milliseconds - * @param {string} options.applicationInfo - Set additional information that will be sent via X-MIRACL-CLIENT HTTP header - */ -export default function Client(options) { - if (!options) { - throw new Error("Invalid configuration"); - } +export default class Client{ + /** + * @param {Object} options + * @param {string} options.projectUrl - MIRACL Trust Project URL used for communication with the MIRACL Trust API + * @param {string} options.projectId - MIRACL Trust Project ID + * @param {string} options.seed - Hex-encoded random number generator seed + * @param {string} options.deviceName - Name of the current device + * @param {Object} options.userStorage - Storage for saving user data + * @param {bool} options.cors - Enable CORS requests if set to 'true' + * @param {number} options.requestTimeout - Time before an HTTP request times out in milliseconds + * @param {string} options.applicationInfo - Set additional information that will be sent via X-MIRACL-CLIENT HTTP header + */ + constructor(options) { + if (!options) { + throw new Error("Invalid configuration"); + } - if (!options.projectId) { - throw new Error("Empty project ID"); - } + if (!options.projectId) { + throw new Error("Empty project ID"); + } + + if (!options.userStorage) { + throw new Error("Invalid user storage"); + } + + if (!options.projectUrl) { + options.projectUrl = "https://api.mpin.io"; + } else { + // Remove trailing slash from URL, if there is one + options.projectUrl = options.projectUrl.replace(/\/$/, ""); + } + + // Ensure the default PIN length is between 4 and 6 + if (!options.defaultPinLength || options.defaultPinLength > 6 || options.defaultPinLength < 4) { + options.defaultPinLength = 4; + } - if (!options.userStorage) { - throw new Error("Invalid user storage"); + if (!options.requestTimeout || isNaN(options.requestTimeout)) { + options.requestTimeout = 4000; + } + + // Set the client name using the current lib version and provided application info + options.clientName = "MIRACL Client.js/8.13.0" + (options.applicationInfo ? " " + options.applicationInfo : ""); + + this.options = options; + + this.crypto = new Crypto(options.seed); + + this.http = new HTTP(options.requestTimeout, options.clientName, this._getDeviceName(), this._getDeviceTag(), options.projectId, options.cors); + + this.users = new Users(options.userStorage, options.projectId, "mfa"); + + this.session = {}; } - if (!options.projectUrl) { - options.projectUrl = "https://api.mpin.io"; - } else { - // Remove trailing slash from URL, if there is one - options.projectUrl = options.projectUrl.replace(/\/$/, ""); + /** + * @deprecated Operation is now implicit; safe to remove + * + * Set the access/session ID + * + * @param {string} accessId + */ + setAccessId(accessId) { + this.session.accessId = accessId; } - // Ensure the default PIN length is between 4 and 6 - if (!options.defaultPinLength || options.defaultPinLength > 6 || options.defaultPinLength < 4) { - options.defaultPinLength = 4; + /** + * @deprecated Use `createCrossDeviceSession` instead + * + * Make a request to start a new session and fetch the access/session ID + * + * @param {string} userId - The unique identifier of the user that will be authenticating (not required) + * @param {function(Error, Object)} callback + */ + fetchAccessId(userId, callback) { + const reqData = { + url: this.options.projectUrl + "/rps/v2/session", + type: "POST", + data: { + projectId: this.options.projectId, + userId: userId + } + }; + + this.http.request(reqData, (error, res) => { + if (error) { + return callback(error, null); + } + + this.session = res; + + callback(null, res); + }); } - if (!options.requestTimeout || isNaN(options.requestTimeout)) { - options.requestTimeout = 4000; + /** + * @deprecated Use `checkCrossDeviceSessionStatus` instead + * + * Get session status + * + * @param {function(Error, Object)} callback + */ + fetchStatus(callback) { + const reqData = { + url: this.options.projectUrl + "/rps/v2/access", + type: "POST", + data: { + webOTT: this.session.webOTT + } + }; + + this.http.request(reqData, (error, data) => { + if (error) { + return callback(error, null); + } + + callback(null, data); + }); } - // Set the client name using the current lib version and provided application info - options.clientName = "MIRACL Client.js/8.13.0" + (options.applicationInfo ? " " + options.applicationInfo : ""); + /** + * @deprecated Use `createCrossDeviceSession` and `sendPushNotification` instead + * + * Start the push authentication flow + * + * @param {string} userId - The unique identifier of the user that will be authenticating + * @param {function(Error, Object)} callback + */ + sendPushNotificationForAuth(userId, callback) { + if (!userId) { + return callback(new Error("Empty user ID"), null); + } - this.options = options; + const reqData = { + url: this.options.projectUrl + "/pushauth", + type: "POST", + data: { + projectId: this.options.projectId, + prerollId: userId + } + }; - this.crypto = new Crypto(options.seed); + this.http.request(reqData, (err, result) => { + if (err) { + if (result && result.error === "NO_PUSH_TOKEN") { + return callback(new Error("No push token", { cause: err }), null); + } - this.http = new HTTP(options.requestTimeout, options.clientName, this._getDeviceName(), this._getDeviceTag(), options.projectId, options.cors); + return callback(err, null); + } - this.users = new Users(options.userStorage, options.projectId, "mfa"); -} + this.session.webOTT = result.webOTT; -Client.prototype.options = {}; - -Client.prototype.session = {}; - -/** - * @deprecated Operation is now implicit; safe to remove - * - * Set the access/session ID - * - * @param {string} accessId - */ -Client.prototype.setAccessId = function (accessId) { - this.session.accessId = accessId; -}; - -/** - * @deprecated Use `createCrossDeviceSession` instead - * - * Make a request to start a new session and fetch the access/session ID - * - * @param {string} userId - The unique identifier of the user that will be authenticating (not required) - * @param {function(Error, Object)} callback - */ -Client.prototype.fetchAccessId = function (userId, callback) { - const reqData = { - url: this.options.projectUrl + "/rps/v2/session", - type: "POST", - data: { - projectId: this.options.projectId, - userId: userId - } - }; + callback(null, result); + }); + } - this.http.request(reqData, (error, res) => { - if (error) { - return callback(error, null); + /** + * Start the verification process for a specified User ID (must be an email address) + * + * @param {string} userId - The email address for which to start verification + * @param {function(Error, Object)} callback + */ + sendVerificationEmail(userId, callback) { + if (!userId) { + return callback(new Error("Empty user ID"), null); } - this.session = res; - - callback(null, res); - }); -}; - -/** - * @deprecated Use `checkCrossDeviceSessionStatus` instead - * - * Get session status - * - * @param {function(Error, Object)} callback - */ -Client.prototype.fetchStatus = function (callback) { - const reqData = { - url: this.options.projectUrl + "/rps/v2/access", - type: "POST", - data: { - webOTT: this.session.webOTT - } - }; + const reqData = { + url: this.options.projectUrl + "/verification/email", + type: "POST", + data: { + userId: userId, + projectId: this.options.projectId, + accessId: this.session.accessId, + deviceName: this._getDeviceName(), + deviceTag: this._getDeviceTag() + } + }; + + this.http.request(reqData, (err, result) => { + if (err) { + if (result && result.error === "REQUEST_BACKOFF") { + return callback(new Error("Request backoff", { cause: err }), result); + } + + return callback(new Error("Verification fail", { cause: err }), result); + } + + callback(null, result); + }); + } + + /** + * Finish the verification process + * + * @param {string} verificationURI - The URI received in the email containing the verification code + * @param {function(Error, Object)} callback + */ + getActivationToken(verificationURI, callback) { + const params = parseUriParams(verificationURI); - this.http.request(reqData, (error, data) => { - if (error) { - return callback(error, null); + if (!params["user_id"]) { + return callback(new Error("Empty user ID"), null); } - callback(null, data); - }); -}; - -/** - * @deprecated Use `createCrossDeviceSession` and `sendPushNotification` instead - * - * Start the push authentication flow - * - * @param {string} userId - The unique identifier of the user that will be authenticating - * @param {function(Error, Object)} callback - */ -Client.prototype.sendPushNotificationForAuth = function (userId, callback) { - if (!userId) { - return callback(new Error("Empty user ID"), null); - } - - const reqData = { - url: this.options.projectUrl + "/pushauth", - type: "POST", - data: { - projectId: this.options.projectId, - prerollId: userId + if (!params["code"]) { + return callback(new Error("Empty verification code"), null); } - }; - this.http.request(reqData, (err, result) => { - if (err) { - if (result && result.error === "NO_PUSH_TOKEN") { - return callback(new Error("No push token", { cause: err }), null); + const reqData = { + url: this.options.projectUrl + "/verification/confirmation", + type: "POST", + data: { + userId: params["user_id"], + code: params["code"], + deviceTag: this._getDeviceTag() } + }; - return callback(err, null); + this.http.request(reqData, (err, result) => { + if (err) { + if (result && result.error === "UNSUCCESSFUL_VERIFICATION") { + return callback(new Error("Unsuccessful verification", { cause: err }), result); + } + + return callback(new Error("Get activation token fail", { cause: err }), result); + } + + result.userId = params["user_id"]; + callback(null, result); + }); + } + + /** + * Create an identity for the specified User ID + * + * @param {string} userId - The unique identifier of the user + * @param {string} activationToken - The code received from the verification process + * @param {function} pinCallback - Called when the PIN code needs to be entered + * @param {function(Error, Object)} callback + */ + register(userId, activationToken, pinCallback, callback) { + if (!userId) { + return callback(new Error("Empty user ID"), null); } - this.session.webOTT = result.webOTT; - - callback(null, result); - }); -}; - -/** - * Start the verification process for a specified User ID (must be an email address) - * - * @param {string} userId - The email address for which to start verification - * @param {function(Error, Object)} callback - */ -Client.prototype.sendVerificationEmail = function (userId, callback) { - if (!userId) { - return callback(new Error("Empty user ID"), null); - } - - const reqData = { - url: this.options.projectUrl + "/verification/email", - type: "POST", - data: { - userId: userId, - projectId: this.options.projectId, - accessId: this.session.accessId, - deviceName: this._getDeviceName(), - deviceTag: this._getDeviceTag() + if (!activationToken) { + return callback(new Error("Empty activation token"), null); } - }; - this.http.request(reqData, (err, result) => { - if (err) { - if (result && result.error === "REQUEST_BACKOFF") { - return callback(new Error("Request backoff", { cause: err }), result); + const keypair = this.crypto.generateKeypair(); + + this._createMPinID(userId, activationToken, keypair, (err, identityData) => { + if (err) { + if (identityData && identityData.error === "INVALID_ACTIVATION_TOKEN") { + return callback(new Error("Invalid activation token", { cause: err }), null); + } + + return callback(new Error("Registration fail", { cause: err }), null); } - return callback(new Error("Verification fail", { cause: err }), result); - } + if (identityData.projectId !== this.options.projectId) { + return callback(new Error("Project mismatch"), null); + } - callback(null, result); - }); -}; + let pinLength = identityData.pinLength; + if (!pinLength) { + pinLength = this.options.defaultPinLength; + } + + this._getTAShares(identityData.designatedTAs, identityData.mpinId, keypair.publicKey, (err, secData) => { + if (err) { + return callback(new Error("Registration fail", { cause: err }), null); + } -/** - * Finish the verification process - * - * @param {string} verificationURI - The URI received in the email containing the verification code - * @param {function(Error, Object)} callback - */ -Client.prototype.getActivationToken = function (verificationURI, callback) { - const params = parseUriParams(verificationURI); + // Should be called to continue the flow after a PIN was provided + const passPin = (userPin) => { + this._createIdentity(userId, userPin, identityData, secData[0], secData[1], keypair, callback); + }; - if (!params["user_id"]) { - return callback(new Error("Empty user ID"), null); + pinCallback(passPin, pinLength); + }); + }); } - if (!params["code"]) { - return callback(new Error("Empty verification code"), null); + _createMPinID(userId, activationToken, keypair, callback) { + const regData = { + url: this.options.projectUrl + "/registration", + type: "POST", + data: { + userId: userId, + deviceName: this._getDeviceName(), + deviceTag: this._getDeviceTag(), + activationToken: activationToken, + publicKey: keypair.publicKey, + ver: 2 + } + }; + + this.http.request(regData, (err, result) => { + if (err) { + return callback(err, result); + } + + callback(null, result); + }); } - const reqData = { - url: this.options.projectUrl + "/verification/confirmation", - type: "POST", - data: { - userId: params["user_id"], - code: params["code"], - deviceTag: this._getDeviceTag() + _getDeviceName() { + if (this.options.deviceName) { + return this.options.deviceName; } - }; - this.http.request(reqData, (err, result) => { - if (err) { - if (result && result.error === "UNSUCCESSFUL_VERIFICATION") { - return callback(new Error("Unsuccessful verification", { cause: err }), result); - } + return "Browser"; + } - return callback(new Error("Get activation token fail", { cause: err }), result); + _getDeviceTag() { + const tag = this.options.userStorage.getItem("miraclDeviceTag"); + if (tag) { + return tag; } - result.userId = params["user_id"]; - callback(null, result); - }); -}; + let newTag; + try { + newTag = this.crypto.randomString(16); + this.options.userStorage.setItem("miraclDeviceTag", newTag); + } catch (err) { + newTag = ""; + } -/** - * Create an identity for the specified User ID - * - * @param {string} userId - The unique identifier of the user - * @param {string} activationToken - The code received from the verification process - * @param {function} pinCallback - Called when the PIN code needs to be entered - * @param {function(Error, Object)} callback - */ -Client.prototype.register = function (userId, activationToken, pinCallback, callback) { - if (!userId) { - return callback(new Error("Empty user ID"), null); + return newTag; } - if (!activationToken) { - return callback(new Error("Empty activation token"), null); - } + _getTAShares(designatedTas, mpinId, publicKey, callback) { + const results = []; + const errors = []; - const keypair = this.crypto.generateKeypair(); + let pending = designatedTas.length; - this._createMPinID(userId, activationToken, keypair, (err, identityData) => { - if (err) { - if (identityData && identityData.error === "INVALID_ACTIVATION_TOKEN") { - return callback(new Error("Invalid activation token", { cause: err }), null); - } + for (let i = 0; i < designatedTas.length; i++) { + this._getTAShare(designatedTas[i], mpinId, publicKey, (err, result) => { + if (err) { + errors.push(err); + } else { + results[i] = result; + } - return callback(new Error("Registration fail", { cause: err }), null); - } + if (--pending === 0) { + if (errors.length > 0) { + return callback(new Error("Failed to get shares", { cause: errors }), null); + } - if (identityData.projectId !== this.options.projectId) { - return callback(new Error("Project mismatch"), null); + callback(null, results); + } + }); } + } - let pinLength = identityData.pinLength; - if (!pinLength) { - pinLength = this.options.defaultPinLength; - } + _getTAShare(designatedTa, mpinId, publicKey, callback) { + const requestData = { + type: "POST", + url: designatedTa.url, + authorization: "Bearer " + designatedTa.token, + data: { + mpinId: mpinId, + pubKey: publicKey + } + }; - this._getTAShares(identityData.designatedTAs, identityData.mpinId, keypair.publicKey, (err, secData) => { + this.http.request(requestData, (err, result) => { if (err) { - return callback(new Error("Registration fail", { cause: err }), null); + return callback(err, null); } - // Should be called to continue the flow after a PIN was provided - const passPin = (userPin) => { - this._createIdentity(userId, userPin, identityData, secData[0], secData[1], keypair, callback); - }; - - pinCallback(passPin, pinLength); + callback(null, result); }); - }); -}; - -Client.prototype._createMPinID = function (userId, activationToken, keypair, callback) { - const regData = { - url: this.options.projectUrl + "/registration", - type: "POST", - data: { - userId: userId, - deviceName: this._getDeviceName(), - deviceTag: this._getDeviceTag(), - activationToken: activationToken, - publicKey: keypair.publicKey, - ver: 2 - } - }; + } - this.http.request(regData, (err, result) => { - if (err) { - return callback(err, result); + _createIdentity(userId, userPin, identityData, sec1Data, sec2Data, keypair, callback) { + let csHex, token; + + try { + csHex = this.crypto.addShares(keypair.privateKey, sec1Data.share, sec2Data.share); + token = this.crypto.extractPin(identityData.mpinId, keypair.publicKey, userPin, csHex); + } catch (err) { + return callback(err, null); } - callback(null, result); - }); -}; + const dtas = btoa(JSON.stringify([sec1Data.node, sec2Data.node])); -Client.prototype._getDeviceName = function () { - if (this.options.deviceName) { - return this.options.deviceName; + const userData = { + mpinId: identityData.mpinId, + token: token, + curve: "BN254CX", + dtas: dtas, + publicKey: keypair.publicKey, + pinLength: identityData.pinLength, + projectId: identityData.projectId, + verificationType: identityData.verificationType, + state: this.users.states.register, + nowTime: identityData.nowTime, + updated: Math.floor(Date.now() / 1000) + }; + this.users.write(userId, userData); + + callback(null, userData); } - return "Browser"; -}; + /** + * Authenticate the user with the specified User ID + * + * @param {string} userId - The unique identifier of the user + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, Object)} callback + */ + authenticate(userId, userPin, callback) { + this._authentication(userId, userPin, ["jwt"], "", callback); + } -Client.prototype._getDeviceTag = function () { - const tag = this.options.userStorage.getItem("miraclDeviceTag"); - if (tag) { - return tag; + /** + * @deprecated Use `getCrossDeviceSessionFromQRCode` and `authenticateCrossDeviceSession` instead + * + * Authenticate the user for the session specified by the qrCode parameter + * + * @param {string} userId - The unique identifier of the user + * @param {string} qrCode - The QR code URL that initiated the authentication + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, Object)} callback + */ + authenticateWithQRCode(userId, qrCode, userPin, callback) { + const accessId = qrCode.split("#").pop(); + + this._authentication(userId, userPin, ["oidc"], accessId, callback); } - let newTag; - try { - newTag = this.crypto.randomString(16); - this.options.userStorage.setItem("miraclDeviceTag", newTag); - } catch (err) { - newTag = ""; + /** + * @deprecated Use `getCrossDeviceSessionFromLink` and `authenticateCrossDeviceSession` instead + * + * Authenticate the user for the session specified by the appLink parameter + * + * @param {string} userId - The unique identifier of the user + * @param {string} appLink - The app link that initiated the authentication + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, Object)} callback + */ + authenticateWithAppLink(userId, appLink, userPin, callback) { + const accessId = appLink.split("#").pop(); + + this._authentication(userId, userPin, ["oidc"], accessId, callback); } - return newTag; -}; + /** + * @deprecated Use `getCrossDeviceSessionFromNotificationPayload` and `authenticateCrossDeviceSession` instead + * + * Authenticate the session specified by the push notification payload + * + * @param {[key: string]: string} payload - The push notification payload + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, Object)} callback + */ + authenticateWithNotificationPayload(payload, userPin, callback) { + if (!payload || !payload["userID"] || !payload["qrURL"]) { + return callback(new Error("Invalid push notification payload"), null); + } -Client.prototype._getTAShares = function (designatedTas, mpinId, publicKey, callback) { - const results = []; - const errors = []; + const accessId = payload["qrURL"].split("#").pop(); - let pending = designatedTas.length; + this._authentication(payload["userID"], userPin, ["oidc"], accessId, callback); + } - for (let i = 0; i < designatedTas.length; i++) { - this._getTAShare(designatedTas[i], mpinId, publicKey, (err, result) => { + /** + * Fetch a registration (bootstrap) code for the specified User ID + * + * @param {string} userId - The unique identifier of the user + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, Object)} callback + */ + generateQuickCode(userId, userPin, callback) { + this._authentication(userId, userPin, ["reg-code"], "", (err, result) => { if (err) { - errors.push(err); - } else { - results[i] = result; + return callback(err, null); } - if (--pending === 0) { - if (errors.length > 0) { - return callback(new Error("Failed to get shares", { cause: errors }), null); + this.http.request({ + url: this.options.projectUrl + "/verification/quickcode", + type: "POST", + data: { + projectId: this.options.projectId, + jwt: result.jwt, + deviceName: this._getDeviceName() + } + }, (err, result) => { + if (err) { + return callback(err, null); } - callback(null, results); - } + callback(null, { + code: result.code, + expireTime: result.expireTime, + ttlSeconds: result.ttlSeconds, + // Deprecated, kept for backward compatibility + OTP: result.code + }); + }); }); } -}; -Client.prototype._getTAShare = function (designatedTa, mpinId, publicKey, callback) { - const requestData = { - type: "POST", - url: designatedTa.url, - authorization: "Bearer " + designatedTa.token, - data: { - mpinId: mpinId, - pubKey: publicKey + _authentication(userId, userPin, scope, accessId, callback) { + if (!userId) { + return callback(new Error("Empty user ID"), null); } - }; - this.http.request(requestData, (err, result) => { - if (err) { - return callback(err, null); + if (!this.users.exists(userId)) { + return callback(new Error("User not found"), null); } - callback(null, result); - }); -}; - -Client.prototype._createIdentity = function (userId, userPin, identityData, sec1Data, sec2Data, keypair, callback) { - let csHex, token; - - try { - csHex = this.crypto.addShares(keypair.privateKey, sec1Data.share, sec2Data.share); - token = this.crypto.extractPin(identityData.mpinId, keypair.publicKey, userPin, csHex); - } catch (err) { - return callback(err, null); - } - - const dtas = btoa(JSON.stringify([sec1Data.node, sec2Data.node])); - - const userData = { - mpinId: identityData.mpinId, - token: token, - curve: "BN254CX", - dtas: dtas, - publicKey: keypair.publicKey, - pinLength: identityData.pinLength, - projectId: identityData.projectId, - verificationType: identityData.verificationType, - state: this.users.states.register, - nowTime: identityData.nowTime, - updated: Math.floor(Date.now() / 1000) - }; - this.users.write(userId, userData); - - callback(null, userData); -}; - -/** - * Authenticate the user with the specified User ID - * - * @param {string} userId - The unique identifier of the user - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, Object)} callback - */ -Client.prototype.authenticate = function (userId, userPin, callback) { - this._authentication(userId, userPin, ["jwt"], "", callback); -}; - -/** - * @deprecated Use `getCrossDeviceSessionFromQRCode` and `authenticateCrossDeviceSession` instead - * - * Authenticate the user for the session specified by the qrCode parameter - * - * @param {string} userId - The unique identifier of the user - * @param {string} qrCode - The QR code URL that initiated the authentication - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, Object)} callback - */ -Client.prototype.authenticateWithQRCode = function (userId, qrCode, userPin, callback) { - const accessId = qrCode.split("#").pop(); - - this._authentication(userId, userPin, ["oidc"], accessId, callback); -}; - -/** - * @deprecated Use `getCrossDeviceSessionFromLink` and `authenticateCrossDeviceSession` instead - * - * Authenticate the user for the session specified by the appLink parameter - * - * @param {string} userId - The unique identifier of the user - * @param {string} appLink - The app link that initiated the authentication - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, Object)} callback - */ -Client.prototype.authenticateWithAppLink = function (userId, appLink, userPin, callback) { - const accessId = appLink.split("#").pop(); - - this._authentication(userId, userPin, ["oidc"], accessId, callback); -}; - -/** - * @deprecated Use `getCrossDeviceSessionFromNotificationPayload` and `authenticateCrossDeviceSession` instead - * - * Authenticate the session specified by the push notification payload - * - * @param {[key: string]: string} payload - The push notification payload - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, Object)} callback - */ -Client.prototype.authenticateWithNotificationPayload = function (payload, userPin, callback) { - if (!payload || !payload["userID"] || !payload["qrURL"]) { - return callback(new Error("Invalid push notification payload"), null); - } - - const accessId = payload["qrURL"].split("#").pop(); - - this._authentication(payload["userID"], userPin, ["oidc"], accessId, callback); -}; - -/** - * Fetch a registration (bootstrap) code for the specified User ID - * - * @param {string} userId - The unique identifier of the user - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, Object)} callback - */ -Client.prototype.generateQuickCode = function (userId, userPin, callback) { - this._authentication(userId, userPin, ["reg-code"], "", (err, result) => { - if (err) { - return callback(err, null); - } + const identityData = this.users.get(userId); - this.http.request({ - url: this.options.projectUrl + "/verification/quickcode", - type: "POST", - data: { - projectId: this.options.projectId, - jwt: result.jwt, - deviceName: this._getDeviceName() - } - }, (err, result) => { + const SEC = [], X = []; + + this._getPass1(identityData, userPin, scope, X, SEC, (err, pass1Data) => { if (err) { - return callback(err, null); + if (pass1Data && pass1Data.error === "EXPIRED_MPINID") { + this.users.write(userId, { state: this.users.states.revoked }); + return callback(new Error("Revoked", { cause: err }), null); + } + + return callback(new Error("Authentication fail", { cause: err }), null); } - callback(null, { - code: result.code, - expireTime: result.expireTime, - ttlSeconds: result.ttlSeconds, - // Deprecated, kept for backward compatibility - OTP: result.code + this._getPass2(identityData, scope, accessId, pass1Data.y, X, SEC, (err, pass2Data) => { + if (err) { + return callback(new Error("Authentication fail", { cause: err }), null); + } + + this._finishAuthentication(userId, userPin, scope, accessId, pass2Data.authOTT, (err, result) => { + if (err) { + if (result && result.error === "UNSUCCESSFUL_AUTHENTICATION") { + return callback(new Error("Unsuccessful authentication", { cause: err }), null); + } + + if (result && result.error === "REVOKED_MPINID") { + this.users.write(userId, { state: this.users.states.revoked }); + return callback(new Error("Revoked", { cause: err }), null); + } + + return callback(new Error("Authentication fail", { cause: err }), null); + } + + callback(null, result); + }); }); }); - }); -}; - -Client.prototype._authentication = function (userId, userPin, scope, accessId, callback) { - if (!userId) { - return callback(new Error("Empty user ID"), null); } - if (!this.users.exists(userId)) { - return callback(new Error("User not found"), null); - } + /** + * Make a request for pass one of the M-PIN protocol + * + * This function assigns a random value to the property X. It assigns the sum of the Client Secret + * and time permit to the property SEC. It also + * calculates the values U and UT which are required for M-Pin authentication, + * where U = X.(map_to_curve(MPIN_ID)) and UT = X.(map_to_curve(MPIN_ID) + map_to_curve(DATE|sha256(MPIN_ID)) + * UT is called the commitment. U is required for finding the PIN error. + * + * Request data has the following structure: + * { + * mpin_id: mpinIdHex, // Hex-encoded M-PIN ID + * dtas: dtaList // Identifier of the DTAs used for this identity + * UT: UT_hex, // Hex-encoded UT + * U: U_hex, // Hex-encoded U + * publicKey: publicKey, // The public key used for DVS + * scope: ['oidc'] // Scope of the authentication + * } + * @private + */ + _getPass1(identityData, userPin, scope, X, SEC, callback) { + let res; - const identityData = this.users.get(userId); + try { + res = this.crypto.calculatePass1(identityData.mpinId, identityData.publicKey, identityData.token, userPin, X, SEC); + } catch (err) { + return callback(err, null); + } - const SEC = [], X = []; + const requestData = { + scope: scope, + mpin_id: identityData.mpinId, // eslint-disable-line camelcase + dtas: identityData.dtas, // eslint-disable-line camelcase + publicKey: identityData.publicKey, + UT: res.UT, + U: res.U + }; - this._getPass1(identityData, userPin, scope, X, SEC, (err, pass1Data) => { - if (err) { - if (pass1Data && pass1Data.error === "EXPIRED_MPINID") { - this.users.write(userId, { state: this.users.states.revoked }); - return callback(new Error("Revoked", { cause: err }), null); - } + this.http.request({ url: this.options.projectUrl + "/rps/v2/pass1", type: "POST", data: requestData }, callback); + } - return callback(new Error("Authentication fail", { cause: err }), null); + /** + * Make a request for pass two of the M-Pin protocol + * + * This function uses the random value y from the server, property X + * and the combined Client Secret and time permit to calculate + * the value V which is sent to the M-PIN server. + * + * Request data has the following structure: + * { + * mpin_id: mpinIdHex, // Hex-encoded M-PIN ID + * V: V_hex, // Value required by the server to authenticate user + * WID: accessNumber // Number required for mobile authentication + * } + * @private + */ + _getPass2(identityData, scope, accessId, yHex, X, SEC, callback) { + let vHex; + + try { + vHex = this.crypto.calculatePass2(X, yHex, SEC); + } catch (err) { + return callback(err, null); } - this._getPass2(identityData, scope, accessId, pass1Data.y, X, SEC, (err, pass2Data) => { + const requestData = { + mpin_id: identityData.mpinId, // eslint-disable-line camelcase + WID: accessId, + V: vHex + }; + + this.http.request({ url: this.options.projectUrl + "/rps/v2/pass2", type: "POST", data: requestData}, callback); + } + + _finishAuthentication(userId, userPin, scope, accessId, authOTT, callback) { + const requestData = { + "authOTT": authOTT, + "wam": "dvs" + }; + + this.http.request({ url: this.options.projectUrl + "/rps/v2/authenticate", type: "POST", data: requestData }, (err, result) => { if (err) { - return callback(new Error("Authentication fail", { cause: err }), null); + return callback(err, result); } - this._finishAuthentication(userId, userPin, scope, accessId, pass2Data.authOTT, (err, result) => { - if (err) { - if (result && result.error === "UNSUCCESSFUL_AUTHENTICATION") { - return callback(new Error("Unsuccessful authentication", { cause: err }), null); + if (result.dvsRegister) { + this._renewSecret(userId, userPin, result.dvsRegister, (err) => { + if (err) { + return callback(err, null); } - if (result && result.error === "REVOKED_MPINID") { - this.users.write(userId, { state: this.users.states.revoked }); - return callback(new Error("Revoked", { cause: err }), null); - } - - return callback(new Error("Authentication fail", { cause: err }), null); - } - + this._authentication(userId, userPin, scope, accessId, callback); + }); + } else { + this.users.updateLastUsed(userId); callback(null, result); - }); + } }); - }); -}; - -/** - * Make a request for pass one of the M-PIN protocol - * - * This function assigns a random value to the property X. It assigns the sum of the Client Secret - * and time permit to the property SEC. It also - * calculates the values U and UT which are required for M-Pin authentication, - * where U = X.(map_to_curve(MPIN_ID)) and UT = X.(map_to_curve(MPIN_ID) + map_to_curve(DATE|sha256(MPIN_ID)) - * UT is called the commitment. U is required for finding the PIN error. - * - * Request data has the following structure: - * { - * mpin_id: mpinIdHex, // Hex-encoded M-PIN ID - * dtas: dtaList // Identifier of the DTAs used for this identity - * UT: UT_hex, // Hex-encoded UT - * U: U_hex, // Hex-encoded U - * publicKey: publicKey, // The public key used for DVS - * scope: ['oidc'] // Scope of the authentication - * } - * @private - */ -Client.prototype._getPass1 = function (identityData, userPin, scope, X, SEC, callback) { - let res; - - try { - res = this.crypto.calculatePass1(identityData.mpinId, identityData.publicKey, identityData.token, userPin, X, SEC); - } catch (err) { - return callback(err, null); - } - - const requestData = { - scope: scope, - mpin_id: identityData.mpinId, // eslint-disable-line camelcase - dtas: identityData.dtas, // eslint-disable-line camelcase - publicKey: identityData.publicKey, - UT: res.UT, - U: res.U - }; - - this.http.request({ url: this.options.projectUrl + "/rps/v2/pass1", type: "POST", data: requestData }, callback); -}; - -/** - * Make a request for pass two of the M-Pin protocol - * - * This function uses the random value y from the server, property X - * and the combined Client Secret and time permit to calculate - * the value V which is sent to the M-PIN server. - * - * Request data has the following structure: - * { - * mpin_id: mpinIdHex, // Hex-encoded M-PIN ID - * V: V_hex, // Value required by the server to authenticate user - * WID: accessNumber // Number required for mobile authentication - * } - * @private - */ -Client.prototype._getPass2 = function (identityData, scope, accessId, yHex, X, SEC, callback) { - let vHex; - - try { - vHex = this.crypto.calculatePass2(X, yHex, SEC); - } catch (err) { - return callback(err, null); - } - - const requestData = { - mpin_id: identityData.mpinId, // eslint-disable-line camelcase - WID: accessId, - V: vHex - }; - - this.http.request({ url: this.options.projectUrl + "/rps/v2/pass2", type: "POST", data: requestData}, callback); -}; - -Client.prototype._finishAuthentication = function (userId, userPin, scope, accessId, authOTT, callback) { - const requestData = { - "authOTT": authOTT, - "wam": "dvs" - }; - - this.http.request({ url: this.options.projectUrl + "/rps/v2/authenticate", type: "POST", data: requestData }, (err, result) => { - if (err) { - return callback(err, result); - } + } + + _renewSecret(userId, userPin, activationData, callback) { + const keypair = this.crypto.generateKeypair(); - if (result.dvsRegister) { - this._renewSecret(userId, userPin, result.dvsRegister, (err) => { + this._createMPinID(userId, activationData.token, keypair, (err, identityData) => { + if (err) { + return callback(err, null); + } + + this._getTAShares(identityData.designatedTAs, identityData.mpinId, keypair.publicKey, (err, secData) => { if (err) { return callback(err, null); } - this._authentication(userId, userPin, scope, accessId, callback); + this._createIdentity(userId, userPin, identityData, secData[0], secData[1], keypair, callback); }); - } else { - this.users.updateLastUsed(userId); - callback(null, result); + }); + } + + /** + * Create a cryptographic signature of a given message + * + * @param {string} userId - The unique identifier of the user + * @param {string} userPin - The PIN associated with the userId + * @param {string} message - The message that will be signed + * @param {number} timestamp - The creation timestamp of the message + * @param {function(Error, Object)} callback + */ + sign(userId, userPin, message, timestamp, callback) { + if (!userId) { + return callback(new Error("Empty user ID"), null); } - }); -}; -Client.prototype._renewSecret = function (userId, userPin, activationData, callback) { - const keypair = this.crypto.generateKeypair(); + if (!this.users.exists(userId)) { + return callback(new Error("User not found"), null); + } - this._createMPinID(userId, activationData.token, keypair, (err, identityData) => { - if (err) { - return callback(err, null); + if (!message) { + return callback(new Error("Empty message"), null); } - this._getTAShares(identityData.designatedTAs, identityData.mpinId, keypair.publicKey, (err, secData) => { + this._authentication(userId, userPin, ["dvs-auth"], "", (err) => { if (err) { - return callback(err, null); + switch (err.message) { + case "Unsuccessful authentication": + case "Revoked": + return callback(err, null); + + default: + return callback(new Error("Signing fail", { cause: err.cause }), null); + } } - this._createIdentity(userId, userPin, identityData, secData[0], secData[1], keypair, callback); - }); - }); -}; + const identityData = this.users.get(userId); -/** - * Create a cryptographic signature of a given message - * - * @param {string} userId - The unique identifier of the user - * @param {string} userPin - The PIN associated with the userId - * @param {string} message - The message that will be signed - * @param {number} timestamp - The creation timestamp of the message - * @param {function(Error, Object)} callback - */ -Client.prototype.sign = function (userId, userPin, message, timestamp, callback) { - if (!userId) { - return callback(new Error("Empty user ID"), null); - } + let res; - if (!this.users.exists(userId)) { - return callback(new Error("User not found"), null); - } + try { + res = this.crypto.sign(identityData.mpinId, identityData.publicKey, identityData.token, userPin, message, timestamp); + } catch (err) { + return callback(new Error("Signing fail", { cause: err }), null); + } + + const signatureData = { + hash: message, + u: res.U, + v: res.V, + mpinId: identityData.mpinId, + publicKey: identityData.publicKey, + dtas: identityData.dtas + }; - if (!message) { - return callback(new Error("Empty message"), null); + callback(null, signatureData); + }); } - this._authentication(userId, userPin, ["dvs-auth"], "", (err) => { - if (err) { - switch (err.message) { - case "Unsuccessful authentication": - case "Revoked": - return callback(err, null); + /** + * @typedef {Object} CrossDeviceSession + * @property {string} type + * @property {string} projectId + * @property {string} token + * @property {string} sessionId + * @property {string} url + * @property {string} userId + * @property {string} description + * @property {string} signingHash + * @property {number} expireTime + */ + + /** + * Create a cross-device session for authentication or signing + * + * @param {string} [userId] - The unique identifier of the user + * @param {string} [description] - Description of the operation + * @param {string} [signingHash] - Hash of the message to be signed; only required for signing + * @param {function(Error, CrossDeviceSession): void} callback + */ + createCrossDeviceSession(userId, description, signingHash, callback) { + if (signingHash && !userId) { + return callback(new Error("Session for signing must be created with user ID"), null); + } - default: - return callback(new Error("Signing fail", { cause: err.cause }), null); + const reqData = { + url: this.options.projectUrl + "/rps/v2/session", + type: "POST", + data: { + projectId: this.options.projectId, + userId: userId, + hash: signingHash, + description: description } - } + }; - const identityData = this.users.get(userId); + this.http.request(reqData, (error, res) => { + if (error) { + return callback(error, null); + } - let res; + callback(null, { + type: signingHash ? "signing" : "authentication", + projectId: this.options.projectId, + token: res.webOTT, + sessionId: res.accessId, + url: res.qrURL, + userId: userId || null, + description: description || null, + signingHash: signingHash || null, + expireTime: res.expireTime + }); + }); + } - try { - res = this.crypto.sign(identityData.mpinId, identityData.publicKey, identityData.token, userPin, message, timestamp); - } catch (err) { - return callback(new Error("Signing fail", { cause: err }), null); + /** + * @typedef {Object} CrossDeviceSessionStatus + * @property {string} status + * @property {string} userId + * @property {string} jwt + * @property {string} signature + */ + + /** + * Check the status of a given cross-device session + * + * @param {CrossDeviceSession} crossDeviceSession + * @param {function(Error, CrossDeviceSessionStatus): void} callback + */ + checkCrossDeviceSessionStatus(crossDeviceSession, callback) { + if (!crossDeviceSession.token) { + return callback(new Error("Invalid cross-device session"), null); } - const signatureData = { - hash: message, - u: res.U, - v: res.V, - mpinId: identityData.mpinId, - publicKey: identityData.publicKey, - dtas: identityData.dtas + const reqData = { + url: this.options.projectUrl + "/rps/v2/access", + type: "POST", + data: { + webOTT: crossDeviceSession.token + } }; - callback(null, signatureData); - }); -}; - -/** - * @typedef {Object} CrossDeviceSession - * @property {string} type - * @property {string} projectId - * @property {string} token - * @property {string} sessionId - * @property {string} url - * @property {string} userId - * @property {string} description - * @property {string} signingHash - * @property {number} expireTime - */ - -/** - * Create a cross-device session for authentication or signing - * - * @param {string} [userId] - The unique identifier of the user - * @param {string} [description] - Description of the operation - * @param {string} [signingHash] - Hash of the message to be signed; only required for signing - * @param {function(Error, CrossDeviceSession): void} callback - */ -Client.prototype.createCrossDeviceSession = function (userId, description, signingHash, callback) { - if (signingHash && !userId) { - return callback(new Error("Session for signing must be created with user ID"), null); - } - - const reqData = { - url: this.options.projectUrl + "/rps/v2/session", - type: "POST", - data: { - projectId: this.options.projectId, - userId: userId, - hash: signingHash, - description: description - } - }; - - this.http.request(reqData, (error, res) => { - if (error) { - return callback(error, null); - } + this.http.request(reqData, (error, data) => { + if (error) { + return callback(error, null); + } - callback(null, { - type: signingHash ? "signing" : "authentication", - projectId: this.options.projectId, - token: res.webOTT, - sessionId: res.accessId, - url: res.qrURL, - userId: userId || null, - description: description || null, - signingHash: signingHash || null, - expireTime: res.expireTime + callback(null, { + status: data.status, + userId: data.userId || null, + jwt: data.jwt || null, + signature: data.signature || null + }); }); - }); -}; - -/** - * @typedef {Object} CrossDeviceSessionStatus - * @property {string} status - * @property {string} userId - * @property {string} jwt - * @property {string} signature - */ - -/** - * Check the status of a given cross-device session - * - * @param {CrossDeviceSession} crossDeviceSession - * @param {function(Error, CrossDeviceSessionStatus): void} callback - */ -Client.prototype.checkCrossDeviceSessionStatus = function (crossDeviceSession, callback) { - if (!crossDeviceSession.token) { - return callback(new Error("Invalid cross-device session"), null); - } - - const reqData = { - url: this.options.projectUrl + "/rps/v2/access", - type: "POST", - data: { - webOTT: crossDeviceSession.token - } - }; + } - this.http.request(reqData, (error, data) => { - if (error) { - return callback(error, null); + /** + * Send push notification for an existing cross-device session + * + * @param {CrossDeviceSession} crossDeviceSession + * @param {function(Error, any): void} callback + */ + sendPushNotification(crossDeviceSession, callback) { + if (!crossDeviceSession.userId) { + return callback(new Error("Cross device session created without user ID"), null); } - callback(null, { - status: data.status, - userId: data.userId || null, - jwt: data.jwt || null, - signature: data.signature || null + const reqData = { + url: this.options.projectUrl + "/push", + type: "POST", + data: { + projectId: this.options.projectId, + userId: crossDeviceSession.userId, + accessId: crossDeviceSession.sessionId + } + }; + + this.http.request(reqData, (err, result) => { + if (err) { + if (result && result.error === "NO_PUSH_TOKEN") { + return callback(new Error("No push token", { cause: err }), null); + } + + return callback(err, null); + } + + callback(null, result); }); - }); -}; - -/** - * Send push notification for an existing cross-device session - * - * @param {CrossDeviceSession} crossDeviceSession - * @param {function(Error, any): void} callback - */ -Client.prototype.sendPushNotification = function (crossDeviceSession, callback) { - if (!crossDeviceSession.userId) { - return callback(new Error("Cross device session created without user ID"), null); - } - - const reqData = { - url: this.options.projectUrl + "/push", - type: "POST", - data: { - projectId: this.options.projectId, - userId: crossDeviceSession.userId, - accessId: crossDeviceSession.sessionId + } + + /** + * Gets the CrossDeviceSession for a QR code + * + * @param {string} qrCode - The QR code URL that initiated the session + * @param {function(Error, CrossDeviceSession): void} callback + */ + getCrossDeviceSessionFromQRCode(qrCode, callback) { + this._getCrossDeviceSession(qrCode, callback); + } + + /** + * Gets CrossDeviceSession for app link or universal link + * + * @param {string} link - The app link that initiated the session + * @param {function(Error, CrossDeviceSession): void} callback + */ + getCrossDeviceSessionFromLink(link, callback) { + this._getCrossDeviceSession(link, callback); + } + + /** + * Gets the CrossDeviceSession from a notification payload + * + * @param {[key: string]: string} payload - The push notification payload + * @param {function(Error, CrossDeviceSession): void} callback + */ + getCrossDeviceSessionFromNotificationPayload(payload, callback) { + if (!payload || !payload["qrURL"]) { + return callback(new Error("Invalid push notification payload"), null); } - }; - this.http.request(reqData, (err, result) => { - if (err) { - if (result && result.error === "NO_PUSH_TOKEN") { - return callback(new Error("No push token", { cause: err }), null); + this._getCrossDeviceSession(payload["qrURL"], callback); + } + + /** + * @private + * + * Get a cross-device session from a session URL + * + * @param {string} url - The URL of the session + * @param {function(Error, CrossDeviceSession): void} callback + */ + _getCrossDeviceSession(url, callback) { + const accessId = url.split("#").pop(); + + const reqData = { + url: this.options.projectUrl + "/rps/v2/codeStatus", + type: "POST", + data: { + status: "wid", + wid: accessId } + }; - return callback(err, null); - } + this.http.request(reqData, (error, data) => { + if (error) { + return callback(new Error("Get cross-device session request failed", { cause: error }), null); + } + + callback(null, { + type: data.hash ? "signing" : "authentication", + projectId: data.projectId, + token: null, + sessionId: accessId, + url: url, + userId: data.prerollId || null, + description: data.description || null, + signingHash: data.hash || null, + expireTime: data.expireTime + }); + }); + } - callback(null, result); - }); -}; - -/** - * Gets the CrossDeviceSession for a QR code - * - * @param {string} qrCode - The QR code URL that initiated the session - * @param {function(Error, CrossDeviceSession): void} callback - */ -Client.prototype.getCrossDeviceSessionFromQRCode = function (qrCode, callback) { - this._getCrossDeviceSession(qrCode, callback); -}; - -/** - * Gets CrossDeviceSession for app link or universal link - * - * @param {string} link - The app link that initiated the session - * @param {function(Error, CrossDeviceSession): void} callback - */ -Client.prototype.getCrossDeviceSessionFromLink = function (link, callback) { - this._getCrossDeviceSession(link, callback); -}; - -/** - * Gets the CrossDeviceSession from a notification payload - * - * @param {[key: string]: string} payload - The push notification payload - * @param {function(Error, CrossDeviceSession): void} callback - */ -Client.prototype.getCrossDeviceSessionFromNotificationPayload = function (payload, callback) { - if (!payload || !payload["qrURL"]) { - return callback(new Error("Invalid push notification payload"), null); - } - - this._getCrossDeviceSession(payload["qrURL"], callback); -}; - -/** - * @private - * - * Get a cross-device session from a session URL - * - * @param {string} url - The URL of the session - * @param {function(Error, CrossDeviceSession): void} callback - */ -Client.prototype._getCrossDeviceSession = function (url, callback) { - const accessId = url.split("#").pop(); - - const reqData = { - url: this.options.projectUrl + "/rps/v2/codeStatus", - type: "POST", - data: { - status: "wid", - wid: accessId + /** + * Authenticate a cross-device session + * + * @param {CrossDeviceSession} crossDeviceSession + * @param {string} userId - The unique identifier of the user + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, any): void} callback + */ + authenticateCrossDeviceSession(crossDeviceSession, userId, userPin, callback) { + if (crossDeviceSession.userId && crossDeviceSession.userId !== userId) { + return callback(new Error("Cross-device session was initiated for different user ID"), null); } - }; - this.http.request(reqData, (error, data) => { - if (error) { - return callback(new Error("Get cross-device session request failed", { cause: error }), null); + this._authentication(userId, userPin, ["jwt"], crossDeviceSession.sessionId, callback); + } + + /** + * Generates a signature for a hash provided by the crossDeviceSession and updates the session + * + * @param {CrossDeviceSession} crossDeviceSession + * @param {string} userId - The unique identifier of the user + * @param {string} userPin - The PIN associated with the userId + * @param {function(Error, any): void} callback + */ + signCrossDeviceSession(crossDeviceSession, userId, userPin, callback) { + if (crossDeviceSession.userId && crossDeviceSession.userId !== userId) { + return callback(new Error("Cross-device session was initiated for different user ID"), null); } - callback(null, { - type: data.hash ? "signing" : "authentication", - projectId: data.projectId, - token: null, - sessionId: accessId, - url: url, - userId: data.prerollId || null, - description: data.description || null, - signingHash: data.hash || null, - expireTime: data.expireTime + const timestamp = Math.floor(new Date().getTime() / 1000); + + this.sign(userId, userPin, crossDeviceSession.signingHash, timestamp, (error, signature) => { + if (error) { + return callback(error, null); + } + + const reqData = { + url: this.options.projectUrl + "/rps/v2/codeStatus", + type: "POST", + data: { + status: "signed", + wid: crossDeviceSession.sessionId, + signature: btoa(JSON.stringify(signature)) + } + }; + + this.http.request(reqData, (error, data) => { + if (error) { + return callback(new Error("Updating cross-device session failed", { cause: error }), null); + } + + callback(null, data); + }); }); - }); -}; - -/** - * Authenticate a cross-device session - * - * @param {CrossDeviceSession} crossDeviceSession - * @param {string} userId - The unique identifier of the user - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, any): void} callback - */ -Client.prototype.authenticateCrossDeviceSession = function (crossDeviceSession, userId, userPin, callback) { - if (crossDeviceSession.userId && crossDeviceSession.userId !== userId) { - return callback(new Error("Cross-device session was initiated for different user ID"), null); - } - - this._authentication(userId, userPin, ["jwt"], crossDeviceSession.sessionId, callback); -}; - -/** - * Generates a signature for a hash provided by the crossDeviceSession and updates the session - * - * @param {CrossDeviceSession} crossDeviceSession - * @param {string} userId - The unique identifier of the user - * @param {string} userPin - The PIN associated with the userId - * @param {function(Error, any): void} callback - */ -Client.prototype.signCrossDeviceSession = function (crossDeviceSession, userId, userPin, callback) { - if (crossDeviceSession.userId && crossDeviceSession.userId !== userId) { - return callback(new Error("Cross-device session was initiated for different user ID"), null); - } - - const timestamp = Math.floor(new Date().getTime() / 1000); - - this.sign(userId, userPin, crossDeviceSession.signingHash, timestamp, (error, signature) => { - if (error) { - return callback(error, null); - } + } + /** + * Abort a cross-device session + * + * @param {CrossDeviceSession} crossDeviceSession - The session to abort + * @param {function(Error, any): void} callback + */ + abortCrossDeviceSession(crossDeviceSession, callback) { const reqData = { url: this.options.projectUrl + "/rps/v2/codeStatus", type: "POST", data: { - status: "signed", - wid: crossDeviceSession.sessionId, - signature: btoa(JSON.stringify(signature)) + status: "abort", + wid: crossDeviceSession.sessionId } }; this.http.request(reqData, (error, data) => { if (error) { - return callback(new Error("Updating cross-device session failed", { cause: error }), null); + return callback(new Error("Aborting cross-device session failed", { cause: error }), null); } callback(null, data); }); - }); -}; - -/** - * Abort a cross-device session - * - * @param {CrossDeviceSession} crossDeviceSession - The session to abort - * @param {function(Error, any): void} callback - */ -Client.prototype.abortCrossDeviceSession = function (crossDeviceSession, callback) { - const reqData = { - url: this.options.projectUrl + "/rps/v2/codeStatus", - type: "POST", - data: { - status: "abort", - wid: crossDeviceSession.sessionId - } - }; - - this.http.request(reqData, (error, data) => { - if (error) { - return callback(new Error("Aborting cross-device session failed", { cause: error }), null); - } - - callback(null, data); - }); -}; + } +} diff --git a/src/crypto.js b/src/crypto.js index 6a2ac7e..338949c 100644 --- a/src/crypto.js +++ b/src/crypto.js @@ -2,200 +2,202 @@ import CTX from "@miracl/crypto-js"; const CryptoContexts = {}; -export default function Crypto(seed) { - // Initialize RNG - this.rng = new (this._crypto().RAND)(); - this.rng.clean(); - - // Seed the RNG - const entropyBytes = this._hexToBytes(seed); - this.rng.seed(entropyBytes.length, entropyBytes); -} - -Crypto.prototype._crypto = function (curve) { - // Set to default curve if not provided - if (!curve) { - curve = "BN254CX"; - } - - if (!CryptoContexts[curve]) { - // Create a new curve context - CryptoContexts[curve] = new CTX(curve); - - // Change maximum PIN length to 6 digits - CryptoContexts[curve].MPIN.MAXPIN = 1000000; - - // Modify M-PIN settings - CryptoContexts[curve].MPIN.PBLEN = 20; - CryptoContexts[curve].MPIN.TRAP = 2000; - } - - return CryptoContexts[curve]; -}; - -Crypto.prototype.generateKeypair = function (curve) { - const privateKeyBytes = []; - const publicKeyBytes = []; - - const errorCode = this._crypto(curve).MPIN.GET_DVS_KEYPAIR(this.rng, privateKeyBytes, publicKeyBytes); - if (errorCode !== 0) { - throw new Error("Could not generate key pair: " + errorCode); +export default class Crypto { + constructor(seed) { + // Initialize RNG + this.rng = new (this._crypto().RAND)(); + this.rng.clean(); + + // Seed the RNG + const entropyBytes = hexToBytes(seed); + this.rng.seed(entropyBytes.length, entropyBytes); + } + + _crypto(curve) { + // Set to default curve if not provided + if (!curve) { + curve = "BN254CX"; + } + + if (!CryptoContexts[curve]) { + // Create a new curve context + CryptoContexts[curve] = new CTX(curve); + + // Change maximum PIN length to 6 digits + CryptoContexts[curve].MPIN.MAXPIN = 1000000; + + // Modify M-PIN settings + CryptoContexts[curve].MPIN.PBLEN = 20; + CryptoContexts[curve].MPIN.TRAP = 2000; + } + + return CryptoContexts[curve]; + } + + generateKeypair(curve) { + const privateKeyBytes = []; + const publicKeyBytes = []; + + const errorCode = this._crypto(curve).MPIN.GET_DVS_KEYPAIR(this.rng, privateKeyBytes, publicKeyBytes); + if (errorCode !== 0) { + throw new Error("Could not generate key pair: " + errorCode); + } + + return { publicKey: bytesToHex(publicKeyBytes), privateKey: bytesToHex(privateKeyBytes) }; + } + + /** + * Add two points on the curve that are originally in hex format + * This function is used to add Client Secret shares. + * Returns a hex-encoded sum of the shares + * @private + */ + addShares(privateKeyHex, share1Hex, share2Hex, curve) { + const privateKeyBytes = hexToBytes(privateKeyHex); + const share1Bytes = hexToBytes(share1Hex); + const share2Bytes = hexToBytes(share2Hex); + const clientSecretBytes = []; + + const errorCodeRecombine = this._crypto(curve).MPIN.RECOMBINE_G1(share1Bytes, share2Bytes, clientSecretBytes); + if (errorCodeRecombine !== 0) { + throw new Error("Could not combine the client secret shares: " + errorCodeRecombine); + } + + const errorCodeG1 = this._crypto(curve).MPIN.GET_G1_MULTIPLE(null, 0, privateKeyBytes, clientSecretBytes, clientSecretBytes); + if (errorCodeG1 !== 0) { + throw new Error("Could not combine private key with client secret: " + errorCodeG1); + } + + return bytesToHex(clientSecretBytes); + } + + /** + * Calculates the M-PIN Token + * This function maps the M-PIN ID to a point on the curve, + * multiplies this value by PIN and then subtracts it from + * the Client Secret curve point to generate the M-PIN token. + * Returns a hex-encoded M-PIN Token + * @private + */ + extractPin(mpinId, publicKey, PIN, clientSecretHex, curve) { + const clientSecretBytes = hexToBytes(clientSecretHex); + const mpinIdBytes = hexToBytes(this._mpinIdWithPublicKey(mpinId, publicKey)); + + const errorCode = this._crypto(curve).MPIN.EXTRACT_PIN(this._crypto(curve).MPIN.SHA256, mpinIdBytes, PIN, clientSecretBytes); + if (errorCode !== 0) { + throw new Error("Could not extract PIN from client secret: " + errorCode); + } + + return bytesToHex(clientSecretBytes); + } + + calculatePass1(mpinId, publicKey, token, userPin, X, SEC, curve) { + const U = [], UT = []; + + const mpinIdHex = this._mpinIdWithPublicKey(mpinId, publicKey); + + const errorCode = this._crypto(curve).MPIN.CLIENT_1( + this._crypto(curve).MPIN.SHA256, + 0, + hexToBytes(mpinIdHex), + this.rng, + X, + userPin, + hexToBytes(token), + SEC, + U, + UT, + hexToBytes(0) + ); + + if (errorCode !== 0) { + throw new Error("Could not calculate pass 1 request data: " + errorCode); + } + + return { + UT: bytesToHex(UT), + U: bytesToHex(U) + }; + } + + calculatePass2(X, yHex, SEC, curve) { + const errorCode = this._crypto(curve).MPIN.CLIENT_2(X, hexToBytes(yHex), SEC); + if (errorCode !== 0) { + throw new Error("Could not calculate pass 2 request data: " + errorCode); + } + + return bytesToHex(SEC); + } + + sign(mpinId, publicKey, token, userPin, message, timestamp, curve) { + const SEC = []; + const X = []; + const Y1 = []; + const U = []; + + const mpinIdHex = this._mpinIdWithPublicKey(mpinId, publicKey); + + const errorCode = this._crypto(curve).MPIN.CLIENT( + this._crypto(curve).MPIN.SHA256, + 0, + hexToBytes(mpinIdHex), + this.rng, + X, + userPin, + hexToBytes(token), + SEC, + U, + null, + null, + timestamp, + Y1, + hexToBytes(message) + ); + + if (errorCode !== 0) { + throw new Error("Could not sign message: " + errorCode); + } + + return { + U: bytesToHex(U), + V: bytesToHex(SEC) + }; + } + + randomString(len) { + const byteArr = new Array(len); + for (let i = 0; i < len; ++i) { + byteArr[i] = this.rng.getByte(); + } + + return bytesToHex(byteArr); + } + + /** + * Returns the public key bytes appended to the M-PIN ID bytes in hex encoding + * @private + */ + _mpinIdWithPublicKey(mpinId, publicKey) { + const mpinIdBytes = hexToBytes(mpinId); + const publicKeyBytes = hexToBytes(publicKey); + + if (!mpinIdBytes) { + return; + } + + if (!publicKeyBytes) { + return mpinId; + } + + for (let i = 0; i < publicKeyBytes.length; i++) { + mpinIdBytes.push(publicKeyBytes[i]); + } + + return bytesToHex(mpinIdBytes); } +} - return { publicKey: this._bytesToHex(publicKeyBytes), privateKey: this._bytesToHex(privateKeyBytes) }; -}; - -/** - * Add two points on the curve that are originally in hex format - * This function is used to add Client Secret shares. - * Returns a hex-encoded sum of the shares - * @private - */ -Crypto.prototype.addShares = function (privateKeyHex, share1Hex, share2Hex, curve) { - const privateKeyBytes = this._hexToBytes(privateKeyHex); - const share1Bytes = this._hexToBytes(share1Hex); - const share2Bytes = this._hexToBytes(share2Hex); - const clientSecretBytes = []; - - const errorCodeRecombine = this._crypto(curve).MPIN.RECOMBINE_G1(share1Bytes, share2Bytes, clientSecretBytes); - if (errorCodeRecombine !== 0) { - throw new Error("Could not combine the client secret shares: " + errorCodeRecombine); - } - - const errorCodeG1 = this._crypto(curve).MPIN.GET_G1_MULTIPLE(null, 0, privateKeyBytes, clientSecretBytes, clientSecretBytes); - if (errorCodeG1 !== 0) { - throw new Error("Could not combine private key with client secret: " + errorCodeG1); - } - - return this._bytesToHex(clientSecretBytes); -}; - -/** - * Calculates the M-PIN Token - * This function maps the M-PIN ID to a point on the curve, - * multiplies this value by PIN and then subtracts it from - * the Client Secret curve point to generate the M-PIN token. - * Returns a hex-encoded M-PIN Token - * @private - */ -Crypto.prototype.extractPin = function (mpinId, publicKey, PIN, clientSecretHex, curve) { - const clientSecretBytes = this._hexToBytes(clientSecretHex); - const mpinIdBytes = this._hexToBytes(this._mpinIdWithPublicKey(mpinId, publicKey)); - - const errorCode = this._crypto(curve).MPIN.EXTRACT_PIN(this._crypto(curve).MPIN.SHA256, mpinIdBytes, PIN, clientSecretBytes); - if (errorCode !== 0) { - throw new Error("Could not extract PIN from client secret: " + errorCode); - } - - return this._bytesToHex(clientSecretBytes); -}; - -Crypto.prototype.calculatePass1 = function (mpinId, publicKey, token, userPin, X, SEC, curve) { - const U = [], UT = []; - - const mpinIdHex = this._mpinIdWithPublicKey(mpinId, publicKey); - - const errorCode = this._crypto(curve).MPIN.CLIENT_1( - this._crypto(curve).MPIN.SHA256, - 0, - this._hexToBytes(mpinIdHex), - this.rng, - X, - userPin, - this._hexToBytes(token), - SEC, - U, - UT, - this._hexToBytes(0) - ); - - if (errorCode !== 0) { - throw new Error("Could not calculate pass 1 request data: " + errorCode); - } - - return { - UT: this._bytesToHex(UT), - U: this._bytesToHex(U) - }; -}; - -Crypto.prototype.calculatePass2 = function (X, yHex, SEC, curve) { - const errorCode = this._crypto(curve).MPIN.CLIENT_2(X, this._hexToBytes(yHex), SEC); - if (errorCode !== 0) { - throw new Error("Could not calculate pass 2 request data: " + errorCode); - } - - return this._bytesToHex(SEC); -}; - -Crypto.prototype.sign = function (mpinId, publicKey, token, userPin, message, timestamp, curve) { - const SEC = []; - const X = []; - const Y1 = []; - const U = []; - - const mpinIdHex = this._mpinIdWithPublicKey(mpinId, publicKey); - - const errorCode = this._crypto(curve).MPIN.CLIENT( - this._crypto(curve).MPIN.SHA256, - 0, - this._hexToBytes(mpinIdHex), - this.rng, - X, - userPin, - this._hexToBytes(token), - SEC, - U, - null, - null, - timestamp, - Y1, - this._hexToBytes(message) - ); - - if (errorCode !== 0) { - throw new Error("Could not sign message: " + errorCode); - } - - return { - U: this._bytesToHex(U), - V: this._bytesToHex(SEC) - }; -}; - -Crypto.prototype.randomString = function (len) { - const byteArr = new Array(len); - for (let i = 0; i < len; ++i) { - byteArr[i] = this.rng.getByte(); - } - - return this._bytesToHex(byteArr); -}; - -/** - * Returns the public key bytes appended to the M-PIN ID bytes in hex encoding - * @private - */ -Crypto.prototype._mpinIdWithPublicKey = function (mpinId, publicKey) { - const mpinIdBytes = this._hexToBytes(mpinId); - const publicKeyBytes = this._hexToBytes(publicKey); - - if (!mpinIdBytes) { - return; - } - - if (!publicKeyBytes) { - return mpinId; - } - - for (let i = 0; i < publicKeyBytes.length; i++) { - mpinIdBytes.push(publicKeyBytes[i]); - } - - return this._bytesToHex(mpinIdBytes); -}; - -Crypto.prototype._hexToBytes = function (hexValue) { +function hexToBytes(hexValue) { if (!hexValue) { return; } @@ -207,9 +209,9 @@ Crypto.prototype._hexToBytes = function (hexValue) { } return byteValue; -}; +} -Crypto.prototype._bytesToHex = function (b) { +function bytesToHex(b) { let s = ""; for (let i = 0; i < b.length; i++) { @@ -219,4 +221,4 @@ Crypto.prototype._bytesToHex = function (b) { } return s; -}; +} diff --git a/src/http.js b/src/http.js index fe26132..bac133e 100644 --- a/src/http.js +++ b/src/http.js @@ -1,85 +1,86 @@ -export default function HTTP(timeout, clientName, deviceName, deviceTag, projectId, cors) { - this.requestTimeout = timeout; - this.clientName = clientName; - this.deviceName = deviceName; - this.deviceTag = deviceTag; - this.projectId = projectId; - this.cors = cors; -} - -/** - * Make an HTTP request - * @private - */ -HTTP.prototype.request = function (options, callback) { - if (typeof callback !== "function") { - throw new Error("Bad or missing callback"); - } - - if (!options.url) { - throw new Error("Missing URL for request"); +export default class HTTP { + constructor(timeout, clientName, deviceName, deviceTag, projectId, cors) { + this.requestTimeout = timeout; + this.clientName = clientName; + this.deviceName = deviceName; + this.deviceTag = deviceTag; + this.projectId = projectId; + this.cors = cors; } - const request = new XMLHttpRequest(); - - request.onreadystatechange = function () { - let response; - - if (request.readyState === 4 && request.status === 200) { - try { - response = JSON.parse(request.responseText); - } catch (e) { - response = request.responseText; - } + /** + * Make an HTTP request + */ + request(options, callback) { + if (typeof callback !== "function") { + throw new Error("Bad or missing callback"); + } - callback(null, response); - } else if (request.readyState === 4) { - if (request.status === 0) { - callback(new Error("The request was aborted"), { status: 0 }); - return; - } + if (!options.url) { + throw new Error("Missing URL for request"); + } - try { - response = JSON.parse(request.responseText); - } catch (e) { - callback(new Error(request.statusText), { status: request.status }); - return; + const request = new XMLHttpRequest(); + + request.onreadystatechange = function () { + let response; + + if (request.readyState === 4 && request.status === 200) { + try { + response = JSON.parse(request.responseText); + } catch (e) { + response = request.responseText; + } + + callback(null, response); + } else if (request.readyState === 4) { + if (request.status === 0) { + callback(new Error("The request was aborted"), { status: 0 }); + return; + } + + try { + response = JSON.parse(request.responseText); + } catch (e) { + callback(new Error(request.statusText), { status: request.status }); + return; + } + + callback(new Error(response.info), { + status: request.status, + error: response.error, + context: response.context + }); } + }; - callback(new Error(response.info), { - status: request.status, - error: response.error, - context: response.context - }); + let url = options.url; + if (this.cors) { + url += (url.indexOf("?") !== -1 ? "&" : "?") + "project_id=" + this.projectId; } - }; - let url = options.url; - if (this.cors) { - url += (url.indexOf("?") !== -1 ? "&" : "?") + "project_id=" + this.projectId; - } + const type = options.type || "GET"; - const type = options.type || "GET"; + request.open(type, url, true); - request.open(type, url, true); + request.timeout = this.requestTimeout; - request.timeout = this.requestTimeout; + request.setRequestHeader("X-Miracl-Client", this.clientName); + request.setRequestHeader("X-Miracl-Device-Name", this.deviceName); + request.setRequestHeader("X-Miracl-Device-Tag", this.deviceTag); - request.setRequestHeader("X-Miracl-Client", this.clientName); - request.setRequestHeader("X-Miracl-Device-Name", this.deviceName); - request.setRequestHeader("X-Miracl-Device-Tag", this.deviceTag); + // Set authorization header if provided + if (options.authorization) { + request.setRequestHeader("Authorization", options.authorization); + } - // Set authorization header if provided - if (options.authorization) { - request.setRequestHeader("Authorization", options.authorization); - } + if (options.data) { + request.setRequestHeader("Content-Type", "application/json"); + request.send(JSON.stringify(options.data)); + } else { + request.send(); + } - if (options.data) { - request.setRequestHeader("Content-Type", "application/json"); - request.send(JSON.stringify(options.data)); - } else { - request.send(); + return request; } - - return request; -}; +} diff --git a/src/users.js b/src/users.js index 2d2d420..10eda7f 100644 --- a/src/users.js +++ b/src/users.js @@ -1,186 +1,187 @@ /** * User management utility. Initialized by {@link Client} - * @class - * - * @param {Object} storage - * @param {string} projectId - * @param {string} storageKey */ -export default function Users(storage, projectId, storageKey) { - if (typeof storage.getItem !== "function" || typeof storage.setItem !== "function") { - throw new Error("Invalid user storage object"); - } +export default class Users { + /** + * @param {Object} storage + * @param {string} projectId + * @param {string} storageKey + */ + constructor(storage, projectId, storageKey) { + if (typeof storage.getItem !== "function" || typeof storage.setItem !== "function") { + throw new Error("Invalid user storage object"); + } - if (!projectId) { - throw new Error("Project ID must be provided when configuring storage"); - } + if (!projectId) { + throw new Error("Project ID must be provided when configuring storage"); + } - if (!storageKey) { - throw new Error("Storage key must be provided when configuring storage"); - } + if (!storageKey) { + throw new Error("Storage key must be provided when configuring storage"); + } - this.storage = storage; - this.projectId = projectId; - this.storageKey = storageKey; + this.storage = storage; + this.projectId = projectId; + this.storageKey = storageKey; - this.loadData(); -} + this.data = []; + this.loadData(); -Users.prototype.data = [], - -Users.prototype.states = { - start: "STARTED", - register: "REGISTERED", - revoked: "REVOKED" -}; + this.states = { + start: "STARTED", + register: "REGISTERED", + revoked: "REVOKED" + }; + } -Users.prototype.loadData = function () { - this.data = JSON.parse(this.storage.getItem(this.storageKey)) || []; + loadData() { + this.data = JSON.parse(this.storage.getItem(this.storageKey)) || []; - this.store(); + this.store(); - // Sort list by last used timestamp - this.data.sort((a, b) => { - if (a.lastUsed && (!b.lastUsed || a.lastUsed > b.lastUsed)) { - return 1; - } + // Sort list by last used timestamp + this.data.sort((a, b) => { + if (a.lastUsed && (!b.lastUsed || a.lastUsed > b.lastUsed)) { + return 1; + } - if (b.lastUsed && (!a.lastUsed || a.lastUsed < b.lastUsed)) { - return -1; - } + if (b.lastUsed && (!a.lastUsed || a.lastUsed < b.lastUsed)) { + return -1; + } - return 0; - }); -}; - -Users.prototype.write = function (userId, userData) { - if (!this.exists(userId)) { - this.data.push({ - userId: userId, - projectId: this.projectId, - state: this.states.invalid, - created: Math.round(new Date().getTime() / 1000) + return 0; }); } - for (let i = 0; i < this.data.length; ++i) { - if (this.data[i].userId === userId && (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId)) { - for (const uKey in userData) { - if (userData[uKey]) { - this.data[i][uKey] = userData[uKey]; + write(userId, userData) { + if (!this.exists(userId)) { + this.data.push({ + userId: userId, + projectId: this.projectId, + state: this.states.invalid, + created: Math.round(new Date().getTime() / 1000) + }); + } + + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].userId === userId && (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId)) { + for (const uKey in userData) { + if (userData[uKey]) { + this.data[i][uKey] = userData[uKey]; + } } } } - } - this.store(); -}; + this.store(); + } -Users.prototype.updateLastUsed = function (userId) { - this.write(userId, { lastUsed: new Date().getTime() }); -}; + updateLastUsed(userId) { + this.write(userId, { lastUsed: new Date().getTime() }); + } -/** - * Check if an user with the specified User ID exists - * @param {string} userId - The ID of the user - * @returns {boolean} - */ -Users.prototype.exists = function (userId) { - return typeof this.get(userId, "userId") !== "undefined"; -}; + /** + * Check if an user with the specified User ID exists + * @param {string} userId - The ID of the user + * @returns {boolean} + */ + exists(userId) { + return typeof this.get(userId, "userId") !== "undefined"; + } -/** - * Check if an user is in a specific state - * @param {string} userId - The ID of the user - * @param {string} state - The state to check for - * @returns {boolean} - Returns true if the state of the user matches the state argument - */ -Users.prototype.is = function (userId, state) { - return this.get(userId, "state") === state; -}; + /** + * Check if an user is in a specific state + * @param {string} userId - The ID of the user + * @param {string} state - The state to check for + * @returns {boolean} - Returns true if the state of the user matches the state argument + */ + is(userId, state) { + return this.get(userId, "state") === state; + } -/** - * Get a property of the user - * @param {string} userId - The ID of the user - * @param {string} userProperty - The name of the property to be fetched - * @returns {string} - The value of the user property. Will return undefined if property doesn't exist - */ -Users.prototype.get = function (userId, userProperty) { - for (let i = 0; i < this.data.length; ++i) { - if (this.data[i].userId === userId && (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId)) { - if (userProperty) { - // Return requested property - return this.data[i][userProperty] || ""; - } else { - // Return the whole user data if no property is requested - return this.data[i]; + /** + * Get a property of the user + * @param {string} userId - The ID of the user + * @param {string} userProperty - The name of the property to be fetched + * @returns {string} - The value of the user property. Will return undefined if property doesn't exist + */ + get(userId, userProperty) { + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].userId === userId && (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId)) { + if (userProperty) { + // Return requested property + return this.data[i][userProperty] || ""; + } else { + // Return the whole user data if no property is requested + return this.data[i]; + } } } } -}; -/** - * List all identities - * @returns {Object} - */ -Users.prototype.list = function () { - const usersList = {}; - for (let i = 0; i < this.data.length; ++i) { - if (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId) { - usersList[this.data[i].userId] = this.data[i].state; + /** + * List all identities + * @returns {Object} + */ + list() { + const usersList = {}; + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId) { + usersList[this.data[i].userId] = this.data[i].state; + } } - } - return usersList; -}; - -/** - * Returns an array of all user objects - * @returns {Array} - */ -Users.prototype.all = function () { - const users = []; - for (let i = 0; i < this.data.length; ++i) { - if (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId) { - users.push(this.data[i]); - } + return usersList; } - return users; -}; + /** + * Returns an array of all user objects + * @returns {Array} + */ + all() { + const users = []; + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId) { + users.push(this.data[i]); + } + } -/** - * Returns the number of registered identities - * @return {number} - */ -Users.prototype.count = function () { - return Object.keys(this.list()).length; -}; + return users; + } -/** - * Remove an identity - * @param {string} userId - The ID of the user - */ -Users.prototype.remove = function (userId) { - if (!this.exists(userId)) { - return; + /** + * Returns the number of registered identities + * @return {number} + */ + count() { + return Object.keys(this.list()).length; } - for (let i = 0; i < this.data.length; ++i) { - if (this.data[i].userId === userId && (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId)) { - this.data.splice(i, 1); + /** + * Remove an identity + * @param {string} userId - The ID of the user + */ + remove(userId) { + if (!this.exists(userId)) { + return; } - } - this.store(); -}; + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].userId === userId && (this.data[i].projectId === this.projectId || this.data[i].customerId === this.projectId)) { + this.data.splice(i, 1); + } + } -Users.prototype.store = function () { - // Ensure that there is no sensitive data before storing it - for (let i = 0; i < this.data.length; ++i) { - delete this.data[i].csHex; - delete this.data[i].regOTT; + this.store(); } - this.storage.setItem(this.storageKey, JSON.stringify(this.data)); -}; + store() { + // Ensure that there is no sensitive data before storing it + for (let i = 0; i < this.data.length; ++i) { + delete this.data[i].csHex; + delete this.data[i].regOTT; + } + + this.storage.setItem(this.storageKey, JSON.stringify(this.data)); + } +}