Fails fast if the AES-GCM round-trip disagrees with itself in this env.
(apiEncryptionKey: string | null)
| 205 | |
| 206 | /** Fails fast if the AES-GCM round-trip disagrees with itself in this env. */ |
| 207 | function assertCryptoRoundTrip(apiEncryptionKey: string | null): void { |
| 208 | if (!apiEncryptionKey) return |
| 209 | const key = Buffer.from(apiEncryptionKey, 'hex') |
| 210 | const sample = 'sk-sim-roundtrip-test-value' |
| 211 | const iv = Buffer.from('00'.repeat(16), 'hex') |
| 212 | const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: 16 }) |
| 213 | let encrypted = cipher.update(sample, 'utf8', 'hex') |
| 214 | encrypted += cipher.final('hex') |
| 215 | const authTag = cipher.getAuthTag() |
| 216 | const assembled = `${iv.toString('hex')}:${encrypted}:${authTag.toString('hex')}` |
| 217 | const roundTripped = decryptApiKey(assembled, apiEncryptionKey) |
| 218 | if (roundTripped !== sample) { |
| 219 | throw new Error('Crypto self-test failed — refusing to run backfill') |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | if ((import.meta as { main?: boolean }).main) { |
| 224 | try { |
no test coverage detected