infisical-autoenv/index.js

78 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-11-05 11:50:53 -07:00
import fs from "node:fs";
import os from "node:os";
import InfisicalClient from "infisical-node";
import rls from "readline-sync";
2023-11-05 17:41:45 -07:00
import { loadConfig, upsertConfig } from "./configurator.js";
2023-11-05 11:50:53 -07:00
const envpath = `${os.homedir()}/.env`;
//upsertConfig(); //TODO Build Configuration Generator
const config = loadConfig();
const secrets = {};
const siteURL = config.infisicalInstance;
const projects = config.projects;
const pendingSecrets = [];
2023-11-05 17:41:45 -07:00
async function getProjectSecrets(
project,
environment,
token,
path = "/",
includeImports = true,
) {
const client = new InfisicalClient({ token, siteURL });
const secrets = await client.getAllSecrets({
environment,
path,
includeImports,
attachToProcessEnv: false,
});
return secrets.map((s) => ({ ...s, project, path }));
2023-11-05 11:50:53 -07:00
}
2023-11-05 17:41:45 -07:00
function mapToFile(proj, secrets) {
const filename = `infisical-autoenv-${proj}`;
const date = new Date();
const dateString =
date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
const paths = Object.keys(secrets);
const lines = paths.map(
(p) =>
`# ---${p}--- ${dateString}\n` +
secrets[p]
.map((s) => `export ${s.secretName}=${s.secretValue}`)
.join("\n"),
);
const fileData = lines.join("\n");
fs.writeFileSync(`${envpath}/${filename}`, fileData);
2023-11-05 11:50:53 -07:00
}
2023-11-05 17:41:45 -07:00
for (var p of projects) {
for (var e of p.environments) {
if (!process.env[e.envar]) throw Error(`${e.envar} could not be found!`);
for (var path of e.paths) {
pendingSecrets.push(
getProjectSecrets(p.name, e.slug, process.env[e.envar], path),
);
}
}
2023-11-05 11:50:53 -07:00
}
2023-11-05 17:41:45 -07:00
const loadedSecrets = await Promise.all(pendingSecrets);
const filteredSecrets = loadedSecrets.flat(2).filter((s) => !s.isFallback);
2023-11-05 11:50:53 -07:00
2023-11-05 17:41:45 -07:00
const proj = projects.map((p) => ({
name: p.name,
paths: p.environments.map((envs) => envs.paths).flat(2),
}));
2023-11-05 11:50:53 -07:00
2023-11-05 17:41:45 -07:00
const projectSecrets = {};
for (var p of proj) {
projectSecrets[p.name] = {};
for (var path of p.paths) {
projectSecrets[p.name][path] = filteredSecrets.filter(
(s) => s.project === p.name && s.path === path,
);
}
mapToFile(p.name, projectSecrets[p.name]);
}