| | | 1 | | import * as fs from 'node:fs/promises'; |
| | | 2 | | import * as dotenv from 'dotenv'; |
| | | 3 | | import { inject, injectable } from 'inversify'; |
| | | 4 | | import { |
| | | 5 | | DependencyMissingError, |
| | | 6 | | EnvironmentFileError, |
| | | 7 | | } from '../../domain/errors/DomainErrors.js'; |
| | | 8 | | import type { |
| | | 9 | | MapFileConfig, |
| | | 10 | | ParsedMapFile, |
| | | 11 | | } from '../../domain/MapFileConfig.js'; |
| | | 12 | | import type { ILogger } from '../../domain/ports/ILogger.js'; |
| | | 13 | | import type { IVariableStore } from '../../domain/ports/IVariableStore.js'; |
| | | 14 | | import { TYPES } from '../../types.js'; |
| | | 15 | | |
| | | 16 | | @injectable() |
| | 8 | 17 | | export class FileVariableStore implements IVariableStore { |
| | | 18 | | private logger: ILogger; |
| | | 19 | | |
| | | 20 | | constructor(@inject(TYPES.ILogger) logger: ILogger) { |
| | 59 | 21 | | if (!logger) { |
| | 1 | 22 | | throw new DependencyMissingError('Logger must be specified'); |
| | | 23 | | } |
| | 58 | 24 | | this.logger = logger; |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | async getMapping(source: string): Promise<Record<string, string>> { |
| | 9 | 28 | | const { mappings } = await this.getParsedMapping(source); |
| | 6 | 29 | | return mappings; |
| | | 30 | | } |
| | | 31 | | |
| | | 32 | | async getParsedMapping(source: string): Promise<ParsedMapFile> { |
| | 14 | 33 | | const raw = await this.readJsonFile(source); |
| | 11 | 34 | | const { $config, ...rest } = raw; |
| | | 35 | | const config: MapFileConfig = |
| | 11 | 36 | | $config && typeof $config === 'object' ? $config : {}; |
| | 14 | 37 | | const mappings: Record<string, string> = {}; |
| | 14 | 38 | | for (const [key, value] of Object.entries(rest)) { |
| | 21 | 39 | | if (!key.startsWith('$') && typeof value === 'string') { |
| | 16 | 40 | | mappings[key] = value; |
| | | 41 | | } |
| | | 42 | | } |
| | 11 | 43 | | return { config, mappings }; |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | private async readJsonFile(source: string): Promise<Record<string, unknown>> { |
| | 14 | 47 | | try { |
| | 14 | 48 | | const content = await fs.readFile(source, 'utf-8'); |
| | 12 | 49 | | try { |
| | 12 | 50 | | return JSON.parse(content); |
| | | 51 | | } catch (_err: unknown) { |
| | 1 | 52 | | this.logger.error(`Error parsing JSON from ${source}`); |
| | 1 | 53 | | throw new EnvironmentFileError( |
| | | 54 | | `Invalid JSON in parameter map file: ${source}`, |
| | | 55 | | ); |
| | | 56 | | } |
| | | 57 | | } catch (error) { |
| | 3 | 58 | | if (error instanceof EnvironmentFileError) { |
| | 1 | 59 | | throw error; |
| | | 60 | | } |
| | 2 | 61 | | throw new EnvironmentFileError(`Failed to read map file: ${source}`); |
| | | 62 | | } |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | async getEnvironment(source: string): Promise<Record<string, string>> { |
| | 8 | 66 | | const envVariables: Record<string, string> = {}; |
| | 8 | 67 | | try { |
| | 8 | 68 | | await fs.access(source); |
| | | 69 | | } catch { |
| | 4 | 70 | | return envVariables; |
| | | 71 | | } |
| | 4 | 72 | | const existingEnvContent = await fs.readFile(source, 'utf-8'); |
| | 2 | 73 | | const parsedEnv = dotenv.parse(existingEnvContent) || {}; |
| | 8 | 74 | | Object.assign(envVariables, parsedEnv); |
| | | 75 | | |
| | 8 | 76 | | return envVariables; |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | async saveEnvironment( |
| | | 80 | | destination: string, |
| | | 81 | | envVariables: Record<string, string>, |
| | | 82 | | ): Promise<void> { |
| | 21 | 83 | | const existingContent = await this.readExistingEnvContent(destination); |
| | 20 | 84 | | const envContent = this.buildEnvContent(existingContent, envVariables); |
| | | 85 | | |
| | 20 | 86 | | try { |
| | 20 | 87 | | await fs.writeFile(destination, envContent); |
| | | 88 | | } catch (error) { |
| | | 89 | | const errorMessage = |
| | 2 | 90 | | error instanceof Error ? error.message : String(error); |
| | 2 | 91 | | this.logger.error(`Failed to write environment file: ${errorMessage}`); |
| | 2 | 92 | | throw new EnvironmentFileError( |
| | | 93 | | `Failed to write environment file: ${errorMessage}`, |
| | | 94 | | ); |
| | | 95 | | } |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | private async readExistingEnvContent( |
| | | 99 | | destination: string, |
| | | 100 | | ): Promise<string | null> { |
| | 21 | 101 | | try { |
| | 21 | 102 | | return await fs.readFile(destination, 'utf-8'); |
| | | 103 | | } catch (error) { |
| | 11 | 104 | | if ( |
| | | 105 | | error instanceof Error && |
| | | 106 | | (error as NodeJS.ErrnoException).code === 'ENOENT' |
| | | 107 | | ) { |
| | 10 | 108 | | return null; |
| | | 109 | | } |
| | 1 | 110 | | const message = error instanceof Error ? error.message : String(error); |
| | 11 | 111 | | this.logger.error(`Failed to read environment file: ${message}`); |
| | 11 | 112 | | throw new EnvironmentFileError( |
| | | 113 | | `Failed to read environment file: ${message}`, |
| | | 114 | | ); |
| | | 115 | | } |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | private buildEnvContent( |
| | | 119 | | existingContent: string | null, |
| | | 120 | | envVariables: Record<string, string>, |
| | | 121 | | ): string { |
| | 20 | 122 | | const pending = { ...envVariables }; |
| | | 123 | | |
| | 20 | 124 | | if (existingContent === null) { |
| | 10 | 125 | | return Object.entries(pending) |
| | 10 | 126 | | .map(([key, value]) => `${key}=${this.escapeEnvValue(value)}`) |
| | | 127 | | .join('\n'); |
| | | 128 | | } |
| | | 129 | | |
| | 10 | 130 | | const newline = existingContent.includes('\r\n') ? '\r\n' : '\n'; |
| | 20 | 131 | | const hasTrailingNewline = /\r?\n$/.test(existingContent); |
| | 20 | 132 | | const lines = existingContent === '' ? [] : existingContent.split(/\r?\n/); |
| | 20 | 133 | | if (hasTrailingNewline) { |
| | 1 | 134 | | lines.pop(); |
| | | 135 | | } |
| | | 136 | | |
| | 10 | 137 | | const assignmentRegex = /^(\s*(?:export\s+)?)([\w.-]+)(\s*=\s*)(.*)$/; |
| | 10 | 138 | | const updatedKeys = new Set<string>(); |
| | 10 | 139 | | const mergedLines = lines.map((line) => { |
| | 19 | 140 | | const match = assignmentRegex.exec(line); |
| | 19 | 141 | | if (match === null) { |
| | 7 | 142 | | return line; |
| | | 143 | | } |
| | 12 | 144 | | const [, prefix, key, separator, originalValue] = match; |
| | 12 | 145 | | if (!Object.hasOwn(pending, key)) { |
| | 0 | 146 | | return line; |
| | | 147 | | } |
| | 12 | 148 | | updatedKeys.add(key); |
| | 12 | 149 | | const value = this.formatValue(pending[key], originalValue); |
| | 12 | 150 | | return `${prefix}${key}${separator}${value}`; |
| | | 151 | | }); |
| | 10 | 152 | | for (const key of updatedKeys) { |
| | 11 | 153 | | delete pending[key]; |
| | | 154 | | } |
| | | 155 | | |
| | 10 | 156 | | const appended = Object.entries(pending).map( |
| | 3 | 157 | | ([key, value]) => `${key}=${this.escapeEnvValue(value)}`, |
| | | 158 | | ); |
| | | 159 | | const allLines = |
| | 10 | 160 | | appended.length > 0 ? [...mergedLines, ...appended] : mergedLines; |
| | 20 | 161 | | const result = allLines.join(newline); |
| | 20 | 162 | | return hasTrailingNewline ? result + newline : result; |
| | | 163 | | } |
| | | 164 | | |
| | | 165 | | private formatValue(newValue: string, originalValue: string): string { |
| | 12 | 166 | | const trimmed = originalValue.trim(); |
| | 12 | 167 | | const quote = trimmed[0]; |
| | | 168 | | const isQuoted = |
| | 12 | 169 | | trimmed.length >= 2 && |
| | | 170 | | (quote === '"' || quote === "'") && |
| | | 171 | | trimmed[trimmed.length - 1] === quote; |
| | | 172 | | // Only keep the original quotes when the new value can be wrapped safely. |
| | | 173 | | // A value containing the same quote, a backslash, or a newline would |
| | | 174 | | // produce a string dotenv cannot parse back, so fall back to the |
| | | 175 | | // unquoted escaped form instead of corrupting the value. |
| | | 176 | | const isSafeToWrap = |
| | 12 | 177 | | !newValue.includes(quote) && |
| | | 178 | | !newValue.includes('\\') && |
| | | 179 | | !/[\r\n]/.test(newValue); |
| | 12 | 180 | | if (isQuoted && isSafeToWrap) { |
| | 2 | 181 | | return `${quote}${newValue}${quote}`; |
| | | 182 | | } |
| | 10 | 183 | | return this.escapeEnvValue(newValue); |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | private escapeEnvValue(value: string): string { |
| | | 187 | | // codeql[js/incomplete-sanitization] |
| | | 188 | | // CodeQL flags this as incomplete sanitization because we don't escape backslashes |
| | | 189 | | // before newlines. However, this is intentional: the dotenv library does NOT |
| | | 190 | | // interpret escape sequences (it treats \n literally as backslash+n, not as a newline). |
| | | 191 | | // Therefore, escaping backslashes would actually break the functionality by |
| | | 192 | | // doubling them when read back by dotenv. This is not a security issue in this context. |
| | 23 | 193 | | return value.replace(/(\r\n|\n|\r)/g, '\\n'); |
| | | 194 | | } |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | export async function readMapFileConfig( |
| | | 198 | | mapPath: string, |
| | | 199 | | ): Promise<MapFileConfig> { |
| | 4 | 200 | | try { |
| | 4 | 201 | | const content = await fs.readFile(mapPath, 'utf-8'); |
| | 3 | 202 | | try { |
| | 3 | 203 | | const raw = JSON.parse(content); |
| | 3 | 204 | | const config = raw.$config; |
| | 3 | 205 | | return config && typeof config === 'object' ? config : {}; |
| | | 206 | | } catch { |
| | 1 | 207 | | throw new EnvironmentFileError( |
| | | 208 | | `Invalid JSON in parameter map file: ${mapPath}`, |
| | | 209 | | ); |
| | | 210 | | } |
| | | 211 | | } catch (error) { |
| | 2 | 212 | | if (error instanceof EnvironmentFileError) { |
| | 1 | 213 | | throw error; |
| | | 214 | | } |
| | 1 | 215 | | throw new EnvironmentFileError(`Failed to read map file: ${mapPath}`); |
| | | 216 | | } |
| | | 217 | | } |