"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 };
    }
};
var __values = (this && this.__values) || function (o) {
    var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
    if (m) return m.call(o);
    return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var crypto = require("crypto");
var electron_1 = require("electron");
var minimist = require("minimist");
var path = require("path");
var url_1 = require("url");
var config_1 = require("../js/config");
var argv = minimist(process.argv.slice(1));
var SingleSignOn = (function () {
    function SingleSignOn(mainBrowserWindow, senderEvent, windowOriginUrl, windowOptions) {
        var _this = this;
        this.mainBrowserWindow = mainBrowserWindow;
        this.senderEvent = senderEvent;
        this.windowOptions = windowOptions;
        this.init = function () { return __awaiter(_this, void 0, void 0, function () {
            var SingleSignOnLoginWindow;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.session = electron_1.session.fromPartition(SingleSignOn.SSO_SESSION_NAME, { cache: false });
                        this.session.setPermissionRequestHandler(function (webContents, permission, callback) { return callback(false); });
                        this.session.webRequest.onBeforeSendHeaders({
                            urls: ['*'],
                        }, function (details, callback) {
                            details.requestHeaders['User-Agent'] = config_1.USER_AGENT;
                            callback({ cancel: false, requestHeaders: details.requestHeaders });
                        });
                        SingleSignOnLoginWindow = this.createBrowserWindow();
                        return [4, SingleSignOn.protocol.register(this.session, function (type) { return _this.finalizeLogin(type); })];
                    case 1:
                        _a.sent();
                        SingleSignOnLoginWindow.loadURL(this.windowOriginUrl.toString());
                        if (argv.devtools) {
                            SingleSignOnLoginWindow.webContents.openDevTools({ mode: 'detach' });
                        }
                        return [2];
                }
            });
        }); };
        this.createBrowserWindow = function () {
            delete _this.windowOptions.webPreferences.preloadURL;
            var SingleSignOnLoginWindow = new electron_1.BrowserWindow(__assign({}, _this.windowOptions, { alwaysOnTop: true, backgroundColor: '#FFFFFF', fullscreen: false, fullscreenable: false, height: _this.windowOptions.height || 600, maximizable: false, minimizable: false, modal: false, movable: false, parent: _this.mainBrowserWindow, resizable: false, title: SingleSignOn.getWindowTitle(_this.windowOriginUrl.origin), titleBarStyle: 'default', useContentSize: true, webPreferences: __assign({}, _this.windowOptions.webPreferences, { allowRunningInsecureContent: false, backgroundThrottling: false, contextIsolation: true, devTools: true, disableBlinkFeatures: '', enableBlinkFeatures: '', experimentalFeatures: false, images: true, javascript: true, nativeWindowOpen: false, nodeIntegration: false, nodeIntegrationInWorker: false, offscreen: false, partition: '', plugins: false, preload: SingleSignOn.PRELOAD_SSO_JS, sandbox: true, scrollBounce: true, session: _this.session, textAreasAreResizable: false, webSecurity: true, webgl: false, webviewTag: false }), width: _this.windowOptions.width || 480 }));
            _this.senderEvent.newGuest = SingleSignOnLoginWindow;
            SingleSignOnLoginWindow.once('closed', function () { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!this.session) return [3, 3];
                            return [4, this.wipeSessionData()];
                        case 1:
                            _a.sent();
                            return [4, SingleSignOn.protocol.unregister(this.session)];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3:
                            this.session = undefined;
                            return [2];
                    }
                });
            }); });
            SingleSignOnLoginWindow.on('page-title-updated', function (event) { return event.preventDefault(); });
            SingleSignOnLoginWindow.webContents.on('new-window', function (event) { return event.preventDefault(); });
            SingleSignOnLoginWindow.webContents.on('did-navigate', function (event, url) {
                var origin = new url_1.URL(url).origin;
                if (origin.length > SingleSignOn.MAX_LENGTH_ORIGIN) {
                    event.preventDefault();
                }
                SingleSignOnLoginWindow.setTitle(SingleSignOn.getWindowTitle(origin));
            });
            return SingleSignOnLoginWindow;
        };
        this.finalizeLogin = function (type) { return __awaiter(_this, void 0, void 0, function () {
            var error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(type === SingleSignOn.RESPONSE_TYPES.AUTH_SUCCESS)) return [3, 6];
                        if (!!this.session) return [3, 2];
                        return [4, this.dispatchResponse(SingleSignOn.RESPONSE_TYPES.AUTH_ERROR_SESS_NOT_AVAILABLE)];
                    case 1:
                        _a.sent();
                        return [2];
                    case 2:
                        _a.trys.push([2, 4, , 6]);
                        return [4, SingleSignOn.cookies.copy(this.session, this.mainSession, this.windowOriginUrl)];
                    case 3:
                        _a.sent();
                        return [3, 6];
                    case 4:
                        error_1 = _a.sent();
                        return [4, this.dispatchResponse(SingleSignOn.RESPONSE_TYPES.AUTH_ERROR_COOKIE)];
                    case 5:
                        _a.sent();
                        return [2];
                    case 6: return [4, this.dispatchResponse(type)];
                    case 7:
                        _a.sent();
                        return [2];
                }
            });
        }); };
        this.dispatchResponse = function (type) { return __awaiter(_this, void 0, void 0, function () {
            var isTypeValid;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        isTypeValid = /^[A-Z_]{1,255}$/g;
                        if (isTypeValid.test(type) === false) {
                            throw new Error('Invalid type detected, aborting.');
                        }
                        return [4, this.senderWebContents.executeJavaScript("window.dispatchEvent(new MessageEvent('message', {origin: '" + this.windowOriginUrl.origin + "', data: {type: '" + type + "'}, type: {isTrusted: true}}));")];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        }); };
        this.wipeSessionData = function () {
            return new Promise(function (resolve) {
                if (_this.session) {
                    _this.session.clearStorageData({}, function () { return resolve(); });
                }
                else {
                    resolve();
                }
            });
        };
        this.senderWebContents = senderEvent.sender;
        this.mainSession = this.senderWebContents.session;
        this.windowOriginUrl = new url_1.URL(windowOriginUrl);
    }
    SingleSignOn.ALLOWED_BACKEND_ORIGINS = config_1.BACKEND_ORIGINS;
    SingleSignOn.PRELOAD_SSO_JS = path.join(electron_1.app.getAppPath(), 'dist', 'js', 'preload-sso.js');
    SingleSignOn.SINGLE_SIGN_ON_FRAME_NAME = 'WIRE_SSO';
    SingleSignOn.SSO_PROTOCOL = 'wire-sso';
    SingleSignOn.SSO_PROTOCOL_HOST = 'response';
    SingleSignOn.SSO_PROTOCOL_RESPONSE_SIZE_LIMIT = 255;
    SingleSignOn.SSO_SESSION_NAME = 'sso';
    SingleSignOn.MAX_LENGTH_ORIGIN_DOMAIN = 255;
    SingleSignOn.MAX_LENGTH_ORIGIN = 'https://'.length + SingleSignOn.MAX_LENGTH_ORIGIN_DOMAIN;
    SingleSignOn.RESPONSE_TYPES = {
        AUTH_ERROR_COOKIE: 'AUTH_ERROR_COOKIE',
        AUTH_ERROR_SESS_NOT_AVAILABLE: 'AUTH_ERROR_SESS_NOT_AVAILABLE',
        AUTH_SUCCESS: 'AUTH_SUCCESS',
    };
    SingleSignOn.cookies = {
        copy: function (from, to, url) { return __awaiter(_this, void 0, void 0, function () {
            var e_1, _a, cookies, cookies_1, cookies_1_1, cookie, e_1_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4, SingleSignOn.cookies.getBackendCookies(from, url)];
                    case 1:
                        cookies = _b.sent();
                        _b.label = 2;
                    case 2:
                        _b.trys.push([2, 7, 8, 9]);
                        cookies_1 = __values(cookies), cookies_1_1 = cookies_1.next();
                        _b.label = 3;
                    case 3:
                        if (!!cookies_1_1.done) return [3, 6];
                        cookie = cookies_1_1.value;
                        return [4, SingleSignOn.cookies.setCookie(to, cookie, url.toString())];
                    case 4:
                        _b.sent();
                        _b.label = 5;
                    case 5:
                        cookies_1_1 = cookies_1.next();
                        return [3, 3];
                    case 6: return [3, 9];
                    case 7:
                        e_1_1 = _b.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 9];
                    case 8:
                        try {
                            if (cookies_1_1 && !cookies_1_1.done && (_a = cookies_1.return)) _a.call(cookies_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 9: return [4, SingleSignOn.cookies.flushCookies(to)];
                    case 10:
                        _b.sent();
                        return [2];
                }
            });
        }); },
        flushCookies: function (session) {
            return new Promise(function (resolve) {
                session.cookies.flushStore(resolve);
            });
        },
        getBackendCookies: function (session, url) {
            return new Promise(function (resolve, reject) {
                var rootDomain = url.hostname
                    .split('.')
                    .reverse()
                    .splice(0, 2)
                    .reverse()
                    .join('.');
                session.cookies.get({ domain: rootDomain, secure: true }, function (error, cookies) {
                    if (error) {
                        return reject(error);
                    }
                    resolve(cookies);
                });
            });
        },
        setCookie: function (session, cookie, url) {
            return new Promise(function (resolve, reject) {
                session.cookies.set(__assign({ url: url }, cookie), function (error) {
                    if (error) {
                        return reject(error);
                    }
                    resolve();
                });
            });
        },
    };
    SingleSignOn.protocol = {
        generateSecret: function (length) {
            return new Promise(function (resolve, reject) {
                crypto.randomBytes(length, function (error, bytes) {
                    if (error) {
                        return reject(error);
                    }
                    resolve(bytes.toString('hex'));
                });
            });
        },
        register: function (session, finalizeLogin) { return __awaiter(_this, void 0, void 0, function () {
            var _a, handleRequest;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = SingleSignOn;
                        return [4, SingleSignOn.protocol.generateSecret(24)];
                    case 1:
                        _a.loginAuthorizationSecret = _b.sent();
                        handleRequest = function (request, response) {
                            try {
                                var url = new url_1.URL(request.url);
                                if (url.protocol !== SingleSignOn.SSO_PROTOCOL + ":") {
                                    throw new Error('Protocol is invalid');
                                }
                                if (url.hostname !== SingleSignOn.SSO_PROTOCOL_HOST) {
                                    throw new Error('Host is invalid');
                                }
                                if (typeof SingleSignOn.loginAuthorizationSecret !== 'string') {
                                    throw new Error('Secret has not be set or has been consumed');
                                }
                                if (url.searchParams.get('secret') !== SingleSignOn.loginAuthorizationSecret) {
                                    throw new Error('Secret is invalid');
                                }
                                var type = url.searchParams.get('type');
                                if (typeof type !== 'string') {
                                    throw new Error('Response is empty');
                                }
                                if (type.length > SingleSignOn.SSO_PROTOCOL_RESPONSE_SIZE_LIMIT) {
                                    throw new Error('Response type is too long');
                                }
                                finalizeLogin(type);
                                response('Please wait...');
                            }
                            catch (error) {
                                response("An error happened, please close the window and try again. Error: " + error.toString());
                            }
                        };
                        session.protocol.registerStringProtocol(SingleSignOn.SSO_PROTOCOL, handleRequest, function (error) {
                            if (error) {
                                throw new Error("Failed to register protocol. Error: " + error);
                            }
                        });
                        return [2];
                }
            });
        }); },
        unregister: function (session) {
            return new Promise(function (resolve, reject) {
                session.protocol.unregisterProtocol(SingleSignOn.SSO_PROTOCOL, function (error) {
                    if (error) {
                        reject(error);
                    }
                    resolve();
                });
            });
        },
    };
    SingleSignOn.isSingleSignOnLoginWindow = function (frameName) { return SingleSignOn.SINGLE_SIGN_ON_FRAME_NAME === frameName; };
    SingleSignOn.isBackendOrigin = function (url) { return SingleSignOn.ALLOWED_BACKEND_ORIGINS.includes(new url_1.URL(url).origin); };
    SingleSignOn.getWindowTitle = function (origin) {
        return SingleSignOn.ALLOWED_BACKEND_ORIGINS.includes(origin) ? '' : origin;
    };
    SingleSignOn.javascriptHelper = function () {
        return "Object.defineProperty(window, 'opener', {\n      configurable: true, // Needed on Chrome :(\n      enumerable: false,\n      value: Object.freeze({\n        postMessage: ({type}) => {\n          const params = new URLSearchParams();\n          params.set('secret', '" + SingleSignOn.loginAuthorizationSecret + "');\n          params.set('type', type);\n          const url = new URL('" + SingleSignOn.SSO_PROTOCOL + "://" + SingleSignOn.SSO_PROTOCOL_HOST + "/');\n          url.search = params.toString();\n          document.location.href = url.toString();\n        }\n      }),\n      writable: false,\n    });";
    };
    return SingleSignOn;
}());
exports.SingleSignOn = SingleSignOn;
//# sourceMappingURL=SingleSignOn.js.map