| | | 1 | | import { readFile } from 'node:fs/promises'; |
| | | 2 | | import type { ContractValidationResult } from '../domain/contract-validation-result.js'; |
| | | 3 | | import type { EnvilderOptions } from '../domain/envilder-options.js'; |
| | | 4 | | import type { ParsedMapFile } from '../domain/parsed-map-file.js'; |
| | | 5 | | import type { ISecretExistenceChecker } from '../domain/ports/secret-existence-checker.js'; |
| | | 6 | | import type { ISecretProvider } from '../domain/ports/secret-provider.js'; |
| | | 7 | | import { SecretProviderType } from '../domain/secret-provider-type.js'; |
| | | 8 | | import { createSecretProvider } from '../infrastructure/secret-provider-factory.js'; |
| | | 9 | | import { |
| | | 10 | | ContractValidationError, |
| | | 11 | | checkRemoteKeys, |
| | | 12 | | invalidMapFileResult, |
| | | 13 | | notCheckableResult, |
| | | 14 | | } from './contract-validation.js'; |
| | | 15 | | import { EnvilderClient } from './envilder-client.js'; |
| | | 16 | | import { MapFileParser } from './map-file-parser.js'; |
| | | 17 | | import { validateMapFileContent } from './map-file-validator.js'; |
| | | 18 | | |
| | | 19 | | /** |
| | | 20 | | * Facade for loading secrets from cloud providers. |
| | | 21 | | * |
| | | 22 | | * Supports loading from a single map file or from an |
| | | 23 | | * environment-based mapping that routes each environment name |
| | | 24 | | * to its own map file (or `null` to skip). |
| | | 25 | | * |
| | | 26 | | * @example |
| | | 27 | | * ```typescript |
| | | 28 | | * // One-liner — resolve + inject into process.env: |
| | | 29 | | * await Envilder.load('envilder.json'); |
| | | 30 | | * |
| | | 31 | | * // Resolve without injecting: |
| | | 32 | | * const secrets = await Envilder.resolveFile('envilder.json'); |
| | | 33 | | * |
| | | 34 | | * // Fluent builder with provider override: |
| | | 35 | | * const secrets = await Envilder.fromMapFile('envilder.json') |
| | | 36 | | * .withProvider(SecretProviderType.Azure) |
| | | 37 | | * .withVaultUrl('https://my-vault.vault.azure.net') |
| | | 38 | | * .inject(); |
| | | 39 | | * |
| | | 40 | | * // Check the map file contract without loading anything: |
| | | 41 | | * const result = await Envilder.fromMapFile('envilder.json').validateContract(); |
| | | 42 | | * |
| | | 43 | | * // Fail the load when the contract does not hold: |
| | | 44 | | * await Envilder.fromMapFile('envilder.json').withContractValidation().inject(); |
| | | 45 | | * |
| | | 46 | | * // Use your own provider instance (for example, an in-memory fake in tests): |
| | | 47 | | * await Envilder.fromMapFile('envilder.json') |
| | | 48 | | * .withSecretProvider(fakeProvider) |
| | | 49 | | * .withContractValidation() |
| | | 50 | | * .inject(); |
| | | 51 | | * ``` |
| | | 52 | | */ |
| | | 53 | | export class Envilder { |
| | | 54 | | private readonly filePath: string; |
| | 25 | 55 | | private options: EnvilderOptions = {}; |
| | 25 | 56 | | private contractValidation = false; |
| | | 57 | | private secretProvider?: ISecretProvider; |
| | | 58 | | |
| | | 59 | | private constructor(filePath: string) { |
| | 25 | 60 | | this.filePath = filePath; |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | /** |
| | | 64 | | * Returns a fluent builder bound to the given map file. |
| | | 65 | | * |
| | | 66 | | * Chain `.withProvider()`, `.withVaultUrl()`, or `.withProfile()` |
| | | 67 | | * before calling `.resolve()` or `.inject()`. |
| | | 68 | | */ |
| | | 69 | | static fromMapFile(filePath: string): Envilder { |
| | 22 | 70 | | validateFilePath(filePath); |
| | 22 | 71 | | return new Envilder(filePath.trim()); |
| | | 72 | | } |
| | | 73 | | |
| | | 74 | | /** |
| | | 75 | | * Resolves secrets and injects them into `process.env`. |
| | | 76 | | * |
| | | 77 | | * Can be called in two ways: |
| | | 78 | | * - `load(filePath)` — load from a single map file |
| | | 79 | | * - `load(env, envMapping)` — look up env in the mapping |
| | | 80 | | */ |
| | | 81 | | static async load( |
| | | 82 | | filePathOrEnv: string, |
| | | 83 | | envMapping?: Record<string, string | null>, |
| | | 84 | | ): Promise<Map<string, string>> { |
| | 8 | 85 | | if (envMapping !== undefined) { |
| | 5 | 86 | | const source = resolveEnvSource(filePathOrEnv, envMapping); |
| | 5 | 87 | | if (source === null) { |
| | 2 | 88 | | return new Map(); |
| | | 89 | | } |
| | 1 | 90 | | return new Envilder(source).inject(); |
| | | 91 | | } |
| | | 92 | | |
| | 3 | 93 | | validateFilePath(filePathOrEnv); |
| | 3 | 94 | | return new Envilder(filePathOrEnv.trim()).inject(); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | /** |
| | | 98 | | * Resolves secrets without injecting into `process.env`. |
| | | 99 | | * |
| | | 100 | | * Can be called in two ways: |
| | | 101 | | * - `resolveFile(filePath)` — resolve from a single map file |
| | | 102 | | * - `resolveFile(env, envMapping)` — look up env in the mapping |
| | | 103 | | */ |
| | | 104 | | static async resolveFile( |
| | | 105 | | filePathOrEnv: string, |
| | | 106 | | envMapping?: Record<string, string | null>, |
| | | 107 | | ): Promise<Map<string, string>> { |
| | 4 | 108 | | if (envMapping !== undefined) { |
| | 3 | 109 | | const source = resolveEnvSource(filePathOrEnv, envMapping); |
| | 3 | 110 | | if (source === null) { |
| | 2 | 111 | | return new Map(); |
| | | 112 | | } |
| | 1 | 113 | | return new Envilder(source).resolve(); |
| | | 114 | | } |
| | | 115 | | |
| | 1 | 116 | | validateFilePath(filePathOrEnv); |
| | 1 | 117 | | return new Envilder(filePathOrEnv.trim()).resolve(); |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | /** Override the secret provider (AWS or Azure). */ |
| | | 121 | | withProvider(provider: SecretProviderType): Envilder { |
| | 2 | 122 | | this.options.provider = provider; |
| | 2 | 123 | | return this; |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | /** Override the Azure Key Vault URL. */ |
| | | 127 | | withVaultUrl(vaultUrl: string): Envilder { |
| | 2 | 128 | | this.options.vaultUrl = vaultUrl; |
| | 2 | 129 | | return this; |
| | | 130 | | } |
| | | 131 | | |
| | | 132 | | /** Override the AWS named profile. */ |
| | | 133 | | withProfile(profile: string): Envilder { |
| | 1 | 134 | | this.options.profile = profile; |
| | 1 | 135 | | return this; |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | /** |
| | | 139 | | * Use this provider instance instead of building one from the map file |
| | | 140 | | * `$config`. The map file is still validated as usual, and the provider |
| | | 141 | | * overrides still set the provider type reported by |
| | | 142 | | * {@link validateContract}. To take part in contract validation, the |
| | | 143 | | * provider must also implement {@link ISecretExistenceChecker}; otherwise |
| | | 144 | | * every key is reported as `provider_error`. |
| | | 145 | | */ |
| | | 146 | | withSecretProvider(provider: ISecretProvider): Envilder { |
| | 7 | 147 | | if (!provider) { |
| | 1 | 148 | | throw new Error('provider cannot be null or undefined'); |
| | | 149 | | } |
| | 6 | 150 | | this.secretProvider = provider; |
| | 6 | 151 | | return this; |
| | | 152 | | } |
| | | 153 | | |
| | | 154 | | /** |
| | | 155 | | * Run {@link validateContract} once before resolving, and fail the load |
| | | 156 | | * with a {@link ContractValidationError} when it does not pass. Off by |
| | | 157 | | * default: without it, a load makes no extra provider call. |
| | | 158 | | */ |
| | | 159 | | withContractValidation(): Envilder { |
| | 5 | 160 | | this.contractValidation = true; |
| | 5 | 161 | | return this; |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | /** |
| | | 165 | | * Checks the map file contract without reading any secret value: the map |
| | | 166 | | * file matches `spec/map-file.v1.json` and the provider configuration it |
| | | 167 | | * resolves to is coherent, and every declared secret exists. Expected |
| | | 168 | | * failures (invalid map file, missing secret, access denied, rejected |
| | | 169 | | * credentials, provider errors) are reported in the result, not thrown. |
| | | 170 | | * When the map file is invalid, no provider is called. |
| | | 171 | | */ |
| | | 172 | | async validateContract(): Promise<ContractValidationResult> { |
| | 10 | 173 | | const { result } = await this.checkContract(await this.readMapFile()); |
| | 9 | 174 | | return result; |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | /** Resolve secrets and return them as a Map. */ |
| | | 178 | | async resolve(): Promise<Map<string, string>> { |
| | 14 | 179 | | const json = await this.readMapFile(); |
| | 14 | 180 | | if (this.contractValidation) { |
| | 5 | 181 | | const { result, mapFile, provider } = await this.checkContract(json); |
| | 5 | 182 | | if (!result.isValid || mapFile === undefined || provider === undefined) { |
| | 3 | 183 | | throw new ContractValidationError(result); |
| | | 184 | | } |
| | 2 | 185 | | return new EnvilderClient(provider).resolveSecrets(mapFile); |
| | | 186 | | } |
| | 9 | 187 | | const mapFile = new MapFileParser().parse(json); |
| | 9 | 188 | | const provider = this.createProvider(mapFile); |
| | 9 | 189 | | const client = new EnvilderClient(provider); |
| | 9 | 190 | | return client.resolveSecrets(mapFile); |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | /** Resolve secrets, inject into `process.env`, and return them. */ |
| | | 194 | | async inject(): Promise<Map<string, string>> { |
| | 7 | 195 | | const secrets = await this.resolve(); |
| | 5 | 196 | | EnvilderClient.injectIntoEnvironment(secrets); |
| | 5 | 197 | | return secrets; |
| | | 198 | | } |
| | | 199 | | |
| | | 200 | | /** |
| | | 201 | | * Validates the map file and, when it is valid, checks every declared key |
| | | 202 | | * with the provider a load would use, which is returned for that load. |
| | | 203 | | */ |
| | | 204 | | private async checkContract(json: string): Promise<{ |
| | | 205 | | result: ContractValidationResult; |
| | | 206 | | mapFile?: ParsedMapFile; |
| | | 207 | | provider?: ISecretProvider; |
| | | 208 | | }> { |
| | 14 | 209 | | const mapFileErrors = validateMapFileContent(json, this.options); |
| | 14 | 210 | | if (mapFileErrors.length > 0) { |
| | 3 | 211 | | return { result: invalidMapFileResult(mapFileErrors) }; |
| | | 212 | | } |
| | 11 | 213 | | const mapFile = new MapFileParser().parse(json); |
| | 11 | 214 | | const provider = this.createProvider(mapFile); |
| | | 215 | | const providerType = |
| | 11 | 216 | | this.options.provider ?? |
| | | 217 | | mapFile.config.provider ?? |
| | | 218 | | SecretProviderType.Aws; |
| | 14 | 219 | | const result = canCheckExistence(provider) |
| | | 220 | | ? await checkRemoteKeys(mapFile, provider, providerType) |
| | | 221 | | : notCheckableResult(mapFile, providerType); |
| | 14 | 222 | | return { result, mapFile, provider }; |
| | | 223 | | } |
| | | 224 | | |
| | | 225 | | private createProvider(mapFile: ParsedMapFile): ISecretProvider { |
| | 20 | 226 | | return ( |
| | | 227 | | this.secretProvider ?? |
| | | 228 | | createSecretProvider(mapFile.config, this.buildOptions()) |
| | | 229 | | ); |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | private async readMapFile(): Promise<string> { |
| | 24 | 233 | | try { |
| | 24 | 234 | | return await readFile(this.filePath, 'utf-8'); |
| | | 235 | | } catch (err: unknown) { |
| | 1 | 236 | | if (err instanceof Error && 'code' in err && err.code === 'ENOENT') { |
| | 1 | 237 | | throw new Error(`Map file not found: ${this.filePath}`); |
| | | 238 | | } |
| | 0 | 239 | | throw err; |
| | | 240 | | } |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | private buildOptions(): EnvilderOptions | undefined { |
| | | 244 | | const hasOverrides = |
| | 15 | 245 | | this.options.provider !== undefined || |
| | | 246 | | this.options.vaultUrl !== undefined || |
| | | 247 | | this.options.profile !== undefined; |
| | 15 | 248 | | return hasOverrides ? this.options : undefined; |
| | | 249 | | } |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | function canCheckExistence( |
| | | 253 | | provider: ISecretProvider, |
| | | 254 | | ): provider is ISecretProvider & ISecretExistenceChecker { |
| | 11 | 255 | | return ( |
| | | 256 | | typeof (provider as Partial<ISecretExistenceChecker>).checkSecretsExist === |
| | | 257 | | 'function' |
| | | 258 | | ); |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | function validateFilePath(filePath: string): void { |
| | 26 | 262 | | if (!filePath?.trim()) { |
| | 3 | 263 | | throw new Error('file path cannot be empty'); |
| | | 264 | | } |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | function resolveEnvSource( |
| | | 268 | | env: string, |
| | | 269 | | envMapping: Record<string, string | null>, |
| | | 270 | | ): string | null { |
| | 8 | 271 | | if (!env?.trim()) { |
| | 1 | 272 | | throw new Error('env cannot be empty'); |
| | | 273 | | } |
| | | 274 | | |
| | 7 | 275 | | const normalized = env.trim(); |
| | | 276 | | |
| | 7 | 277 | | if (!Object.hasOwn(envMapping, normalized)) { |
| | 2 | 278 | | return null; |
| | | 279 | | } |
| | | 280 | | |
| | 5 | 281 | | const source = envMapping[normalized]; |
| | | 282 | | |
| | 5 | 283 | | if (source === null) { |
| | 2 | 284 | | return null; |
| | | 285 | | } |
| | | 286 | | |
| | 3 | 287 | | if (!source.trim()) { |
| | 1 | 288 | | throw new Error( |
| | | 289 | | `envMapping contains an empty file path for environment '${normalized}'.`, |
| | | 290 | | ); |
| | | 291 | | } |
| | | 292 | | |
| | 2 | 293 | | return source.trim(); |
| | | 294 | | } |