"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const misc_1 = require("./misc");
const promises_1 = require("fs/promises");
const node_forge_1 = require("node-forge");
const config_1 = require("./config");
exports.default = {
    async make_self_signed_cert({ attributes, fileName }) {
        (0, misc_1.apiAssertTypes)({
            object_undefined: { attributes },
            string_undefined: { fileName },
        });
        const keys = node_forge_1.pki.rsa.generateKeyPair(2048);
        const cert = node_forge_1.pki.createCertificate();
        cert.publicKey = keys.publicKey;
        cert.serialNumber = '01';
        cert.validity.notBefore = new Date();
        cert.validity.notAfter = new Date();
        cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
        const attrs = Object.entries(attributes || {}).map(x => ({ name: x[0], value: x[1] }));
        cert.setSubject(attrs);
        cert.setIssuer(attrs);
        cert.sign(keys.privateKey);
        const ret = {
            cert: node_forge_1.pki.certificateToPem(cert),
            private_key: node_forge_1.pki.privateKeyToPem(keys.privateKey),
        };
        if (!fileName)
            return ret;
        const configs = { cert: fileName + '.cer', private_key: fileName + '.key' };
        await (0, promises_1.writeFile)(configs.private_key, ret.private_key);
        await (0, promises_1.writeFile)(configs.cert, ret.cert);
        await (0, config_1.setConfig)(configs);
        return configs;
    }
};
