"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 };
        }
    };
};
Object.defineProperty(exports, "__esModule", { value: true });
var certificateUtils = require("@wireapp/certificate-check");
var electron_1 = require("electron");
var fs = require("fs-extra");
var path = require("path");
var environment = require("../js/environment");
var locale_1 = require("../locale/locale");
var util_1 = require("../util/");
var LOG_DIR = path.join(electron_1.app.getPath('userData'), 'logs');
util_1.LogFactory.LOG_FILE_PATH = LOG_DIR;
util_1.LogFactory.LOG_FILE_NAME = 'electron.log';
var logger = util_1.LogFactory.getLogger('CertificateVerifyProcManager.ts', { forceEnable: true });
var CertificateVerifyProcManager = (function () {
    function CertificateVerifyProcManager() {
    }
    CertificateVerifyProcManager.displayCertificateDetails = function (hostname, certificate, options) {
        var _this = this;
        var goBack = function () {
            _this.displayCertificateError(hostname, certificate, __assign({}, options, { bypassDialogLock: true }));
        };
        var textDetails = (options.isChromiumError ? this.LOCALE.SHOW_DETAILS_TEXT_CHROMIUM : this.LOCALE.SHOW_DETAILS_TEXT_PINNING) + " " + hostname;
        var isTrustDialogSupported = environment.platform.IS_MAC_OS;
        if (isTrustDialogSupported) {
            electron_1.dialog.showCertificateTrustDialog({
                certificate: certificate,
                message: textDetails,
            }, goBack);
        }
        else {
            electron_1.dialog.showMessageBox({
                buttons: [this.LOCALE.SHOW_DETAILS_GO_BACK, this.LOCALE.SHOW_DETAILS_SAVE_CERTIFICATE],
                cancelId: this.RESPONSE.GO_BACK,
                detail: textDetails,
                message: this.LOCALE.SHOW_DETAILS_TITLE,
                type: 'info',
            }, function (response) {
                switch (response) {
                    case _this.RESPONSE.SAVE_CERTIFICATE: {
                        electron_1.dialog.showSaveDialog({
                            defaultPath: hostname + ".pem",
                        }, function (chosenPath) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (!(chosenPath !== undefined)) return [3, 2];
                                        return [4, fs.writeFile(chosenPath, Buffer.from(certificate.data))];
                                    case 1:
                                        _a.sent();
                                        _a.label = 2;
                                    case 2:
                                        this.displayCertificateDetails(hostname, certificate, options);
                                        return [2];
                                }
                            });
                        }); });
                        break;
                    }
                    case _this.RESPONSE.GO_BACK: {
                        goBack();
                        break;
                    }
                }
            });
        }
    };
    CertificateVerifyProcManager.isCertificatePinningEnabled = function () {
        return !this.bypassCertificatePinning;
    };
    CertificateVerifyProcManager.displayCertificateChromiumError = function (hostname, certificate) {
        this.displayCertificateError(hostname, certificate, { isChromiumError: true });
    };
    CertificateVerifyProcManager.displayCertificateError = function (hostname, certificate, options) {
        var _this = this;
        var _a = __assign({ bypassDialogLock: false, isCheckboxChecked: false, isChromiumError: false }, options), bypassDialogLock = _a.bypassDialogLock, isChromiumError = _a.isChromiumError, isCheckboxChecked = _a.isCheckboxChecked;
        if (this.isDialogLocked && !bypassDialogLock) {
            return;
        }
        this.isDialogLocked = true;
        electron_1.dialog.showMessageBox({
            buttons: [this.LOCALE.RETRY, this.LOCALE.SHOW_DETAILS],
            cancelId: this.RESPONSE.RETRY,
            checkboxChecked: isChromiumError ? undefined : isCheckboxChecked,
            checkboxLabel: isChromiumError ? undefined : this.LOCALE.WARNING_BYPASS,
            defaultId: this.RESPONSE.RETRY,
            detail: isChromiumError ? this.LOCALE.WARNING_TEXT_CHROMIUM : this.LOCALE.WARNING_TEXT_PINNING,
            message: this.LOCALE.WARNING_TITLE,
            type: 'warning',
        }, function (response, checkboxChecked) {
            switch (response) {
                case _this.RESPONSE.RETRY: {
                    if (!isChromiumError) {
                        _this.bypassCertificatePinning = checkboxChecked;
                        if (_this.bypassCertificatePinning) {
                            logger.log('User disabled certificate pinning');
                        }
                    }
                    setTimeout(function () { return (_this.isDialogLocked = false); }, _this.dialogUnlockTimeout);
                    break;
                }
                case _this.RESPONSE.SHOW_DETAILS: {
                    _this.displayCertificateDetails(hostname, certificate, {
                        bypassDialogLock: bypassDialogLock,
                        isCheckboxChecked: checkboxChecked,
                        isChromiumError: isChromiumError,
                    });
                    break;
                }
            }
        });
    };
    CertificateVerifyProcManager.bypassCertificatePinning = false;
    CertificateVerifyProcManager.isDialogLocked = false;
    CertificateVerifyProcManager.dialogUnlockTimeout = 6000;
    CertificateVerifyProcManager.CHROMIUM_ERRORS = {
        CERT_AUTHORITY_INVALID: -202,
        CERT_COMMON_NAME_INVALID: -200,
    };
    CertificateVerifyProcManager.RESPONSE = {
        RETRY: 0,
        SHOW_DETAILS: 1,
        GO_BACK: 0,
        SAVE_CERTIFICATE: 1,
    };
    CertificateVerifyProcManager.LOCALE = {
        RETRY: locale_1.getText('certificateVerifyProcManagerRetry'),
        SHOW_DETAILS: locale_1.getText('certificateVerifyProcManagerShowDetails'),
        SHOW_DETAILS_GO_BACK: locale_1.getText('certificateVerifyProcManagerShowDetailsGoBack'),
        SHOW_DETAILS_SAVE_CERTIFICATE: locale_1.getText('certificateVerifyProcManagerShowDetailsSaveCertificate'),
        SHOW_DETAILS_TEXT_CHROMIUM: locale_1.getText('certificateVerifyProcManagerShowDetailsTextChromium'),
        SHOW_DETAILS_TEXT_PINNING: locale_1.getText('certificateVerifyProcManagerShowDetailsTextPinning'),
        SHOW_DETAILS_TITLE: locale_1.getText('certificateVerifyProcManagerShowDetailsTitle'),
        WARNING_BYPASS: locale_1.getText('certificateVerifyProcManagerWarningBypass'),
        WARNING_TEXT_CHROMIUM: locale_1.getText('certificateVerifyProcManagerWarningTextChromium'),
        WARNING_TEXT_PINNING: locale_1.getText('certificateVerifyProcManagerWarningTextPinning'),
        WARNING_TITLE: locale_1.getText('certificateVerifyProcManagerWarningTitle'),
    };
    return CertificateVerifyProcManager;
}());
exports.setCertificateVerifyProc = function (request, cb) {
    var e_1, _a;
    var hostname = request.hostname, certificate = request.certificate, verificationResult = request.verificationResult, errorCode = request.errorCode;
    if (verificationResult !== 'net::OK') {
        logger.error("Internal Chrome TLS verification failed. Hostname: " + hostname + ". Verification result: " + verificationResult + ". Error code: " + errorCode);
        var isCommonCertificateError = errorCode === CertificateVerifyProcManager.CHROMIUM_ERRORS.CERT_COMMON_NAME_INVALID ||
            errorCode === CertificateVerifyProcManager.CHROMIUM_ERRORS.CERT_AUTHORITY_INVALID;
        if (isCommonCertificateError) {
            CertificateVerifyProcManager.displayCertificateChromiumError(hostname, certificate);
        }
        return cb(-2);
    }
    if (certificateUtils.hostnameShouldBePinned(hostname) && CertificateVerifyProcManager.isCertificatePinningEnabled()) {
        var pinningResults = certificateUtils.verifyPinning(hostname, certificate);
        try {
            for (var _b = __values(Object.values(pinningResults)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var result = _c.value;
                if (result === false) {
                    logger.error("Certificate verification failed for \"" + hostname + "\":\n" + pinningResults.errorMessage + ", showing certificate pinning error dialog.");
                    CertificateVerifyProcManager.displayCertificateError(hostname, certificate);
                    return cb(-2);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    return cb(-3);
};
//# sourceMappingURL=CertificateVerifyProcManager.js.map