"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.Account = exports.CachedToken = exports.OAuthProvider = void 0;
var OAuthServer = require("oauth2-server");
var openflow_api_1 = require("@openiap/openflow-api");
var Config_1 = require("./Config");
var Crypt_1 = require("./Crypt");
var fs = require("fs");
var oidc_provider_1 = require("oidc-provider");
var MongoAdapter_1 = require("./MongoAdapter");
var DBHelper_1 = require("./DBHelper");
var Logger_1 = require("./Logger");
// import * as Provider from "oidc-provider";
var Request = OAuthServer.Request;
var Response = OAuthServer.Response;
var OAuthProvider = /** @class */ (function () {
    function OAuthProvider() {
        this.clients = [];
        this.codes = {};
        this.oauthServer = null;
        this.authorizationCodeStore = {};
    }
    OAuthProvider.interactionsUrl = function (ctx, interaction) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, "/oidclogin"];
            });
        });
    };
    OAuthProvider.logoutSource = function (ctx, form) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // @param ctx - koa request context
                // @param form - form source (id="op.logoutForm") to be embedded in the page and submitted by
                //   the End-User
                ctx.body = "<!DOCTYPE html>\n      <head>\n      <title>Logout Request</title>\n      <style>/* css and html classes omitted for brevity, see lib/helpers/defaults.js */</style>\n      </head>\n      <body onload=\"logout()\">\n      <div>\n        <h1>Do you want to sign-out from " + ctx.host + "?</h1>\n        <script>\n          function logout() {\n            var form = document.getElementById('op.logoutForm');\n            var input = document.createElement('input');\n            input.type = 'hidden';\n            input.name = 'logout';\n            input.value = 'yes';\n            form.appendChild(input);\n            form.submit();\n          }\n          function rpLogoutOnly() {\n            var form = document.getElementById('op.logoutForm');\n            form.submit();\n          }\n          \n        </script>\n        " + form + "\n        <button onclick=\"logout()\">Yes, sign me out</button>\n        <button onclick=\"rpLogoutOnly()\">No, stay signed in</button>\n      </div>\n      </body>\n      </html>";
                return [2 /*return*/];
            });
        });
    };
    OAuthProvider.generatekeys = function () {
        return new Promise(function (resolve, reject) {
            var jose = require('jose');
            var keystore = new jose.JWKS.KeyStore();
            Promise.all([
                keystore.generate('RSA', 2048, { use: 'sig' }),
                keystore.generate('RSA', 2048, { use: 'enc' }),
                keystore.generate('EC', 'P-256', { use: 'sig' }),
                keystore.generate('EC', 'P-256', { use: 'enc' }),
                keystore.generate('OKP', 'Ed25519', { use: 'sig' }),
            ]).then(function () {
                resolve(keystore.toJWKS(true));
            }).catch(function (err) {
                reject(err);
            });
        });
    };
    OAuthProvider.LoadClients = function () {
        return __awaiter(this, void 0, void 0, function () {
            var instance, span, jwksresults, jwks, result, provider, orig_1, orgpostLogoutRedirectUriAllowed_1, orgredirectUriAllowed_1, error_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        instance = OAuthProvider.instance;
                        span = Logger_1.Logger.otel.startSpan("OAuthProvider.LoadClients");
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 7, , 8]);
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "jwks" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 2:
                        jwksresults = _a.sent();
                        jwks = null;
                        if (!(jwksresults.length == 0)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.generatekeys()];
                    case 3:
                        jwks = _a.sent();
                        jwks._type = "jwks";
                        Config_1.Config.db.InsertOne(jwks, "config", 1, true, Crypt_1.Crypt.rootToken(), span);
                        return [3 /*break*/, 5];
                    case 4:
                        jwks = jwksresults[0];
                        _a.label = 5;
                    case 5: return [4 /*yield*/, Config_1.Config.db.query({ _type: "oauthclient" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 6:
                        result = _a.sent();
                        instance.clients = result;
                        instance.clients.forEach(function (cli) {
                            cli.client_id = cli.clientId;
                            cli.client_secret = cli.clientSecret;
                            cli.redirect_uris = cli.redirectUris;
                            // token_endpoint_auth_method can only be none, client_secret_post, client_secret_basic, private_key_jwt or tls_client_auth
                            if (openflow_api_1.NoderedUtil.IsNullEmpty(cli.token_endpoint_auth_method))
                                cli.token_endpoint_auth_method = "none";
                            // response_types can only contain 'code id_token', 'code', 'id_token', or 'none' 
                            // id_token token
                            if (openflow_api_1.NoderedUtil.IsNullEmpty(cli.response_types))
                                cli.response_types = ['code', 'id_token', 'code id_token'];
                            // https://github.com/panva/node-oidc-provider/blob/64edda69a84e556531f45ac814788c8c92ab6212/test/claim_types/claim_types.test.js
                            // cli.grant_types = cli.grants;
                            // if (cli.grant_types == null) cli.grant_types = ['authorization_code'];
                            if (cli.grant_types == null)
                                cli.grant_types = ['implicit', 'authorization_code'];
                            // cli.redirect_uris.push("https://localhost.openiap.io/")
                        });
                        provider = new oidc_provider_1.Provider(Config_1.Config.baseurl() + "oidc", {
                            clients: instance.clients,
                            adapter: MongoAdapter_1.MongoAdapter,
                            formats: {
                                AccessToken: 'jwt',
                            },
                            jwks: jwks,
                            features: {
                                encryption: { enabled: true },
                                introspection: { enabled: true },
                                revocation: { enabled: true },
                                devInteractions: { enabled: false },
                                clientCredentials: { enabled: true },
                                userinfo: { enabled: true },
                                jwtUserinfo: { enabled: true },
                                claimsParameter: { enabled: false },
                                rpInitiatedLogout: {
                                    enabled: true,
                                    logoutSource: this.logoutSource
                                }
                                // sessionManagement: { enabled: true },
                            },
                            claims: {
                                acr: null,
                                auth_time: null,
                                iss: null,
                                openid: [
                                    'sub', 'name', 'email', 'email_verified', 'role'
                                ],
                                sid: null
                            },
                            conformIdTokenClaims: false,
                            interactions: {
                                url: this.interactionsUrl
                            },
                            // logoutSource: this.logoutSource,
                            // findAccount: this.FindAccount,
                            // findAccount: this.findAccount,
                            findAccount: Account.findAccount,
                            // cookies: {
                            //     long: { signed: false, maxAge: 0, path: '/' },
                            //     keys: ["Y6SPiXCxDhAJbN7cbydMw5eX1wIrdy8PiWApqEcguss="], // node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
                            //     short: {
                            //         signed: false,
                            //         path: '/',
                            //     },
                            // },
                            cookies: {
                                short: {
                                    path: '/',
                                },
                                keys: [Config_1.Config.oidc_cookie_key], // node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
                            },
                        });
                        provider.proxy = true;
                        orig_1 = provider.Client.Schema.prototype.invalidate;
                        provider.Client.Schema.prototype.invalidate = function invalidate(message, code) {
                            if (code === 'implicit-force-https' || code === 'implicit-forbid-localhost') {
                                return;
                            }
                            if (message === 'redirect_uris must contain members') {
                                return;
                            }
                            orig_1.call(this, message);
                        };
                        orgpostLogoutRedirectUriAllowed_1 = provider.Client.prototype.postLogoutRedirectUriAllowed;
                        provider.Client.prototype.postLogoutRedirectUriAllowed = function (value) {
                            // const client = await provider.Client.find(this.clientId);
                            if (this.postLogoutRedirectUris == null || this.postLogoutRedirectUris.length == 0)
                                return true;
                            return orgpostLogoutRedirectUriAllowed_1(value);
                        };
                        orgredirectUriAllowed_1 = provider.Client.prototype.redirectUriAllowed;
                        provider.Client.prototype.redirectUriAllowed = function (value) {
                            // const client = await provider.Client.find(this.clientId);
                            if (this.redirectUris == null || this.redirectUris.length == 0)
                                return true;
                            return orgredirectUriAllowed_1(value);
                        };
                        if (instance.oidc != null) {
                            instance.oidc = provider;
                            return [2 /*return*/];
                        }
                        instance.oidc = provider;
                        instance.app.use('/oidc', function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
                            var _session, session, session1, session2, referer;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (req.originalUrl == "/oidc/me/emails") { // Grafana old school hack
                                            // if (req.user) {
                                            //     res.send('["' + (req.user as any).username + '"]');
                                            // } else {
                                            //     res.send('[]');
                                            // }
                                            res.send('[]');
                                            return [2 /*return*/];
                                        }
                                        if (!req.originalUrl.startsWith("/oidc/auth")) return [3 /*break*/, 7];
                                        _session = req.cookies["_session"];
                                        session = req.cookies["session"];
                                        return [4 /*yield*/, this.instance.oidc.Session.find(_session)];
                                    case 1:
                                        session1 = _a.sent();
                                        return [4 /*yield*/, this.instance.oidc.Session.find(session)];
                                    case 2:
                                        session2 = _a.sent();
                                        if (!(session1 != null)) return [3 /*break*/, 6];
                                        referer = req.headers.referer;
                                        if (!openflow_api_1.NoderedUtil.IsNullEmpty(referer)) return [3 /*break*/, 3];
                                        res.redirect("/oidc/session/end");
                                        return [3 /*break*/, 5];
                                    case 3: return [4 /*yield*/, session1.destroy()];
                                    case 4:
                                        _a.sent();
                                        res.redirect(referer);
                                        _a.label = 5;
                                    case 5: return [2 /*return*/];
                                    case 6:
                                        if (session2 != null) {
                                            session2.resetIdentifier();
                                            session2.destroy();
                                        }
                                        req.logout();
                                        _a.label = 7;
                                    case 7:
                                        instance.oidc.callback(req, res);
                                        return [2 /*return*/];
                                }
                            });
                        }); });
                        instance.app.use('/oidclogin', function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                if (req && req.user) {
                                    // const _session = req.cookies["_session"];
                                    // var session1 = await this.instance.oidc.Session.find(_session)
                                    // if (session1 != null) {
                                    // }
                                    res.cookie("originalUrl", "/oidccb", { maxAge: 900000, httpOnly: true });
                                    res.redirect("/oidccb");
                                }
                                else {
                                    res.cookie("originalUrl", "/oidclogin", { maxAge: 900000, httpOnly: true });
                                    res.redirect("/login");
                                }
                                return [2 /*return*/];
                            });
                        }); });
                        instance.app.use('/oidccb', function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
                            var test, _a, uid, prompt_1, params_1, session, r, u, isAuthenticated, client, tuser, error_2;
                            var _b;
                            return __generator(this, function (_c) {
                                switch (_c.label) {
                                    case 0:
                                        _c.trys.push([0, 6, , 7]);
                                        return [4 /*yield*/, this.instance.oidc.interactionDetails(req, res)];
                                    case 1:
                                        test = _c.sent();
                                        return [4 /*yield*/, this.instance.oidc.interactionDetails(req, res)];
                                    case 2:
                                        _a = _c.sent(), uid = _a.uid, prompt_1 = _a.prompt, params_1 = _a.params, session = _a.session;
                                        r = req;
                                        u = req.user;
                                        isAuthenticated = req.isAuthenticated();
                                        if (isAuthenticated) {
                                            // if(!NoderedUtil.IsNullEmpty(test.returnTo) ) {
                                            //     res.redirect(test.returnTo);
                                            //     return;                            
                                            // }
                                        }
                                        else {
                                            res.cookie("originalUrl", "/oidccb", { maxAge: 900000, httpOnly: true });
                                            res.redirect('/login');
                                            return [2 /*return*/];
                                        }
                                        if (!req.user) return [3 /*break*/, 5];
                                        return [4 /*yield*/, this.instance.clients.filter(function (x) { return x.clientId == params_1.client_id; })[0]];
                                    case 3:
                                        client = _c.sent();
                                        tuser = openflow_api_1.TokenUser.From(req.user);
                                        Account.AddAccount(tuser, client);
                                        return [4 /*yield*/, this.instance.oidc.interactionFinished(req, res, (_b = {
                                                    // authentication/login prompt got resolved, omit if no authentication happened, i.e. the user
                                                    // cancelled
                                                    login: {
                                                        account: tuser._id,
                                                        acr: "acr",
                                                        remember: false, // true if provider should use a persistent cookie rather than a session one, defaults to true
                                                        // ts: number, // unix timestamp of the authentication, defaults to now()
                                                    },
                                                    // consent was given by the user to the client for this session
                                                    consent: {
                                                        rejectedScopes: [],
                                                        rejectedClaims: [], // array of strings, claim names the end-user has not granted
                                                    },
                                                    // meta is a free object you may store alongside an authorization. It can be useful
                                                    // during the interaction check to verify information on the ongoing session.
                                                    meta: {
                                                        // object structure up-to-you
                                                        "openflow": "true"
                                                    }
                                                },
                                                _b['custom prompt name resolved'] = {},
                                                _b))];
                                    case 4:
                                        _c.sent();
                                        _c.label = 5;
                                    case 5: return [3 /*break*/, 7];
                                    case 6:
                                        error_2 = _c.sent();
                                        span.recordException(error_2);
                                        if (error_2.name == "SessionNotFound") {
                                            res.redirect("/");
                                            res.end();
                                            return [2 /*return*/];
                                        }
                                        res.json(error_2);
                                        return [3 /*break*/, 7];
                                    case 7: return [2 /*return*/];
                                }
                            });
                        }); });
                        return [3 /*break*/, 8];
                    case 7:
                        error_1 = _a.sent();
                        span.recordException(error_1);
                        Logger_1.Logger.instanse.error(error_1);
                        return [3 /*break*/, 8];
                    case 8:
                        Logger_1.Logger.otel.endSpan(span);
                        return [2 /*return*/];
                }
            });
        });
    };
    OAuthProvider.configure = function (app) {
        var _this = this;
        var instance = new OAuthProvider();
        try {
            OAuthProvider.instance = instance;
            instance.app = app;
            instance.oauthServer = new OAuthServer({
                model: instance,
                grants: ['authorization_code', 'refresh_token'],
                accessTokenLifetime: (60 * 60 * 24) * 7,
                refreshTokenLifetime: (60 * 60 * 24) * 7,
                allowEmptyState: true,
                allowExtendedTokenAttributes: true,
                allowBearerTokensInQueryString: true
            });
            this.LoadClients();
            app.oauth = instance.oauthServer;
            app.all('/oauth/token', instance.obtainToken.bind(instance));
            app.get('/oauth/login', function (req, res) { return __awaiter(_this, void 0, void 0, function () {
                var span, _a, state, access_type, client_id, redirect_uri, response_type, scope, client, _b, code, error_3;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            span = Logger_1.Logger.otel.startSpan("OAuthProvider.oauth.login");
                            _c.label = 1;
                        case 1:
                            _c.trys.push([1, 6, 7, 8]);
                            if (!openflow_api_1.NoderedUtil.IsNullUndefinded(instance.clients)) return [3 /*break*/, 3];
                            _a = instance;
                            return [4 /*yield*/, Config_1.Config.db.query({ _type: "oauthclient" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                        case 2:
                            _a.clients = _c.sent();
                            if (instance.clients == null || instance.clients.length == 0)
                                return [2 /*return*/, res.status(500).json({ message: 'OAuth not configured' })];
                            _c.label = 3;
                        case 3:
                            state = (req.params.state ? req.params.state : req.params["amp;state"]);
                            if (state == null)
                                state = encodeURIComponent((req.query.state ? req.query.state : req.query["amp;state"]));
                            access_type = (req.query.access_type ? req.query.access_type : req.query["amp;access_type"]);
                            client_id = (req.query.client_id ? req.query.client_id : req.query["amp;client_id"]);
                            redirect_uri = (req.query.redirect_uri ? req.query.redirect_uri : req.query["amp;redirect_uri"]);
                            response_type = (req.query.response_type ? req.query.response_type : req.query["amp;response_type"]);
                            scope = (req.query.scope ? req.query.scope : req.query["amp;scope"]);
                            client = instance.getClientById(client_id);
                            if (!openflow_api_1.NoderedUtil.IsNullUndefinded(client)) return [3 /*break*/, 5];
                            _b = instance;
                            return [4 /*yield*/, Config_1.Config.db.query({ _type: "oauthclient" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                        case 4:
                            _b.clients = _c.sent();
                            if (instance.clients == null || instance.clients.length == 0)
                                return [2 /*return*/, res.status(500).json({ message: 'OAuth not configured' })];
                            _c.label = 5;
                        case 5:
                            if (req.user) {
                                if (!openflow_api_1.NoderedUtil.IsNullUndefinded(client) && !Array.isArray(client.redirectUris)) {
                                    client.redirectUris = [];
                                }
                                if (!openflow_api_1.NoderedUtil.IsNullUndefinded(client) && client.redirectUris.length > 0) {
                                    if (client.redirectUris.indexOf(redirect_uri) == -1) {
                                        return [2 /*return*/, res.status(500).json({ message: 'illegal redirect_uri ' + redirect_uri })];
                                        // client.redirectUris.push(redirect_uri);
                                    }
                                }
                                code = openflow_api_1.NoderedUtil.GetUniqueIdentifier();
                                Logger_1.Logger.instanse.info("[OAuth][" + req.user.username + "] /oauth/login " + state);
                                instance.saveAuthorizationCode(code, client, req.user, redirect_uri);
                                res.redirect(redirect_uri + "?state=" + state + "&code=" + code);
                            }
                            else {
                                Logger_1.Logger.instanse.info("[OAuth][anon] /oauth/login " + state);
                                res.cookie("originalUrl", req.originalUrl, { maxAge: 900000, httpOnly: true });
                                res.redirect("/login");
                            }
                            return [3 /*break*/, 8];
                        case 6:
                            error_3 = _c.sent();
                            span.recordException(error_3);
                            throw error_3;
                        case 7:
                            Logger_1.Logger.otel.endSpan(span);
                            return [7 /*endfinally*/];
                        case 8: return [2 /*return*/];
                    }
                });
            }); });
            // app.get('/oauth/authorize', instance.authorize.bind(instance));
            app.all('/oauth/authorize', function (req, res) {
                var request = new Request(req);
                var response = new Response(res);
                return instance.oauthServer.authenticate(request, response)
                    .then(function (token) {
                    res.json(token.user);
                }).catch(function (err) {
                    console.error(err);
                    res.status(err.code || 500).json(err);
                });
            });
            // app.all('/oauth/authorize', instance.oauthServer.authenticate.bind(instance));
            // app.all('/oauth/authorize/emails', instance.oauthServer.authenticate.bind(instance));
        }
        catch (error) {
            console.error(error);
            var json = JSON.stringify(error, null, 3);
            console.error(json);
            throw error;
        }
        return instance;
    };
    OAuthProvider.prototype.authorize = function (req, res) {
        Logger_1.Logger.instanse.info("[OAuth] authorize");
        var request = new Request(req);
        var response = new Response(res);
        return this.oauthServer.authorize(request, response)
            .then(function (token) {
            res.json(token);
        }).catch(function (err) {
            console.error(err);
            res.status(err.code || 500).json(err);
        });
    };
    OAuthProvider.prototype.authenticateHandler = function () {
        return {
            handle: function (request, response) {
                //in this example, we store the logged-in user as the 'loginUser' attribute in session
                if (request.session.loginUser) {
                    return { username: request.session.loginUser.username };
                }
                return null;
            }
        };
    };
    OAuthProvider.prototype.obtainToken = function (req, res) {
        Logger_1.Logger.instanse.info("[OAuth] obtainToken");
        var request = new Request(req);
        var response = new Response(res);
        return this.oauthServer.token(request, response)
            .then(function (token) {
            Logger_1.Logger.instanse.info("[OAuth] obtainToken::success: token:");
            res.json(token);
        }).catch(function (err) {
            Logger_1.Logger.instanse.info("[OAuth] obtainToken::failed: token:");
            console.error(err);
            res.status(err.code || 500).json(err);
        });
    };
    OAuthProvider.prototype.getAccessToken = function (accessToken) {
        return __awaiter(this, void 0, void 0, function () {
            var span, token, tokens, error_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSpan("OAuthProvider.getAccessToken");
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, 6, 7]);
                        Logger_1.Logger.instanse.info("[OAuth] getAccessToken " + accessToken);
                        return [4 /*yield*/, OAuthProvider.getCachedAccessToken(accessToken)];
                    case 2:
                        token = _a.sent();
                        if (token != null)
                            return [2 /*return*/, token];
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "token", "accessToken": accessToken }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 3:
                        tokens = _a.sent();
                        token = tokens.length ? tokens[0] : null;
                        return [4 /*yield*/, OAuthProvider.addToken(token)];
                    case 4:
                        _a.sent();
                        if (token == null)
                            return [2 /*return*/, false];
                        return [2 /*return*/, token];
                    case 5:
                        error_4 = _a.sent();
                        span.recordException(error_4);
                        throw error_4;
                    case 6:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    OAuthProvider.prototype.getRefreshToken = function (refreshToken) {
        return __awaiter(this, void 0, void 0, function () {
            var span, token, tokens, error_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSpan("OAuthProvider.getRefreshToken");
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, 6, 7]);
                        Logger_1.Logger.instanse.info("[OAuth] getRefreshToken " + refreshToken);
                        return [4 /*yield*/, OAuthProvider.getCachedAccessToken(refreshToken)];
                    case 2:
                        token = _a.sent();
                        if (token != null)
                            return [2 /*return*/, token];
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "token", "refreshToken": refreshToken }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 3:
                        tokens = _a.sent();
                        token = tokens.length ? tokens[0] : null;
                        return [4 /*yield*/, OAuthProvider.addToken(token)];
                    case 4:
                        _a.sent();
                        if (token == null)
                            return [2 /*return*/, false];
                        return [2 /*return*/, token];
                    case 5:
                        error_5 = _a.sent();
                        span.recordException(error_5);
                        throw error_5;
                    case 6:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    OAuthProvider.prototype.getClient = function (clientId, clientSecret) {
        Logger_1.Logger.instanse.info("[OAuth] getClient " + clientId);
        var clients = this.clients.filter(function (client) {
            return client.clientId === clientId && client.clientSecret === clientSecret;
        });
        return clients.length ? clients[0] : false;
    };
    OAuthProvider.prototype.getClientById = function (clientId) {
        Logger_1.Logger.instanse.info("[OAuth] getClientById " + clientId);
        var clients = this.clients.filter(function (client) {
            return client.clientId === clientId;
        });
        return clients.length ? clients[0] : null;
    };
    OAuthProvider.prototype.saveToken = function (token, client, user) {
        return __awaiter(this, void 0, void 0, function () {
            var span, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSpan("OAuthProvider.saveToken");
                        Logger_1.Logger.instanse.info("[OAuth] saveToken for " + user.name + " in " + client.clientId);
                        result = {
                            name: "Token for " + user.name,
                            accessToken: token.accessToken,
                            access_token: token.accessToken,
                            accessTokenExpiresAt: token.accessTokenExpiresAt,
                            clientId: client.clientId,
                            refreshToken: token.refreshToken,
                            refresh_token: token.refreshToken,
                            refreshTokenExpiresAt: token.refreshTokenExpiresAt,
                            userId: user.id,
                            user: user,
                            client: client,
                            _type: "token"
                        };
                        return [4 /*yield*/, OAuthProvider.addToken(result)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, Config_1.Config.db.InsertOne(result, "oauthtokens", 0, false, Crypt_1.Crypt.rootToken(), span)];
                    case 2:
                        _a.sent();
                        Logger_1.Logger.otel.endSpan(span);
                        return [2 /*return*/, result];
                }
            });
        });
    };
    OAuthProvider.prototype.saveAuthorizationCode = function (code, client, user, redirect_uri) {
        return __awaiter(this, void 0, void 0, function () {
            var span, codeobject;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSpan("OAuthProvider.saveAuthorizationCode");
                        Logger_1.Logger.instanse.info("[OAuth] saveAuthorizationCode " + code);
                        codeobject = Object.assign({}, user);
                        delete codeobject._id;
                        codeobject._type = 'code';
                        codeobject.code = code;
                        codeobject.id = user._id;
                        codeobject.username = user.username;
                        codeobject.email = user.email;
                        if (openflow_api_1.NoderedUtil.IsNullEmpty(codeobject.email))
                            codeobject.email = user.username;
                        codeobject.fullname = user.name;
                        codeobject.redirect_uri = redirect_uri;
                        codeobject.client_id = client.clientId;
                        codeobject.name = "Code " + code + " for " + user.name;
                        this.codes[code] = codeobject;
                        return [4 /*yield*/, Config_1.Config.db.InsertOne(codeobject, "oauthtokens", 1, false, Crypt_1.Crypt.rootToken(), span)];
                    case 1:
                        _a.sent();
                        Logger_1.Logger.instanse.info("[OAuth] saveAuthorizationCode " + code + " saved");
                        // instance.codes[code].client_id = client_id;
                        // await Config.db.InsertOne(result, "oauthtokens", 0, false, Crypt.rootToken());
                        // // const codeToSave: any = this.codes[code];
                        // const codeToSave: any = {
                        //     'authorizationCode': code.authorizationCode,
                        //     'expiresAt': code.expiresAt,
                        //     'redirectUri': code.redirectUri,
                        //     'scope': code.scope,
                        //     'client': client.id,
                        //     'user': user.username
                        // };
                        // this.codes[code] = codeToSave;
                        // this.revokeAuthorizationCode(code);
                        // code = Object.assign({}, code, {
                        //     'client': client.id,
                        //     'user': user.username
                        // });
                        Logger_1.Logger.otel.endSpan(span);
                        return [2 /*return*/, codeobject];
                }
            });
        });
    };
    OAuthProvider.prototype.sleep = function (ms) {
        return new Promise(function (resolve) {
            setTimeout(resolve, ms);
        });
    };
    OAuthProvider.prototype.getAuthorizationCode = function (code) {
        return __awaiter(this, void 0, void 0, function () {
            var span, user, users, client_id, redirect_uri, expiresAt, tuser, client, role, keys, i, result, error_6;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSpan("OAuthProvider.validateToken");
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 10, 11, 12]);
                        Logger_1.Logger.instanse.info("[OAuth] getAuthorizationCode " + code);
                        user = this.codes[code];
                        if (!(user == null)) return [3 /*break*/, 9];
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "code", "code": code }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 2:
                        users = _a.sent();
                        user = users.length ? users[0] : null;
                        if (!(user == null)) return [3 /*break*/, 5];
                        return [4 /*yield*/, this.sleep(1000)];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "code", "code": code }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 4:
                        users = _a.sent();
                        user = users.length ? users[0] : null;
                        _a.label = 5;
                    case 5:
                        if (!(user == null)) return [3 /*break*/, 8];
                        return [4 /*yield*/, this.sleep(1000)];
                    case 6:
                        _a.sent();
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "code", "code": code }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken(), undefined, undefined, span)];
                    case 7:
                        users = _a.sent();
                        user = users.length ? users[0] : null;
                        _a.label = 8;
                    case 8:
                        if (user == null) {
                            Logger_1.Logger.instanse.error("[OAuth] getAuthorizationCode, unkown code '" + code + "'");
                            return [2 /*return*/, null];
                        }
                        if (user != null) {
                            this.codes[code] = user;
                        }
                        _a.label = 9;
                    case 9:
                        client_id = this.codes[code].client_id;
                        if (user == null)
                            return [2 /*return*/, null];
                        this.revokeAuthorizationCode(code);
                        redirect_uri = user.redirect_uri;
                        expiresAt = new Date((new Date).getTime() + (1000 * Config_1.Config.oauth_access_token_lifetime));
                        tuser = openflow_api_1.TokenUser.From(user);
                        client = this.getClientById(client_id);
                        if (openflow_api_1.NoderedUtil.IsNullUndefinded(client))
                            return [2 /*return*/, null];
                        role = client.defaultrole;
                        keys = Object.keys(client.rolemappings);
                        for (i = 0; i < keys.length; i++) {
                            if (tuser.HasRoleName(keys[i]))
                                role = client.rolemappings[keys[i]];
                        }
                        result = {
                            code: code,
                            client: this.clients[0],
                            user: {
                                id: user.id,
                                _id: user.id,
                                name: user.fullname,
                                username: user.username,
                                email: user.username,
                                role: role
                            },
                            expiresAt: expiresAt,
                            redirectUri: redirect_uri
                        };
                        // node-bb username hack
                        if (result.user.name == result.user.email && result.user.email.indexOf("@") > -1) {
                            result.user.name = result.user.email.substr(0, result.user.email.indexOf("@") - 1);
                        }
                        if (result.user.name == result.user.email && result.user.email.indexOf("@") == -1) {
                            result.user.email = result.user.email + "@unknown.local";
                        }
                        if (result.user.name == result.user.email) {
                            result.user.name = "user " + result.user.email;
                        }
                        return [2 /*return*/, result];
                    case 10:
                        error_6 = _a.sent();
                        span.recordException(error_6);
                        throw error_6;
                    case 11:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 12: return [2 /*return*/];
                }
            });
        });
    };
    OAuthProvider.prototype.revokeAuthorizationCode = function (code) {
        return __awaiter(this, void 0, void 0, function () {
            var refreshTokenExpiresAt, accessTokenExpiresAt, codeExpiresAt;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (typeof code !== "string") {
                            code = code.code;
                        }
                        Logger_1.Logger.instanse.info("[OAuth] revokeAuthorizationCode " + code);
                        delete this.codes[code];
                        refreshTokenExpiresAt = new Date((new Date).getTime() - (1000 * Config_1.Config.oauth_refresh_token_lifetime)).toISOString();
                        accessTokenExpiresAt = new Date((new Date).getTime() - (1000 * Config_1.Config.oauth_access_token_lifetime)).toISOString();
                        codeExpiresAt = new Date((new Date).getTime() - (1000 * 120)).toISOString();
                        return [4 /*yield*/, Config_1.Config.db.DeleteMany({
                                "$or": [
                                    { "_type": "code", "_created": { "$lte": codeExpiresAt } },
                                    { "_type": "token", "refreshTokenExpiresAt": { "$lte": refreshTokenExpiresAt } },
                                    { "_type": "token", "accessTokenExpiresAt": { "$lte": accessTokenExpiresAt } }
                                ]
                            }, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 1:
                        _a.sent();
                        // await Config.db.DeleteMany({ "_type": "code", "code": code }, null, "oauthtokens", Crypt.rootToken());
                        return [4 /*yield*/, Config_1.Config.db.DeleteMany({ "_type": "code", "_created": { "$lte": codeExpiresAt } }, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 2:
                        // await Config.db.DeleteMany({ "_type": "code", "code": code }, null, "oauthtokens", Crypt.rootToken());
                        _a.sent();
                        return [2 /*return*/, true];
                }
            });
        });
    };
    OAuthProvider.getCachedAccessToken = function (accessToken) {
        return __awaiter(this, void 0, void 0, function () {
            var i, res, begin, end, seconds;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        for (i = this.tokenCache.length - 1; i >= 0; i--) {
                            res = this.tokenCache[i];
                            begin = res.firstsignin.getTime();
                            end = new Date().getTime();
                            seconds = Math.round((end - begin) / 1000);
                            if (seconds > Config_1.Config.oauth_token_cache_seconds) {
                                this.tokenCache.splice(i, 1);
                            }
                            else if (res.token.accessToken == accessToken) {
                                semaphore.up();
                                return [2 /*return*/, res.token];
                            }
                        }
                        semaphore.up();
                        return [2 /*return*/, null];
                }
            });
        });
    };
    OAuthProvider.getCachedRefreshToken = function (refreshToken) {
        return __awaiter(this, void 0, void 0, function () {
            var i, res, begin, end, seconds;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        for (i = this.tokenCache.length - 1; i >= 0; i--) {
                            res = this.tokenCache[i];
                            begin = res.firstsignin.getTime();
                            end = new Date().getTime();
                            seconds = Math.round((end - begin) / 1000);
                            if (seconds > Config_1.Config.oauth_token_cache_seconds) {
                                this.tokenCache.splice(i, 1);
                            }
                            else if (res.token.refreshToken == refreshToken) {
                                semaphore.up();
                                return [2 /*return*/, res.token];
                            }
                        }
                        semaphore.up();
                        return [2 /*return*/, null];
                }
            });
        });
    };
    OAuthProvider.addToken = function (token) {
        return __awaiter(this, void 0, void 0, function () {
            var cuser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        cuser = new CachedToken(token);
                        this.tokenCache.push(cuser);
                        semaphore.up();
                        return [2 /*return*/];
                }
            });
        });
    };
    OAuthProvider.instance = null;
    OAuthProvider.store = new Map();
    OAuthProvider.tokenCache = [];
    return OAuthProvider;
}());
exports.OAuthProvider = OAuthProvider;
var CachedToken = /** @class */ (function () {
    function CachedToken(token) {
        this.token = token;
        this.firstsignin = new Date();
    }
    return CachedToken;
}());
exports.CachedToken = CachedToken;
var Semaphore = function (n) { return ({
    n: n,
    down: function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.n <= 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.wait()];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 0];
                    case 2:
                        this.n--;
                        return [2 /*return*/];
                }
            });
        });
    },
    up: function () {
        this.n++;
    },
    wait: function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.n <= 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, new Promise(function (res, req) {
                                setImmediate(function () { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) {
                                    switch (_b.label) {
                                        case 0:
                                            _a = res;
                                            return [4 /*yield*/, this.wait()];
                                        case 1: return [2 /*return*/, _a.apply(void 0, [_b.sent()])];
                                    }
                                }); }); });
                            })];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2: return [2 /*return*/];
                }
            });
        });
    },
}); };
var semaphore = Semaphore(1);
var accountStorage = new Map();
var Account = /** @class */ (function () {
    function Account(accountId, user) {
        this.accountId = accountId;
        this.user = user;
        accountStorage.set("Account:" + this.accountId, this);
        if (user == null)
            throw new Error("Cannot create Account from null user for id ${this.accountId}");
        user = Object.assign(user, { accountId: accountId, sub: accountId });
        // var roles = [];
        // user.roles.forEach(role => {
        //     roles.push(role.name);
        // });
        // user.roles = roles;
        // node-bb username hack
        if (openflow_api_1.NoderedUtil.IsNullEmpty(user.email))
            user.email = user.username;
        if (user.name == user.email && user.email.indexOf("@") > -1) {
            user.name = user.email.substr(0, user.email.indexOf("@") - 1);
        }
        if (user.name == user.email && user.email.indexOf("@") == -1) {
            user.email = user.email + "@unknown.local";
        }
        if (user.name == user.email) {
            user.name = "user " + user.email;
        }
    }
    Object.defineProperty(Account, "storage", {
        get: function () {
            return accountStorage;
        },
        enumerable: false,
        configurable: true
    });
    Account.prototype.claims = function () {
        return this.user;
    };
    Account.findAccount = function (ctx, id) {
        return __awaiter(this, void 0, void 0, function () {
            var acc, user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        acc = accountStorage.get("Account:" + id);
                        if (!!acc) return [3 /*break*/, 2];
                        return [4 /*yield*/, DBHelper_1.DBHelper.FindById(id, undefined, undefined)];
                    case 1:
                        user = _a.sent();
                        acc = new Account(id, openflow_api_1.TokenUser.From(user));
                        _a.label = 2;
                    case 2: return [2 /*return*/, acc];
                }
            });
        });
    };
    Account.AddAccount = function (tuser, client) {
        try {
            var acc = accountStorage.get("Account:" + tuser._id);
            if (!acc) {
                var role = client.defaultrole;
                var keys = Object.keys(client.rolemappings);
                for (var i = 0; i < keys.length; i++) {
                    if (tuser.HasRoleName(keys[i]))
                        role = client.rolemappings[keys[i]];
                }
                tuser.role = role;
                acc = new Account(tuser._id, tuser);
            }
            return acc;
        }
        catch (error) {
            console.error(error);
        }
        return undefined;
    };
    return Account;
}());
exports.Account = Account;
//# sourceMappingURL=OAuthProvider.js.map