envilder
Version:
A CLI and GitHub Action that securely centralizes your environment variables from AWS SSM or Azure Key Vault as a single source of truth
221 lines • 10.1 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import * as fs from 'node:fs/promises';
import * as dotenv from 'dotenv';
import { inject, injectable } from 'inversify';
import { DependencyMissingError, EnvironmentFileError, } from '../../domain/errors/DomainErrors.js';
import { TYPES } from '../../types.js';
let FileVariableStore = class FileVariableStore {
constructor(logger) {
if (!logger) {
throw new DependencyMissingError('Logger must be specified');
}
this.logger = logger;
}
getMapping(source) {
return __awaiter(this, void 0, void 0, function* () {
const { mappings } = yield this.getParsedMapping(source);
return mappings;
});
}
getParsedMapping(source) {
return __awaiter(this, void 0, void 0, function* () {
const raw = yield this.readJsonFile(source);
const { $config } = raw, rest = __rest(raw, ["$config"]);
const config = $config && typeof $config === 'object' ? $config : {};
const mappings = {};
for (const [key, value] of Object.entries(rest)) {
if (!key.startsWith('$') && typeof value === 'string') {
mappings[key] = value;
}
}
return { config, mappings };
});
}
readJsonFile(source) {
return __awaiter(this, void 0, void 0, function* () {
try {
const content = yield fs.readFile(source, 'utf-8');
try {
return JSON.parse(content);
}
catch (_err) {
this.logger.error(`Error parsing JSON from ${source}`);
throw new EnvironmentFileError(`Invalid JSON in parameter map file: ${source}`);
}
}
catch (error) {
if (error instanceof EnvironmentFileError) {
throw error;
}
throw new EnvironmentFileError(`Failed to read map file: ${source}`);
}
});
}
getEnvironment(source) {
return __awaiter(this, void 0, void 0, function* () {
const envVariables = {};
try {
yield fs.access(source);
}
catch (_a) {
return envVariables;
}
const existingEnvContent = yield fs.readFile(source, 'utf-8');
const parsedEnv = dotenv.parse(existingEnvContent) || {};
Object.assign(envVariables, parsedEnv);
return envVariables;
});
}
saveEnvironment(destination, envVariables) {
return __awaiter(this, void 0, void 0, function* () {
const existingContent = yield this.readExistingEnvContent(destination);
const envContent = this.buildEnvContent(existingContent, envVariables);
try {
yield fs.writeFile(destination, envContent);
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
this.logger.error(`Failed to write environment file: ${errorMessage}`);
throw new EnvironmentFileError(`Failed to write environment file: ${errorMessage}`);
}
});
}
readExistingEnvContent(destination) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield fs.readFile(destination, 'utf-8');
}
catch (error) {
if (error instanceof Error &&
error.code === 'ENOENT') {
return null;
}
const message = error instanceof Error ? error.message : String(error);
this.logger.error(`Failed to read environment file: ${message}`);
throw new EnvironmentFileError(`Failed to read environment file: ${message}`);
}
});
}
buildEnvContent(existingContent, envVariables) {
const pending = Object.assign({}, envVariables);
if (existingContent === null) {
return Object.entries(pending)
.map(([key, value]) => `${key}=${this.escapeEnvValue(value)}`)
.join('\n');
}
const newline = existingContent.includes('\r\n') ? '\r\n' : '\n';
const hasTrailingNewline = /\r?\n$/.test(existingContent);
const lines = existingContent === '' ? [] : existingContent.split(/\r?\n/);
if (hasTrailingNewline) {
lines.pop();
}
const assignmentRegex = /^(\s*(?:export\s+)?)([\w.-]+)(\s*=\s*)(.*)$/;
const updatedKeys = new Set();
const mergedLines = lines.map((line) => {
const match = assignmentRegex.exec(line);
if (match === null) {
return line;
}
const [, prefix, key, separator, originalValue] = match;
if (!Object.hasOwn(pending, key)) {
return line;
}
updatedKeys.add(key);
const value = this.formatValue(pending[key], originalValue);
return `${prefix}${key}${separator}${value}`;
});
for (const key of updatedKeys) {
delete pending[key];
}
const appended = Object.entries(pending).map(([key, value]) => `${key}=${this.escapeEnvValue(value)}`);
const allLines = appended.length > 0 ? [...mergedLines, ...appended] : mergedLines;
const result = allLines.join(newline);
return hasTrailingNewline ? result + newline : result;
}
formatValue(newValue, originalValue) {
const trimmed = originalValue.trim();
const quote = trimmed[0];
const isQuoted = trimmed.length >= 2 &&
(quote === '"' || quote === "'") &&
trimmed[trimmed.length - 1] === quote;
// Only keep the original quotes when the new value can be wrapped safely.
// A value containing the same quote, a backslash, or a newline would
// produce a string dotenv cannot parse back, so fall back to the
// unquoted escaped form instead of corrupting the value.
const isSafeToWrap = !newValue.includes(quote) &&
!newValue.includes('\\') &&
!/[\r\n]/.test(newValue);
if (isQuoted && isSafeToWrap) {
return `${quote}${newValue}${quote}`;
}
return this.escapeEnvValue(newValue);
}
escapeEnvValue(value) {
// codeql[js/incomplete-sanitization]
// CodeQL flags this as incomplete sanitization because we don't escape backslashes
// before newlines. However, this is intentional: the dotenv library does NOT
// interpret escape sequences (it treats \n literally as backslash+n, not as a newline).
// Therefore, escaping backslashes would actually break the functionality by
// doubling them when read back by dotenv. This is not a security issue in this context.
return value.replace(/(\r\n|\n|\r)/g, '\\n');
}
};
FileVariableStore = __decorate([
injectable(),
__param(0, inject(TYPES.ILogger)),
__metadata("design:paramtypes", [Object])
], FileVariableStore);
export { FileVariableStore };
export function readMapFileConfig(mapPath) {
return __awaiter(this, void 0, void 0, function* () {
try {
const content = yield fs.readFile(mapPath, 'utf-8');
try {
const raw = JSON.parse(content);
const config = raw.$config;
return config && typeof config === 'object' ? config : {};
}
catch (_a) {
throw new EnvironmentFileError(`Invalid JSON in parameter map file: ${mapPath}`);
}
}
catch (error) {
if (error instanceof EnvironmentFileError) {
throw error;
}
throw new EnvironmentFileError(`Failed to read map file: ${mapPath}`);
}
});
}
//# sourceMappingURL=FileVariableStore.js.map