< Summary - Envilder Node.js SDK

Information
Class: src/sdks/nodejs/src/application/envilder.ts
Assembly: Default
File(s): src/sdks/nodejs/src/application/envilder.ts
Tag: 605_44106794472
Line coverage
98%
Covered lines: 75
Uncovered lines: 1
Coverable lines: 76
Total lines: 294
Line coverage: 98.6%
Branch coverage
97%
Covered branches: 45
Total branches: 46
Branch coverage: 97.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

File(s)

src/sdks/nodejs/src/application/envilder.ts

#LineLine coverage
 1import { readFile } from 'node:fs/promises';
 2import type { ContractValidationResult } from '../domain/contract-validation-result.js';
 3import type { EnvilderOptions } from '../domain/envilder-options.js';
 4import type { ParsedMapFile } from '../domain/parsed-map-file.js';
 5import type { ISecretExistenceChecker } from '../domain/ports/secret-existence-checker.js';
 6import type { ISecretProvider } from '../domain/ports/secret-provider.js';
 7import { SecretProviderType } from '../domain/secret-provider-type.js';
 8import { createSecretProvider } from '../infrastructure/secret-provider-factory.js';
 9import {
 10  ContractValidationError,
 11  checkRemoteKeys,
 12  invalidMapFileResult,
 13  notCheckableResult,
 14} from './contract-validation.js';
 15import { EnvilderClient } from './envilder-client.js';
 16import { MapFileParser } from './map-file-parser.js';
 17import { 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 */
 53export class Envilder {
 54  private readonly filePath: string;
 2555  private options: EnvilderOptions = {};
 2556  private contractValidation = false;
 57  private secretProvider?: ISecretProvider;
 58
 59  private constructor(filePath: string) {
 2560    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 {
 2270    validateFilePath(filePath);
 2271    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>> {
 885    if (envMapping !== undefined) {
 586      const source = resolveEnvSource(filePathOrEnv, envMapping);
 587      if (source === null) {
 288        return new Map();
 89      }
 190      return new Envilder(source).inject();
 91    }
 92
 393    validateFilePath(filePathOrEnv);
 394    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>> {
 4108    if (envMapping !== undefined) {
 3109      const source = resolveEnvSource(filePathOrEnv, envMapping);
 3110      if (source === null) {
 2111        return new Map();
 112      }
 1113      return new Envilder(source).resolve();
 114    }
 115
 1116    validateFilePath(filePathOrEnv);
 1117    return new Envilder(filePathOrEnv.trim()).resolve();
 118  }
 119
 120  /** Override the secret provider (AWS or Azure). */
 121  withProvider(provider: SecretProviderType): Envilder {
 2122    this.options.provider = provider;
 2123    return this;
 124  }
 125
 126  /** Override the Azure Key Vault URL. */
 127  withVaultUrl(vaultUrl: string): Envilder {
 2128    this.options.vaultUrl = vaultUrl;
 2129    return this;
 130  }
 131
 132  /** Override the AWS named profile. */
 133  withProfile(profile: string): Envilder {
 1134    this.options.profile = profile;
 1135    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 {
 7147    if (!provider) {
 1148      throw new Error('provider cannot be null or undefined');
 149    }
 6150    this.secretProvider = provider;
 6151    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 {
 5160    this.contractValidation = true;
 5161    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> {
 10173    const { result } = await this.checkContract(await this.readMapFile());
 9174    return result;
 175  }
 176
 177  /** Resolve secrets and return them as a Map. */
 178  async resolve(): Promise<Map<string, string>> {
 14179    const json = await this.readMapFile();
 14180    if (this.contractValidation) {
 5181      const { result, mapFile, provider } = await this.checkContract(json);
 5182      if (!result.isValid || mapFile === undefined || provider === undefined) {
 3183        throw new ContractValidationError(result);
 184      }
 2185      return new EnvilderClient(provider).resolveSecrets(mapFile);
 186    }
 9187    const mapFile = new MapFileParser().parse(json);
 9188    const provider = this.createProvider(mapFile);
 9189    const client = new EnvilderClient(provider);
 9190    return client.resolveSecrets(mapFile);
 191  }
 192
 193  /** Resolve secrets, inject into `process.env`, and return them. */
 194  async inject(): Promise<Map<string, string>> {
 7195    const secrets = await this.resolve();
 5196    EnvilderClient.injectIntoEnvironment(secrets);
 5197    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  }> {
 14209    const mapFileErrors = validateMapFileContent(json, this.options);
 14210    if (mapFileErrors.length > 0) {
 3211      return { result: invalidMapFileResult(mapFileErrors) };
 212    }
 11213    const mapFile = new MapFileParser().parse(json);
 11214    const provider = this.createProvider(mapFile);
 215    const providerType =
 11216      this.options.provider ??
 217      mapFile.config.provider ??
 218      SecretProviderType.Aws;
 14219    const result = canCheckExistence(provider)
 220      ? await checkRemoteKeys(mapFile, provider, providerType)
 221      : notCheckableResult(mapFile, providerType);
 14222    return { result, mapFile, provider };
 223  }
 224
 225  private createProvider(mapFile: ParsedMapFile): ISecretProvider {
 20226    return (
 227      this.secretProvider ??
 228      createSecretProvider(mapFile.config, this.buildOptions())
 229    );
 230  }
 231
 232  private async readMapFile(): Promise<string> {
 24233    try {
 24234      return await readFile(this.filePath, 'utf-8');
 235    } catch (err: unknown) {
 1236      if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {
 1237        throw new Error(`Map file not found: ${this.filePath}`);
 238      }
 0239      throw err;
 240    }
 241  }
 242
 243  private buildOptions(): EnvilderOptions | undefined {
 244    const hasOverrides =
 15245      this.options.provider !== undefined ||
 246      this.options.vaultUrl !== undefined ||
 247      this.options.profile !== undefined;
 15248    return hasOverrides ? this.options : undefined;
 249  }
 250}
 251
 252function canCheckExistence(
 253  provider: ISecretProvider,
 254): provider is ISecretProvider & ISecretExistenceChecker {
 11255  return (
 256    typeof (provider as Partial<ISecretExistenceChecker>).checkSecretsExist ===
 257    'function'
 258  );
 259}
 260
 261function validateFilePath(filePath: string): void {
 26262  if (!filePath?.trim()) {
 3263    throw new Error('file path cannot be empty');
 264  }
 265}
 266
 267function resolveEnvSource(
 268  env: string,
 269  envMapping: Record<string, string | null>,
 270): string | null {
 8271  if (!env?.trim()) {
 1272    throw new Error('env cannot be empty');
 273  }
 274
 7275  const normalized = env.trim();
 276
 7277  if (!Object.hasOwn(envMapping, normalized)) {
 2278    return null;
 279  }
 280
 5281  const source = envMapping[normalized];
 282
 5283  if (source === null) {
 2284    return null;
 285  }
 286
 3287  if (!source.trim()) {
 1288    throw new Error(
 289      `envMapping contains an empty file path for environment '${normalized}'.`,
 290    );
 291  }
 292
 2293  return source.trim();
 294}