@mytmpvpn/mytmpvpn-client
Version:
MyTmpVpn Client Library
148 lines (147 loc) • 6.12 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTestUserProfile = exports.createPassword = exports.AuthImpl = void 0;
// src/auth.ts
const auth = __importStar(require("amazon-cognito-identity-js"));
const clientLib = __importStar(require("./client"));
const utils = __importStar(require("@mytmpvpn/mytmpvpn-common/utils"));
const errors_1 = require("@mytmpvpn/mytmpvpn-common/errors");
const logging_1 = require("./logging");
class AuthImpl {
constructor(appConfig, userProfile) {
this.session = null;
this.userPool = new auth.CognitoUserPool({
UserPoolId: appConfig.userPoolId,
ClientId: appConfig.userPoolClientId,
});
this.userProfile = userProfile;
this.cognitoUser = new auth.CognitoUser({
Username: this.userProfile.username,
Pool: this.userPool
});
this.client = new clientLib.MyTmpVpnClientImpl(appConfig.apiUrl);
}
async login() {
return new Promise((resolve, reject) => {
const authenticationDetails = new auth.AuthenticationDetails({
Username: this.userProfile.username,
Password: this.userProfile.password
});
this.cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: session => resolve(session),
onFailure: err => reject(err)
});
});
}
async authenticate() {
logging_1.logger.debug(`Authenticating user ${JSON.stringify(this.userProfile)}`);
// Try to get existing session
try {
this.session = await new Promise((resolve, reject) => {
this.cognitoUser.getSession((err, session) => {
if (err)
reject(err);
else
resolve(session);
});
});
}
catch (err) {
// No session found, let's login
if (!this.userProfile.password) {
throw new errors_1.MyTmpVpnError(`Specify a password in profile ${JSON.stringify(this.userProfile)}`);
}
logging_1.logger.debug(`Session not found for user ${JSON.stringify(this.cognitoUser)}, logging in`);
this.session = await this.login();
}
logging_1.logger.debug(`Setting user session ${JSON.stringify(this.session)} to client: ${JSON.stringify(this.client)}`);
this.client.setUserSession(this.cognitoUser, this.session);
// Validate session
if (!this.getUser() || !this.getSession()) {
throw new errors_1.MyTmpVpnError(`No session found in client: ${JSON.stringify(this.client)}`);
}
return this.client;
}
async register() {
return new Promise((resolve, reject) => {
const userAttributes = [];
const validationData = [];
this.userPool.signUp(this.userProfile.username, this.userProfile.password ?? '', userAttributes, validationData, (err, result) => {
if (err)
reject(err);
else
resolve(result.user);
});
});
}
async confirmRegistration(code) {
return new Promise((resolve, reject) => {
this.cognitoUser.confirmRegistration(code, true, (err, result) => {
if (err)
reject(err);
resolve(result);
});
});
}
getUser() {
return this.cognitoUser;
}
getSession() {
return this.session;
}
}
exports.AuthImpl = AuthImpl;
// For testing purposes
const PASSWORD_ALPHABET = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const PASSWORD_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const PASSWORD_SYMBOLS = ['!', '@', '#', '$', '%', '^', '&'];
function createPassword() {
const password = [];
for (let i = 0; i < 32; i++) {
password.push(utils.choose(PASSWORD_ALPHABET));
}
// Make sure we have at least one digit, one high cap, and one symbol
password.push(utils.choose(PASSWORD_DIGITS));
password.push(utils.choose(PASSWORD_SYMBOLS));
password.push(utils.choose(PASSWORD_ALPHABET).toUpperCase());
return password.join('');
}
exports.createPassword = createPassword;
function createTestUserProfile() {
const TEST_USERNAME_TEMPLATE = utils.getFromEnvOrThrow('TEST_USERNAME_TEMPLATE');
// Generate a unique id from a random number in hex format
const id = Math.floor(Math.random() * 1000000).toString(16);
const username = TEST_USERNAME_TEMPLATE.replace('${id}', id);
// Generate a password using random number generation
const password = createPassword();
const userProfile = {
username,
password
};
// logger.debug(`User profile generated: ${JSON.stringify(userProfile)}`)
return userProfile;
}
exports.createTestUserProfile = createTestUserProfile;