secrets.js (3914B)
1 import crypto from 'node:crypto'; 2 import { app } from '../app.js'; 3 import { HttpError } from './http/http-error.js'; 4 import { getSystemDatabase, openRealmDatabase } from './realm.js'; 5 6 const PREFIX = 'enc:v1:'; 7 const IV_LENGTH = 12; 8 const TAG_LENGTH = 16; 9 const KEY_LENGTH = 32; 10 11 export function parseSecretKey(raw) { 12 const value = String(raw || '').trim(); 13 if (!value) { 14 throw new Error('encryption key must not be empty'); 15 } 16 let key; 17 if (/^[0-9a-f]{64}$/i.test(value)) { 18 key = Buffer.from(value, 'hex'); 19 } else { 20 key = Buffer.from(value, 'base64'); 21 } 22 if (key.length !== KEY_LENGTH) { 23 throw new Error('encryption key must be 32 bytes (64 hex characters or base64)'); 24 } 25 return key; 26 } 27 28 function configuredSecretKey() { 29 const raw = app.config?.secrets?.encryption_key ?? process.env.AUTH_SECRETS_KEY ?? ''; 30 if (!String(raw).trim()) return null; 31 return parseSecretKey(raw); 32 } 33 34 export function hasSecretKey() { 35 return configuredSecretKey() !== null; 36 } 37 38 export function isEncrypted(value) { 39 return String(value || '').startsWith(PREFIX); 40 } 41 42 export function secretStorageUnavailable() { 43 return new HttpError( 44 503, 45 'secret_storage_unavailable', 46 'A secrets encryption key must be configured to store client secrets' 47 ); 48 } 49 50 function secretAad(realmId, providerId) { 51 return Buffer.from(`${realmId}:${providerId}:identity-provider-secret`, 'utf8'); 52 } 53 54 export function encryptSecret(plaintext, { realmId, providerId }) { 55 const key = configuredSecretKey(); 56 if (!key) { 57 throw secretStorageUnavailable(); 58 } 59 const iv = crypto.randomBytes(IV_LENGTH); 60 const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); 61 cipher.setAAD(secretAad(realmId, providerId)); 62 const ciphertext = Buffer.concat([ 63 cipher.update(String(plaintext), 'utf8'), 64 cipher.final(), 65 ]); 66 const packed = Buffer.concat([iv, cipher.getAuthTag(), ciphertext]); 67 return `${PREFIX}${packed.toString('base64url')}`; 68 } 69 70 export function decryptSecret(stored, { realmId, providerId }) { 71 const value = stored === null || stored === undefined ? '' : String(stored); 72 if (!value) return null; 73 if (!isEncrypted(value)) return value; 74 75 const fail = () => 76 new HttpError(500, 'secret_decrypt_failed', 'The stored client secret could not be decrypted'); 77 const key = configuredSecretKey(); 78 if (!key) { 79 throw fail(); 80 } 81 try { 82 const packed = Buffer.from(value.slice(PREFIX.length), 'base64url'); 83 const iv = packed.subarray(0, IV_LENGTH); 84 const tag = packed.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH); 85 const ciphertext = packed.subarray(IV_LENGTH + TAG_LENGTH); 86 if (!iv.length || tag.length !== TAG_LENGTH || !ciphertext.length) { 87 throw new Error('malformed envelope'); 88 } 89 const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); 90 decipher.setAAD(secretAad(realmId, providerId)); 91 decipher.setAuthTag(tag); 92 return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); 93 } catch { 94 throw fail(); 95 } 96 } 97 98 export async function migrateProviderSecrets() { 99 const key = configuredSecretKey(); 100 if (!key) return 0; 101 102 const systemDb = getSystemDatabase(); 103 const realms = await systemDb.all('SELECT id, slug, db_file FROM realms ORDER BY slug ASC'); 104 let migrated = 0; 105 106 for (const realm of realms) { 107 const db = await openRealmDatabase(realm); 108 const rows = await db.all( 109 `SELECT id, client_secret FROM identity_providers 110 WHERE client_secret IS NOT NULL AND client_secret <> ''` 111 ); 112 for (const row of rows) { 113 if (isEncrypted(row.client_secret)) continue; 114 await db.run( 115 'UPDATE identity_providers SET client_secret = {value} WHERE id = {id}', 116 { 117 value: encryptSecret(row.client_secret, { realmId: realm.id, providerId: row.id }), 118 id: row.id, 119 } 120 ); 121 migrated += 1; 122 } 123 } 124 125 return migrated; 126 }