| | | 1 | | import 'reflect-metadata'; |
| | | 2 | | import { existsSync } from 'node:fs'; |
| | | 3 | | import { dirname, join } from 'node:path'; |
| | | 4 | | import { fileURLToPath } from 'node:url'; |
| | | 5 | | import { Command } from 'commander'; |
| | | 6 | | import type { Container } from 'inversify'; |
| | | 7 | | import pc from 'picocolors'; |
| | | 8 | | import { DispatchActionCommand } from '../../../core/application/dispatch/DispatchActionCommand.js'; |
| | | 9 | | import type { DispatchActionCommandHandler } from '../../../core/application/dispatch/DispatchActionCommandHandler.js'; |
| | | 10 | | import type { CliOptions } from '../../../core/domain/CliOptions.js'; |
| | | 11 | | import { InvalidArgumentError } from '../../../core/domain/errors/DomainErrors.js'; |
| | | 12 | | import type { MapFileConfig } from '../../../core/domain/MapFileConfig.js'; |
| | | 13 | | import { OperationMode } from '../../../core/domain/OperationMode.js'; |
| | | 14 | | import type { ILogger } from '../../../core/domain/ports/ILogger.js'; |
| | | 15 | | import { PackageVersionReader } from '../../../core/infrastructure/package/PackageVersionReader.js'; |
| | | 16 | | import { readMapFileConfig } from '../../../core/infrastructure/variableStore/FileVariableStore.js'; |
| | | 17 | | import { TYPES } from '../../../core/types.js'; |
| | | 18 | | import { executeWithSsoRecovery } from '../recovery/SsoLoginRecovery.js'; |
| | | 19 | | import { Startup } from '../Startup.js'; |
| | | 20 | | |
| | 1 | 21 | | const DEFAULT_MAP_FILE = 'envilder.json'; |
| | 1 | 22 | | const DEFAULT_ENV_FILE = '.env'; |
| | | 23 | | |
| | | 24 | | let serviceProvider: Container; |
| | | 25 | | |
| | | 26 | | async function executeCommand(options: CliOptions): Promise<void> { |
| | 9 | 27 | | const commandHandler = serviceProvider.get<DispatchActionCommandHandler>( |
| | | 28 | | TYPES.DispatchActionCommandHandler, |
| | | 29 | | ); |
| | | 30 | | |
| | 9 | 31 | | const command = DispatchActionCommand.fromCliOptions(options); |
| | 9 | 32 | | await commandHandler.handleCommand(command); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | export async function main() { |
| | 35 | 36 | | const program = new Command(); |
| | 35 | 37 | | const version = await readPackageVersion(); |
| | | 38 | | |
| | 35 | 39 | | const banner = ` |
| | | 40 | | ${pc.green('███████╗')}${pc.cyan('███╗ ██╗')}${pc.magenta('██╗ ██╗')}${pc.yellow('██╗')}${pc.red('██╗ ')}${pc. |
| | | 41 | | ${pc.green('██╔════╝')}${pc.cyan('████╗ ██║')}${pc.magenta('██║ ██║')}${pc.yellow('██║')}${pc.red('██║ ')}${pc. |
| | | 42 | | ${pc.green('█████╗ ')}${pc.cyan('██╔██╗ ██║')}${pc.magenta('██║ ██║')}${pc.yellow('██║')}${pc.red('██║ ')}${pc. |
| | | 43 | | ${pc.green('██╔══╝ ')}${pc.cyan('██║╚██╗██║')}${pc.magenta('╚██╗ ██╔╝')}${pc.yellow('██║')}${pc.red('██║ ')}${pc. |
| | | 44 | | ${pc.green('███████╗')}${pc.cyan('██║ ╚████║')}${pc.magenta(' ╚████╔╝ ')}${pc.yellow('██║')}${pc.red('███████╗')}${pc. |
| | | 45 | | ${pc.green('╚══════╝')}${pc.cyan('╚═╝ ╚═══╝')}${pc.magenta(' ╚═══╝ ')}${pc.yellow('╚═╝')}${pc.red('╚══════╝')}${pc. |
| | | 46 | | ${pc.dim('Your secrets, one command away')} ${pc.dim('aws & azure')} |
| | | 47 | | |
| | | 48 | | ${pc.yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')} |
| | | 49 | | ${pc.green('WORLD 1-1')} ${pc.dim('— SELECT YOUR MISSION')} |
| | | 50 | | ${pc.yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')} |
| | | 51 | | |
| | | 52 | | ${pc.green('>')} ${pc.bold('Generate a .env file')} ${pc.dim('(pull secrets from the cloud)')} |
| | | 53 | | ${pc.cyan('envilder')} ${pc.dim('# uses envilder.json → .env by default')} |
| | | 54 | | |
| | | 55 | | ${pc.magenta('>')} ${pc.bold('Sync .env back to cloud')} ${pc.dim('(push secrets up)')} |
| | | 56 | | ${pc.cyan('envilder --push')} ${pc.dim('# uses envilder.json + .env by default')} |
| | | 57 | | |
| | | 58 | | ${pc.red('>')} ${pc.bold('Push a single secret')} |
| | | 59 | | ${pc.cyan('envilder --key=API_KEY --value=s3cret --secret-path=/my/path')} |
| | | 60 | | |
| | | 61 | | ${pc.blue('>')} ${pc.bold('Use Azure Key Vault')} |
| | | 62 | | ${pc.cyan('envilder --provider=azure --vault-url=https://my-vault.vault.azure.net')} |
| | | 63 | | `; |
| | | 64 | | |
| | 35 | 65 | | program |
| | | 66 | | .name('envilder') |
| | | 67 | | .description(banner) |
| | | 68 | | .version(version) |
| | | 69 | | .option( |
| | | 70 | | '--map <path>', |
| | | 71 | | `Path to the JSON file with environment variable mapping (default: ${DEFAULT_MAP_FILE})`, |
| | | 72 | | ) |
| | | 73 | | .option( |
| | | 74 | | '--envfile <path>', |
| | | 75 | | `Path to the .env file to be generated or imported (default: ${DEFAULT_ENV_FILE})`, |
| | | 76 | | ) |
| | | 77 | | .option('--profile <name>', 'AWS CLI profile to use (optional)') |
| | | 78 | | .option( |
| | | 79 | | '--provider <name>', |
| | | 80 | | 'Cloud provider to use: aws or azure (default: aws)', |
| | | 81 | | ) |
| | | 82 | | .option( |
| | | 83 | | '--vault-url <url>', |
| | | 84 | | 'Azure Key Vault URL (overrides $config.vaultUrl in map file)', |
| | | 85 | | ) |
| | | 86 | | .option('--push', 'Push a map-file-backed .env file to the cloud provider') |
| | | 87 | | .option( |
| | | 88 | | '--key <name>', |
| | | 89 | | 'Environment variable name; with --value and --secret-path, performs a single-secret push (no --push required)', |
| | | 90 | | ) |
| | | 91 | | .option( |
| | | 92 | | '--value <value>', |
| | | 93 | | 'Secret value; with --key and --secret-path, performs a single-secret push (no --push required)', |
| | | 94 | | ) |
| | | 95 | | .option( |
| | | 96 | | '--secret-path <path>', |
| | | 97 | | 'Cloud secret path; with --key and --value, performs a single-secret push (no --push required)', |
| | | 98 | | ) |
| | | 99 | | .option( |
| | | 100 | | '--ssm-path <path>', |
| | | 101 | | '[DEPRECATED: use --secret-path] Alias for --secret-path', |
| | | 102 | | ) |
| | | 103 | | .hook('preAction', (thisCommand) => { |
| | 34 | 104 | | const opts = thisCommand.opts(); |
| | | 105 | | // Alias on presence, not truthiness: an explicitly empty --ssm-path must |
| | | 106 | | // reach the single-secret guard below instead of vanishing silently. |
| | 34 | 107 | | if (opts.ssmPath !== undefined) { |
| | 4 | 108 | | console.warn( |
| | | 109 | | pc.yellow( |
| | | 110 | | '⚠️ --ssm-path is deprecated and will be removed in a future release. Use --secret-path instead.', |
| | | 111 | | ), |
| | | 112 | | ); |
| | 4 | 113 | | if (opts.secretPath === undefined) { |
| | 4 | 114 | | thisCommand.setOptionValue('secretPath', opts.ssmPath); |
| | | 115 | | } |
| | | 116 | | } |
| | | 117 | | }) |
| | | 118 | | .action( |
| | | 119 | | async ({ |
| | | 120 | | provider, |
| | | 121 | | vaultUrl, |
| | | 122 | | ...options |
| | | 123 | | }: CliOptions & { provider?: string; vaultUrl?: string }) => { |
| | 34 | 124 | | const singleSecretOptions = [ |
| | | 125 | | options.key, |
| | | 126 | | options.value, |
| | | 127 | | options.secretPath, |
| | | 128 | | ]; |
| | | 129 | | const hasPartialSingleSecretOptions = |
| | 62 | 130 | | singleSecretOptions.some((option) => option !== undefined) && |
| | 52 | 131 | | !singleSecretOptions.every((option) => Boolean(option)); |
| | 34 | 132 | | if (hasPartialSingleSecretOptions) { |
| | 22 | 133 | | throw new InvalidArgumentError( |
| | | 134 | | 'Single-secret push requires non-empty --key, --value, and --secret-path.', |
| | | 135 | | ); |
| | | 136 | | } |
| | | 137 | | |
| | 12 | 138 | | const mode = DispatchActionCommand.determineOperationMode(options); |
| | 12 | 139 | | const isPushSingle = mode === OperationMode.PUSH_SINGLE; |
| | 12 | 140 | | const resolvedMap = resolveMapFile(options.map, { |
| | | 141 | | required: !isPushSingle, |
| | | 142 | | }); |
| | 12 | 143 | | const resolvedEnvfile = resolveEnvfile(options.envfile); |
| | | 144 | | |
| | 12 | 145 | | const resolvedOptions: CliOptions = { |
| | | 146 | | ...options, |
| | | 147 | | map: resolvedMap, |
| | | 148 | | envfile: resolvedEnvfile, |
| | | 149 | | }; |
| | | 150 | | |
| | 12 | 151 | | const fileConfig = resolvedMap |
| | | 152 | | ? await readMapFileConfig(resolvedMap) |
| | | 153 | | : {}; |
| | | 154 | | |
| | 34 | 155 | | const config: MapFileConfig = { |
| | | 156 | | ...fileConfig, |
| | | 157 | | ...(provider && { provider }), |
| | | 158 | | ...(vaultUrl && { vaultUrl }), |
| | | 159 | | ...(options.profile && { profile: options.profile }), |
| | | 160 | | }; |
| | | 161 | | |
| | 34 | 162 | | const infraOptions: Record<string, unknown> = {}; |
| | 34 | 163 | | const extraHosts = process.env.ENVILDER_ALLOWED_VAULT_HOSTS; |
| | 34 | 164 | | if (extraHosts) { |
| | 1 | 165 | | infraOptions.allowedVaultHosts = extraHosts |
| | | 166 | | .split(',') |
| | 2 | 167 | | .map((h) => h.trim()); |
| | 1 | 168 | | infraOptions.disableChallengeResourceVerification = true; |
| | | 169 | | } |
| | | 170 | | |
| | 9 | 171 | | serviceProvider = Startup.build() |
| | | 172 | | .configureServices() |
| | | 173 | | .configureInfrastructure(config, infraOptions) |
| | | 174 | | .create(); |
| | | 175 | | |
| | 9 | 176 | | if (isPushSingle) { |
| | 4 | 177 | | const logger = serviceProvider.get<ILogger>(TYPES.ILogger); |
| | 4 | 178 | | const providerName = config.provider?.toLowerCase() || 'aws'; |
| | | 179 | | const vaultInfo = |
| | 4 | 180 | | providerName === 'azure' && config.vaultUrl |
| | | 181 | | ? `, vault=${new URL(config.vaultUrl).origin}` |
| | | 182 | | : ''; |
| | 4 | 183 | | const source = resolvedMap |
| | | 184 | | ? `configuration from ${resolvedMap}` |
| | | 185 | | : 'configuration'; |
| | 4 | 186 | | logger.info(`Using ${source}: provider=${providerName}${vaultInfo}`); |
| | | 187 | | } |
| | | 188 | | |
| | 9 | 189 | | await executeWithSsoRecovery(() => executeCommand(resolvedOptions)); |
| | | 190 | | }, |
| | | 191 | | ); |
| | | 192 | | |
| | 35 | 193 | | await program.parseAsync(process.argv); |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | function resolveMapFile( |
| | | 197 | | mapOption: string | undefined, |
| | | 198 | | options: { required: boolean } = { required: true }, |
| | | 199 | | ): string | undefined { |
| | 12 | 200 | | if (mapOption !== undefined) { |
| | 8 | 201 | | const trimmed = mapOption.trim(); |
| | 8 | 202 | | if (trimmed.length === 0) { |
| | 1 | 203 | | throw new InvalidArgumentError( |
| | | 204 | | 'Invalid --map value: path must not be empty.', |
| | | 205 | | ); |
| | | 206 | | } |
| | 7 | 207 | | return trimmed; |
| | | 208 | | } |
| | | 209 | | |
| | 4 | 210 | | const defaultPath = join(process.cwd(), DEFAULT_MAP_FILE); |
| | 4 | 211 | | if (existsSync(defaultPath)) { |
| | 2 | 212 | | return DEFAULT_MAP_FILE; |
| | | 213 | | } |
| | | 214 | | |
| | 2 | 215 | | if (!options.required) { |
| | 1 | 216 | | return undefined; |
| | | 217 | | } |
| | | 218 | | |
| | 1 | 219 | | throw new InvalidArgumentError( |
| | | 220 | | `No map file found. Provide --map or create ${DEFAULT_MAP_FILE} in the current directory.`, |
| | | 221 | | ); |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | function resolveEnvfile(envfileOption: string | undefined): string { |
| | 10 | 225 | | if (envfileOption === undefined) { |
| | 5 | 226 | | return DEFAULT_ENV_FILE; |
| | | 227 | | } |
| | | 228 | | |
| | 5 | 229 | | const trimmed = envfileOption.trim(); |
| | 5 | 230 | | if (trimmed.length === 0) { |
| | 1 | 231 | | throw new InvalidArgumentError( |
| | | 232 | | 'Invalid --envfile value: path must not be empty.', |
| | | 233 | | ); |
| | | 234 | | } |
| | | 235 | | |
| | 4 | 236 | | return trimmed; |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | function readPackageVersion(): Promise<string> { |
| | 35 | 240 | | const __filename = fileURLToPath(import.meta.url); |
| | 35 | 241 | | const __dirname = dirname(__filename); |
| | 35 | 242 | | const packageJsonPath = join(__dirname, '../../../../../package.json'); |
| | | 243 | | |
| | 35 | 244 | | return new PackageVersionReader().getVersion(packageJsonPath); |
| | | 245 | | } |