|
| 1 | +import { type EnvObject, EnvTarget } from './types'; |
| 2 | +import { base64ToUint8Array, uint8ArrayToBase64 } from './utils'; |
| 3 | + |
| 4 | +const PBKDF2_ROUNDS = process.env.GITOPS_SECRETS_PBKDF2_ROUNDS || 1000000; |
| 5 | +const PBKDF2_KEYLEN = 32; |
| 6 | +const PBKDF2_DIGEST = 'SHA-256'; |
| 7 | +const ALGORITHM = 'AES-GCM'; |
| 8 | +const AES_IV_BYTES = 12; |
| 9 | +const AES_SALT_BYTES = 8; |
| 10 | +const ENCODING = 'base64'; |
| 11 | +const TEXT_ENCODING = 'utf8'; |
| 12 | + |
| 13 | +function masterKey() { |
| 14 | + if (!process.env.GITOPS_SECRETS_MASTER_KEY || process.env.GITOPS_SECRETS_MASTER_KEY.length < 16) { |
| 15 | + throw new Error( |
| 16 | + `The 'GITOPS_SECRETS_MASTER_KEY' environment variable must be set to a string of 16 characters or more`, |
| 17 | + ); |
| 18 | + } |
| 19 | + |
| 20 | + return process.env.GITOPS_SECRETS_MASTER_KEY; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Derive encryption key using the Web Crypto API's PBKDF2 |
| 25 | + * |
| 26 | + * @param {string} masterKeyString - The master key string |
| 27 | + * @param {Uint8Array} salt - The salt for key derivation |
| 28 | + * @param {number} iterations - The number of iterations for key derivation |
| 29 | + * @returns {Promise<CryptoKey>} - The derived key |
| 30 | + */ |
| 31 | +async function deriveKey( |
| 32 | + masterKeyString: string, |
| 33 | + salt: Uint8Array, |
| 34 | + iterations: number = Number(PBKDF2_ROUNDS), |
| 35 | +): Promise<CryptoKey> { |
| 36 | + const masterKeyBuffer = new TextEncoder().encode(masterKeyString); |
| 37 | + const importedKey = await crypto.subtle.importKey('raw', masterKeyBuffer, { name: 'PBKDF2' }, false, ['deriveKey']); |
| 38 | + |
| 39 | + return crypto.subtle.deriveKey( |
| 40 | + { |
| 41 | + name: 'PBKDF2', |
| 42 | + salt: salt, |
| 43 | + iterations: iterations, |
| 44 | + hash: PBKDF2_DIGEST, |
| 45 | + }, |
| 46 | + importedKey, |
| 47 | + { name: ALGORITHM, length: PBKDF2_KEYLEN * 8 }, |
| 48 | + false, |
| 49 | + ['encrypt', 'decrypt'], |
| 50 | + ); |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Encrypt secrets to a secure format |
| 55 | + * |
| 56 | + * @param {string} secrets - The data to encrypt |
| 57 | + * @returns {Promise<string>} - Encrypted data in format "base64:rounds:salt:iv:encryptedData" |
| 58 | + */ |
| 59 | +async function encrypt(secrets: string): Promise<string> { |
| 60 | + const salt = crypto.getRandomValues(new Uint8Array(AES_SALT_BYTES)); |
| 61 | + const iv = crypto.getRandomValues(new Uint8Array(AES_IV_BYTES)); |
| 62 | + const key = await deriveKey(masterKey(), salt); |
| 63 | + |
| 64 | + const dataBuffer = new TextEncoder().encode(secrets); |
| 65 | + const encryptedBuffer = await crypto.subtle.encrypt( |
| 66 | + { |
| 67 | + name: ALGORITHM, |
| 68 | + iv: iv, |
| 69 | + }, |
| 70 | + key, |
| 71 | + dataBuffer, |
| 72 | + ); |
| 73 | + |
| 74 | + const saltBase64 = uint8ArrayToBase64(salt); |
| 75 | + const ivBase64 = uint8ArrayToBase64(iv); |
| 76 | + const encryptedBase64 = uint8ArrayToBase64(new Uint8Array(encryptedBuffer)); |
| 77 | + |
| 78 | + return `${ENCODING}:${PBKDF2_ROUNDS}:${saltBase64}:${ivBase64}:${encryptedBase64}`; |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Decrypt secrets from secure format |
| 83 | + * |
| 84 | + * @param {string} ciphertext - Data in format "base64:rounds:salt:iv:encryptedData" |
| 85 | + * @returns {Promise<string>} - Decrypted data |
| 86 | + */ |
| 87 | +async function decrypt(ciphertext: string): Promise<string> { |
| 88 | + const encodedData = ciphertext.startsWith(`${ENCODING}:`) ? ciphertext.substring(`${ENCODING}:`.length) : ciphertext; |
| 89 | + |
| 90 | + const parts = encodedData.split(':'); |
| 91 | + if (parts.length !== 4) { |
| 92 | + throw new Error(`Encrypted payload invalid. Expected 4 sections but got ${parts.length}`); |
| 93 | + } |
| 94 | + |
| 95 | + const rounds = Number.parseInt(parts[0], 10); |
| 96 | + const salt = base64ToUint8Array(parts[1]); |
| 97 | + const iv = base64ToUint8Array(parts[2]); |
| 98 | + const encryptedContent = base64ToUint8Array(parts[3]); |
| 99 | + |
| 100 | + try { |
| 101 | + const key = await deriveKey(masterKey(), salt, rounds); |
| 102 | + |
| 103 | + const decryptedBuffer = await crypto.subtle.decrypt( |
| 104 | + { |
| 105 | + name: ALGORITHM, |
| 106 | + iv: iv, |
| 107 | + }, |
| 108 | + key, |
| 109 | + encryptedContent, |
| 110 | + ); |
| 111 | + |
| 112 | + const decrypted = new TextDecoder(TEXT_ENCODING).decode(decryptedBuffer); |
| 113 | + return decrypted; |
| 114 | + } catch (error) { |
| 115 | + throw new Error(`Decryption failed: ${error instanceof Error ? error.message : String(error)}`); |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +/** |
| 120 | + * Get the appropriate environment object based on the target |
| 121 | + * |
| 122 | + * @param {EnvTarget} target - The environment target |
| 123 | + * @returns {EnvObject} - The environment object |
| 124 | + */ |
| 125 | +function getEnvObject(target: EnvTarget): EnvObject { |
| 126 | + switch (target) { |
| 127 | + case EnvTarget.PROCESS: |
| 128 | + if (typeof process !== 'undefined' && process.env) { |
| 129 | + return process.env; |
| 130 | + } |
| 131 | + throw new Error('process.env is not available in this environment'); |
| 132 | + case EnvTarget.IMPORT_META: |
| 133 | + if (typeof import.meta !== 'undefined' && import.meta.env) { |
| 134 | + return import.meta.env; |
| 135 | + } |
| 136 | + throw new Error('import.meta.env is not available in this environment'); |
| 137 | + |
| 138 | + default: |
| 139 | + throw new Error(`Unsupported environment target: ${target}`); |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +/** |
| 144 | + * Merge secrets payload into the specified environment |
| 145 | + * |
| 146 | + * @param {Record<string, string>} payload - The payload object containing secrets |
| 147 | + * @param {EnvTarget} target - The environment target to merge secrets into |
| 148 | + * @returns {EnvObject} - The environment object with merged secrets |
| 149 | + */ |
| 150 | +function mergeSecrets(payload: Record<string, string>, target: EnvTarget): EnvObject { |
| 151 | + const envObject = getEnvObject(target); |
| 152 | + |
| 153 | + for (const [key, value] of Object.entries(payload)) { |
| 154 | + if (target === EnvTarget.PROCESS && typeof process !== 'undefined') { |
| 155 | + process.env[key] = value; |
| 156 | + } else if (target === EnvTarget.IMPORT_META) { |
| 157 | + import.meta.env[key] = value; |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return envObject; |
| 162 | +} |
| 163 | + |
| 164 | +/** |
| 165 | + * Load encrypted secrets, decrypt them, and merge into the specified environment |
| 166 | + * |
| 167 | + * @param {string} encryptedSecrets - The encrypted secrets string |
| 168 | + * @param {EnvTarget} target - The environment target to merge with |
| 169 | + * @returns {Promise<EnvObject>} - The environment with merged secrets |
| 170 | + */ |
| 171 | +async function loadSecrets(encryptedSecrets: string, target: EnvTarget = EnvTarget.PROCESS): Promise<EnvObject> { |
| 172 | + try { |
| 173 | + const decryptedJson = await decrypt(encryptedSecrets); |
| 174 | + const secretsPayload = JSON.parse(decryptedJson) as Record<string, string>; |
| 175 | + |
| 176 | + return mergeSecrets(secretsPayload, target); |
| 177 | + } catch (error) { |
| 178 | + console.error('Failed to load secrets:', error); |
| 179 | + return getEnvObject(target); |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +export { encrypt, decrypt, mergeSecrets, loadSecrets }; |
0 commit comments