UNPKG

@probot/get-private-key

Version:

Get private key from a path, environment variables, or a `*.pem` file in the current working directory

96 lines (93 loc) 3.04 kB
// pkg/dist-src/index.js import { resolve } from "node:path"; import { existsSync, readdirSync, readFileSync } from "node:fs"; // pkg/dist-src/version.js var VERSION = "0.0.0-development"; // pkg/dist-src/index.js var pkcs1Begin = "-----BEGIN RSA PRIVATE KEY-----"; var pkcs1End = "-----END RSA PRIVATE KEY-----"; var pkcs8Begin = "-----BEGIN PRIVATE KEY-----"; var pkcs8End = "-----END PRIVATE KEY-----"; function isPKCS1(privateKey) { return privateKey.includes(pkcs1Begin) && privateKey.includes(pkcs1End); } function isPKCS8(privateKey) { return privateKey.includes(pkcs8Begin) && privateKey.includes(pkcs8End); } function getPrivateKey(options = {}) { const env = options.env || process.env; const cwd = options.cwd || process.cwd(); if (options.filepath) { return readFileSync(resolve(cwd, options.filepath), "utf-8"); } if (env.PRIVATE_KEY) { let privateKey = env.PRIVATE_KEY; if (isBase64(privateKey)) { privateKey = Buffer.from(privateKey, "base64").toString(); } if (privateKey.indexOf("\\n") !== -1) { privateKey = privateKey.replace(/\\n/g, "\n"); } if (isPKCS1(privateKey)) { if (privateKey.indexOf("\n") === -1) { privateKey = addNewlines({ privateKey, begin: pkcs1Begin, end: pkcs1End }); } return privateKey; } if (isPKCS8(privateKey)) { if (privateKey.indexOf("\n") === -1) { privateKey = addNewlines({ privateKey, begin: pkcs8Begin, end: pkcs8End }); } return privateKey; } throw new Error( `[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.` ); } if (env.PRIVATE_KEY_PATH) { const filepath = resolve(cwd, env.PRIVATE_KEY_PATH); if (existsSync(filepath)) { return readFileSync(filepath, "utf-8"); } else { throw new Error( `[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.` ); } } const pemFiles = readdirSync(cwd).filter((path) => path.endsWith(".pem")); if (pemFiles.length > 1) { const paths = pemFiles.join(", "); throw new Error( `[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH` ); } else if (pemFiles[0]) { return getPrivateKey({ filepath: pemFiles[0], cwd }); } return null; } function isBase64(str) { return Buffer.from(str, "base64").toString("base64") === str; } function addNewlines({ privateKey, begin, end }) { const middleLength = privateKey.length - begin.length - end.length - 2; const middle = privateKey.substr(begin.length + 1, middleLength); return `${begin} ${middle.trim().replace(/\s+/g, "\n")} ${end}`; } getPrivateKey.VERSION = VERSION; export { getPrivateKey };