"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Crypt = void 0;
var crypto = require("crypto");
var bcrypt = require("bcryptjs");
var jsonwebtoken = require("jsonwebtoken");
var Config_1 = require("./Config");
var openflow_api_1 = require("@openiap/openflow-api");
var handlebars_1 = require("handlebars");
var Logger_1 = require("./Logger");
var Crypt = /** @class */ (function () {
    function Crypt() {
    }
    Crypt.rootUser = function () {
        var result = new openflow_api_1.User();
        result._type = "user";
        result.name = "root";
        result.username = "root";
        result._id = openflow_api_1.WellknownIds.root;
        result.roles = [];
        result.roles.push(new openflow_api_1.Rolemember("admins", openflow_api_1.WellknownIds.admins));
        return result;
    };
    Crypt.rootToken = function () {
        return Crypt.createToken(this.rootUser(), Config_1.Config.shorttoken_expires_in);
    };
    Crypt.SetPassword = function (user, password, parent) {
        return __awaiter(this, void 0, void 0, function () {
            var span, _a, error_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSubSpan("Crypt.SetPassword", parent);
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 3, 4, 5]);
                        _a = user;
                        return [4 /*yield*/, Crypt.hash(password)];
                    case 2:
                        _a.passwordhash = _b.sent();
                        if (!(this.ValidatePassword(user, password, span))) {
                            throw new Error("Failed validating password after hasing");
                        }
                        return [3 /*break*/, 5];
                    case 3:
                        error_1 = _b.sent();
                        span.recordException(error_1);
                        throw error_1;
                    case 4:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    Crypt.ValidatePassword = function (user, password, parent) {
        return __awaiter(this, void 0, void 0, function () {
            var span, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSubSpan("Crypt.ValidatePassword", parent);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, 4, 5]);
                        return [4 /*yield*/, Crypt.compare(password, user.passwordhash, span)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        error_2 = _a.sent();
                        span.recordException(error_2);
                        throw error_2;
                    case 4:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    Crypt.encrypt = function (text) {
        var iv = crypto.randomBytes(Crypt.iv_length);
        var cipher = crypto.createCipheriv("aes-256-cbc", Buffer.from(Crypt.encryption_key), iv);
        var encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return iv.toString("hex") + ":" + encrypted.toString("hex");
    };
    Crypt.decrypt = function (text) {
        var textParts = text.split(":");
        var iv = Buffer.from(textParts.shift(), "hex");
        var encryptedText = Buffer.from(textParts.join(":"), "hex");
        var decipher = crypto.createDecipheriv("aes-256-cbc", Buffer.from(Crypt.encryption_key), iv);
        var decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()]);
        return decrypted.toString();
    };
    Crypt.hash = function (password) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                        var _this = this;
                        return __generator(this, function (_a) {
                            try {
                                bcrypt.hash(password, Crypt.bcrypt_salt_rounds, function (error, hash) { return __awaiter(_this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        if (error) {
                                            return [2 /*return*/, reject(error)];
                                        }
                                        resolve(hash);
                                        return [2 /*return*/];
                                    });
                                }); });
                            }
                            catch (error) {
                                reject(error);
                            }
                            return [2 /*return*/];
                        });
                    }); })];
            });
        });
    };
    Crypt.compare = function (password, passwordhash, parent) {
        return __awaiter(this, void 0, void 0, function () {
            var span;
            var _this = this;
            return __generator(this, function (_a) {
                span = Logger_1.Logger.otel.startSubSpan("Crypt.compare", parent);
                return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                        var _this = this;
                        return __generator(this, function (_a) {
                            try {
                                if (openflow_api_1.NoderedUtil.IsNullEmpty(password)) {
                                    span.recordException("Password cannot be empty");
                                    return [2 /*return*/, reject("Password cannot be empty")];
                                }
                                if (openflow_api_1.NoderedUtil.IsNullEmpty(passwordhash)) {
                                    span.recordException("Passwordhash cannot be empty");
                                    return [2 /*return*/, reject("Passwordhash cannot be empty")];
                                }
                                bcrypt.compare(password, passwordhash, function (error, res) { return __awaiter(_this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        if (error) {
                                            span.recordException(error);
                                            Logger_1.Logger.otel.endSpan(span);
                                            return [2 /*return*/, reject(error)];
                                        }
                                        Logger_1.Logger.otel.endSpan(span);
                                        resolve(res);
                                        return [2 /*return*/];
                                    });
                                }); });
                            }
                            catch (error) {
                                span.recordException(error);
                                reject(error);
                                Logger_1.Logger.otel.endSpan(span);
                            }
                            return [2 /*return*/];
                        });
                    }); })];
            });
        });
    };
    Crypt.createToken = function (item, expiresIn) {
        var user = new openflow_api_1.TokenUser();
        user._type = item._type;
        user._id = item._id;
        user.impostor = item.impostor;
        user.name = item.name;
        user.username = item.username;
        user.roles = item.roles;
        var key = Crypt.encryption_key;
        if (openflow_api_1.NoderedUtil.IsNullEmpty(Config_1.Config.aes_secret))
            throw new handlebars_1.Exception("Config missing aes_secret");
        if (openflow_api_1.NoderedUtil.IsNullEmpty(key))
            throw new handlebars_1.Exception("Config missing aes_secret");
        var token = jsonwebtoken.sign({ data: user }, key, { expiresIn: expiresIn }); // 60 (seconds), "2 days", "10h", "7d"
        return token;
    };
    Crypt.verityToken = function (token) {
        if (openflow_api_1.NoderedUtil.IsNullEmpty(token)) {
            throw new Error('jwt must be provided');
        }
        var o = jsonwebtoken.verify(token, Crypt.encryption_key);
        o.data = openflow_api_1.TokenUser.assign(o.data);
        return o.data;
    };
    Crypt.decryptToken = function (token) {
        var o = jsonwebtoken.verify(token, Crypt.encryption_key);
        return o;
    };
    Crypt.encryption_key = Config_1.Config.aes_secret.substr(0, 32); // must be 256 bytes (32 characters)
    Crypt.iv_length = 16; // for AES, this is always 16
    Crypt.bcrypt_salt_rounds = 12;
    return Crypt;
}());
exports.Crypt = Crypt;
//# sourceMappingURL=Crypt.js.map