config.js (5102B)
1 // src/lib/config.js - configuration loading for the auth server 2 // 3 // Resolution order, lowest precedence first: 4 // 1. built-in defaults (see DEFAULTS) 5 // 2. YAML file, from ./auth.yaml when present 6 // 3. environment variables (see ENV_MAP) 7 8 import fs from 'node:fs'; 9 import YAML from 'yaml'; 10 import { parseSecretKey } from './secrets.js'; 11 12 const SUPPORTED_DIALECTS = ['sqlite']; 13 14 const DEFAULTS = { 15 server: { 16 host: '0.0.0.0', 17 port: 3000, 18 public_url: 'http://localhost:3000', 19 }, 20 database: { 21 dialect: 'sqlite', 22 path: './data/system.sqlite', 23 realms: './data/realms', 24 }, 25 apps: { 26 admin: null, 27 account: null, 28 }, 29 secrets: { 30 encryption_key: null, 31 }, 32 }; 33 34 // [environment variable, dotted config path, parser] 35 const ENV_MAP = [ 36 ['AUTH_HOST', 'server.host', String], 37 ['AUTH_PORT', 'server.port', toInt], 38 ['AUTH_PUBLIC_URL', 'server.public_url', String], 39 ['AUTH_DATABASE_DIALECT', 'database.dialect', lower], 40 ['AUTH_DATABASE_PATH', 'database.path', String], 41 ['AUTH_REALMS_PATH', 'database.realms', String], 42 ['AUTH_ADMIN_APP_URL', 'apps.admin', String], 43 ['AUTH_ACCOUNT_APP_URL', 'apps.account', String], 44 ['AUTH_SECRETS_KEY', 'secrets.encryption_key', String], 45 ]; 46 47 function lower(v) { 48 return String(v).trim().toLowerCase(); 49 } 50 51 function toInt(v) { 52 const n = parseInt(v, 10); 53 if (!Number.isFinite(n)) throw new Error(`expected an integer, got ${JSON.stringify(v)}`); 54 return n; 55 } 56 57 function isPlainObject(v) { 58 return v !== null && typeof v === 'object' && !Array.isArray(v); 59 } 60 61 function deepMerge(base, overlay) { 62 const out = Array.isArray(base) ? [...base] : { ...base }; 63 for (const [k, v] of Object.entries(overlay || {})) { 64 if (v === undefined) continue; 65 out[k] = isPlainObject(v) && isPlainObject(base?.[k]) ? deepMerge(base[k], v) : v; 66 } 67 return out; 68 } 69 70 function setPath(obj, dotted, value) { 71 const keys = dotted.split('.'); 72 const last = keys.pop(); 73 let cur = obj; 74 for (const k of keys) { 75 if (!isPlainObject(cur[k])) cur[k] = {}; 76 cur = cur[k]; 77 } 78 cur[last] = value; 79 } 80 81 function deepFreeze(obj) { 82 for (const v of Object.values(obj)) { 83 if (isPlainObject(v) || Array.isArray(v)) deepFreeze(v); 84 } 85 return Object.freeze(obj); 86 } 87 88 function validate(cfg) { 89 const errors = []; 90 91 const port = cfg.server.port; 92 if (!Number.isInteger(port) || port < 0 || port > 65535) { 93 errors.push(`server.port must be between 0 and 65535, got ${port}`); 94 } 95 96 try { 97 const publicUrl = new URL(cfg.server.public_url); 98 if (publicUrl.protocol !== 'http:' && publicUrl.protocol !== 'https:') { 99 errors.push('server.public_url must use http or https'); 100 } 101 } catch { 102 errors.push('server.public_url must be an absolute URL'); 103 } 104 105 if (!SUPPORTED_DIALECTS.includes(cfg.database.dialect)) { 106 errors.push( 107 `database.dialect must be one of ${SUPPORTED_DIALECTS.join(', ')}, got ${JSON.stringify(cfg.database.dialect)}` 108 ); 109 } 110 111 if (cfg.database.dialect === 'sqlite') { 112 if (!cfg.database.path) { 113 errors.push('database.path is required for sqlite (set database.path or AUTH_DATABASE_PATH)'); 114 } 115 if (!cfg.database.realms) { 116 errors.push('database.realms is required for sqlite (set database.realms or AUTH_REALMS_PATH)'); 117 } 118 } 119 120 const encryptionKey = cfg.secrets?.encryption_key; 121 if (encryptionKey) { 122 try { 123 parseSecretKey(encryptionKey); 124 } catch (e) { 125 errors.push(`secrets.encryption_key ${e.message}`); 126 } 127 } 128 129 for (const [name, value] of Object.entries(cfg.apps || {})) { 130 if (!value) continue; 131 try { 132 const url = new URL(value); 133 if (url.protocol !== 'http:' && url.protocol !== 'https:') { 134 errors.push(`apps.${name} must use http or https`); 135 } 136 if (url.pathname !== '/' || url.search || url.hash) { 137 errors.push(`apps.${name} must be an origin without a path`); 138 } 139 } catch { 140 errors.push(`apps.${name} must be an absolute URL`); 141 } 142 } 143 144 if (errors.length > 0) { 145 throw new Error(`invalid configuration:\n - ${errors.join('\n - ')}`); 146 } 147 } 148 149 export function loadConfig(explicitPath) { 150 const file = explicitPath || 'auth.yaml'; 151 let cfg = structuredClone(DEFAULTS); 152 let source = null; 153 154 if (fs.existsSync(file)) { 155 const text = fs.readFileSync(file, 'utf8'); 156 let parsed; 157 try { 158 parsed = YAML.parse(text) || {}; 159 } catch (e) { 160 throw new Error(`failed to parse config file ${file}: ${e.message}`); 161 } 162 if (!isPlainObject(parsed)) { 163 throw new Error(`config file ${file} must contain a YAML mapping at the top level`); 164 } 165 cfg = deepMerge(cfg, parsed); 166 source = file; 167 } else if (explicitPath) { 168 throw new Error(`config file not found: ${file}`); 169 } 170 171 for (const [env, dotted, parse] of ENV_MAP) { 172 const raw = process.env[env]; 173 if (raw === undefined || raw === '') continue; 174 try { 175 setPath(cfg, dotted, parse(raw)); 176 } catch (e) { 177 throw new Error(`invalid value for ${env}: ${e.message}`); 178 } 179 } 180 181 cfg.source = source; 182 183 validate(cfg); 184 185 return deepFreeze(cfg); 186 }