async function createCertFile()

in lib/CertificateTools.js [54:210]


async function createCertFile(config, open) {
    ConsoleWriter.info(`Generating a new certificate...`);
    const subject = "localhost";
    const keyLength = 2048;
    const algorithm = "sha256";
    const validPeriod = 365;

    if (typeof open === 'undefined') {
        open = false;
    }

    let certPath = path.join(__dirname, '..', config.server.certificate);
    let keyPath = path.join(__dirname, '..', config.server.privateKey);
    let pfxPath = path.join(__dirname, '..', config.server.pfx);

    let openCmds = {
        linux: 'openssl',
        darwin: 'openssl',
        win32: 'powershell'
    };
    let startCmd = openCmds[os.platform()];

    if (startCmd) {
        try {
            let createCertCommand = "";
            switch (os.platform()) {
                case "linux":
                    await removeCertFiles(certPath, keyPath);
                    createCertCommand =
                        `  req -newkey rsa:${keyLength}` +
                        ` -nodes` +
                        ` -keyout ${keyPath}` +
                        ` -x509 ` +
                        ` -days ${validPeriod} ` +
                        ` -out ${certPath} ` +
                        ` -subj "/CN=${subject}"`;
                    await exec(`${startCmd} ${createCertCommand}`);
                    if (await fs.exists(certPath)) {
                        ConsoleWriter.info(`Certificate generated. Location is ${certPath}`);
                        if (open) {
                            await openCertFile(config);
                        }
                    }
                    break;
                case "darwin":
                    await removeCertFiles(certPath, keyPath);
                    createCertCommand =
                        `  req -newkey rsa:${keyLength}` +
                        ` -nodes` +
                        ` -keyout ${keyPath}` +
                        ` -x509 ` +
                        ` -days ${validPeriod} ` +
                        ` -out ${certPath} ` +
                        ` -subj "/CN=${subject}"`;
                    await exec(`${startCmd} ${createCertCommand}`);
                    if (await fs.exists(certPath)) {
                        ConsoleWriter.info(`Certificate generated. Location is ${certPath}`);
                        if (open) {
                            await openCertFile(config);
                        }
                    }
                    break;
                case "win32":
                    let passphrase = "";
                    // for windows 7 and others
                    // 6.1 - Windows 7
                    let osVersion = os.release().split(".");
                    if ((Number(osVersion[0]) === 6 && Number(osVersion[1]) === 1) || Number(osVersion[0]) < 6) {
                        await removeCertFiles(certPath, keyPath, pfxPath);
                        startCmd = "openssl";
                        createCertCommand =
                            `  req -newkey rsa:${keyLength}` +
                            ` -nodes` +
                            ` -keyout ${keyPath}` +
                            ` -x509 ` +
                            ` -days ${validPeriod} ` +
                            ` -out ${certPath} ` +
                            ` -subj "/CN=${subject}"`;
                        await exec(`${startCmd} ${createCertCommand}`);
                        if (await fs.exists(certPath)) {
                            ConsoleWriter.info(`Certificate generated. Location is ${certPath}`);
                            if (open) {
                                await openCertFile(config);
                            }
                        }
                        break;
                    }
                    // for windows 8 / 8.1 / server 2012 R2 /
                    if (Number(osVersion[0]) === 6 && (Number(osVersion[1]) === 2 || Number(osVersion[1]) === 3)) {
                        // for 10
                        passphrase = Math.random().toString().substring(2);
                        config.server.passphrase = passphrase;
                        fs.writeFileSync(path.join(__dirname, confPath), JSON.stringify(config));

                        createCertCommand = `$cert = ('Cert:\\CurrentUser\\My\\' + (` +
                            `   New-SelfSignedCertificate ` +
                            `       -DnsName localhost ` +
                            `       -CertStoreLocation Cert:\\CurrentUser\\My ` +
                            `   | select Thumbprint | ` +
                            `   ForEach-Object { $_.Thumbprint.ToString() }).toString()); ` +
                            `   Export-PfxCertificate -Cert $cert` +
                            `       -FilePath '${pfxPath}' ` +
                            `       -Password (ConvertTo-SecureString -String '${passphrase}' -Force -AsPlainText)`;

                        await exec(`${startCmd} "${createCertCommand}"`);
                        if (await fs.exists(pfxPath)) {
                            ConsoleWriter.info(`Certificate generated. Location is ${pfxPath}. Passphrase is '${passphrase}'`);
                        }
                    } else {
                        // for window 10 / server 2016
                        passphrase = Math.random().toString().substring(2);
                        config.server.passphrase = passphrase;
                        fs.writeFileSync(path.join(__dirname, confPath), JSON.stringify(config));

                        createCertCommand = `$cert = ('Cert:\\CurrentUser\\My\\' + (` +
                            `   New-SelfSignedCertificate ` +
                            `       -DnsName localhost ` +
                            `       -HashAlgorithm ${algorithm} ` +
                            `       -Type Custom ` +
                            `       -Subject ${subject} ` +
                            `       -KeyAlgorithm RSA ` +
                            `       -KeyLength ${keyLength} ` +
                            `       -KeyExportPolicy Exportable ` +
                            `       -CertStoreLocation Cert:\\CurrentUser\\My ` +
                            `       -NotAfter (get-date).AddDays(${validPeriod}) ` +
                            `   | select Thumbprint | ` +
                            `   ForEach-Object { $_.Thumbprint.ToString() }).toString()); ` +
                            `   Export-PfxCertificate -Cert $cert` +
                            `       -FilePath '${pfxPath}' ` +
                            `       -Password (ConvertTo-SecureString -String '${passphrase}' -Force -AsPlainText)`;

                        await exec(`${startCmd} "${createCertCommand}"`);
                        if (await fs.exists(pfxPath)) {
                            ConsoleWriter.info(`Certificate generated. Location is ${pfxPath}. Passphrase is '${passphrase}'`);
                        }
                    }
                    break;
                default:
                    ConsoleWriter.error('Unknown platform');
            }
        } catch (e) {
            if (e && e.message && e.message.indexOf("'openssl' is not recognized as an internal or external command") > 0) {
                ConsoleWriter.warn('Create certificate error:');
                ConsoleWriter.warn('OpenSSL is not installed or not available from command line');
                ConsoleWriter.info('Install OpenSSL from https://www.openssl.org or https://wiki.openssl.org/index.php/Binaries');
                ConsoleWriter.info('and try again');

                ConsoleWriter.info('Read more at');
                ConsoleWriter.info('https://github.com/Microsoft/PowerBI-visuals/blob/master/tools/CreateCertificate.md#manual');
            } else {
                ConsoleWriter.error('Create certificate error:', e);
            }
        }
    } else {
        ConsoleWriter.error('Unknown platform. Please place a custom-generated certificate in:', certPath);
    }
}