@szegedsw/lib-node
Version:
A little framework published by Szeged Software Zrt. in order to enhance api endpoint security and create reuseable code. Email module, Logging system, and much more. Further improvements are expected.
103 lines • 5.02 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.certHandler = exports.certErrors = void 0;
const fs = __importStar(require("fs"));
const node_forge_1 = __importDefault(require("node-forge"));
const path_1 = require("path");
const config_1 = require("../config/config");
const logger_1 = require("../logger/logger");
exports.certErrors = {
ENOENT: { code: "notFound", body: "File not found!", override: "file not found" },
"PKCS#12 MAC could not be verified. Invalid password?": {
code: "unprocessableEntity",
body: "Invalid certificate passphrase!",
override: "invalid password",
},
"Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.": {
code: "unprocessableEntity",
body: "File is not in P12 format!",
override: "wrong p12 format",
},
"Too few bytes to parse DER.": {
code: "unprocessableEntity",
body: "Certificate file is empty!",
override: "too few bytes",
},
"key or cert missing": { code: "unprocessableEntity", body: "Key or certificate is missing from P12!" },
"bad clientid": {
code: "conflict",
body: "Client ID is not in accordance with certificate file attributes! (_organizationName/_commonName)",
},
};
/**
* @description Process certificate, split into cert and key.
* @param file file name, file in string or Buffer containing base64 value, encoded in utf8
* @param passphrase provide passphrase for unlocking certificate
* @param clientId optional client ID to be checked against organization and common name
* @param folder optional folder for placing the newly created files
* @throws different errors, please import "certErrors" for full list
*/
function certHandler(file, passphrase, clientId, folder) {
var _a, _b;
let fileValue;
let fileName;
if (typeof file === "string") {
if (fs.existsSync(file)) {
fileValue = fs.readFileSync(file, { encoding: "base64" });
fileName = file;
}
else {
fileValue = file;
}
}
else {
fileValue = file.toString("base64");
}
const p12Der = node_forge_1.default.util.decode64(fileValue);
const p12 = node_forge_1.default.pkcs12.pkcs12FromAsn1(node_forge_1.default.asn1.fromDer(p12Der), false, passphrase);
// fetching certBag
const certBag = (_a = p12.getBags({ bagType: node_forge_1.default.pki.oids.certBag })[node_forge_1.default.pki.oids.certBag]) === null || _a === void 0 ? void 0 : _a[0];
// fetching keyBag
const keyBag = (_b = p12.getBags({ bagType: node_forge_1.default.pki.oids.pkcs8ShroudedKeyBag })[node_forge_1.default.pki.oids.pkcs8ShroudedKeyBag]) === null || _b === void 0 ? void 0 : _b[0];
if (!(keyBag === null || keyBag === void 0 ? void 0 : keyBag.key) || !(certBag === null || certBag === void 0 ? void 0 : certBag.cert)) {
throw new Error("key or cert missing");
}
const notAfter = certBag.cert.validity.notAfter;
logger_1.Logger.trace(certBag.cert.subject.attributes);
const organizationName = certBag.cert.subject.getField({ name: "organizationName" }).value;
const commonName = certBag.cert.subject.getField({ name: "commonName" }).value;
if (clientId && clientId !== `${organizationName}/${commonName}`) {
throw new Error(`bad clientid +organizationName=${organizationName} +commonName=${commonName}`);
}
let rawFileName = fileName === null || fileName === void 0 ? void 0 : fileName.split(".").reverse().slice(1).reverse().join(".");
if (!rawFileName) {
rawFileName = (folder || config_1.env.uploadDirectory) + path_1.sep + commonName;
}
fs.writeFileSync(`${rawFileName}.key.pem`, node_forge_1.default.pki.privateKeyToPem(keyBag.key));
fs.writeFileSync(`${rawFileName}.crt.pem`, node_forge_1.default.pki.certificateToPem(certBag.cert));
return { rawFileName, notAfter, organizationName, commonName };
}
exports.certHandler = certHandler;
//# sourceMappingURL=cert-handler.js.map