realm.js (21264B)
1 import fs from 'node:fs'; 2 import path from 'node:path'; 3 import crypto from 'node:crypto'; 4 import { normalizeBrandingObject } from './admin-branding.js'; 5 import { openDatabase, runMigrations } from './db/index.js'; 6 import { MIGRATIONS_ROOT } from './db/migrate.js'; 7 import { HttpError } from './http/http-error.js'; 8 import { isSystemClient } from './oidc/clients.js'; 9 10 export const REALM_SLUG_MAX_LENGTH = 63; 11 12 const RESERVED_REALM_SLUGS = new Set(['admin', 'account', 'global']); 13 let systemDb = null; 14 let dialect = 'sqlite'; 15 let realmsPath = null; 16 const realmDbs = new Map(); 17 18 function migrationDir(dbDialect, type) { 19 return path.join(MIGRATIONS_ROOT, dbDialect, type); 20 } 21 22 async function migrateRealm(db, label) { 23 return runMigrations(db, { 24 dir: migrationDir(db.dialect, 'realm'), 25 namespace: 'realm', 26 label, 27 }); 28 } 29 30 async function migrateSystem(db) { 31 return runMigrations(db, { 32 dir: migrationDir(db.dialect, 'system'), 33 namespace: 'system', 34 label: 'system', 35 }); 36 } 37 38 async function ensureRole(db, slug, name, now) { 39 const existing = await db.get('SELECT id FROM roles WHERE slug = {slug}', { slug }); 40 if (existing) return existing.id; 41 const id = crypto.randomUUID(); 42 await db.run( 43 'INSERT INTO roles (id, slug, name, created_at) VALUES ({id}, {slug}, {name}, {createdAt})', 44 { id, slug, name, createdAt: now } 45 ); 46 return id; 47 } 48 49 async function seedRealmDefaults(db) { 50 const now = Date.now(); 51 await ensureRole(db, 'realm-admin', 'Realm administrator', now); 52 } 53 54 function removeRealmFiles(fullPath) { 55 for (const suffix of ['', '-wal', '-shm']) { 56 fs.rmSync(`${fullPath}${suffix}`, { force: true }); 57 } 58 } 59 60 export function normalizeRealmSlug(slug) { 61 const value = String(slug || '').trim(); 62 if (!/^[a-z0-9][a-z0-9-]*$/.test(value)) { 63 throw new Error(`invalid realm slug: ${JSON.stringify(slug)}`); 64 } 65 if (value.length > REALM_SLUG_MAX_LENGTH) { 66 throw new Error( 67 `realm slug must be at most ${REALM_SLUG_MAX_LENGTH} characters: ${JSON.stringify(value)}` 68 ); 69 } 70 if (RESERVED_REALM_SLUGS.has(value)) { 71 throw new Error(`realm slug is reserved: ${value}`); 72 } 73 return value; 74 } 75 76 async function writeRealmSettings(db, settings) { 77 const now = Date.now(); 78 await db.run( 79 `INSERT INTO realm_settings 80 (id, slug, display_name, kind, status, branding, allow_session_duration_choice, created_at, updated_at) 81 VALUES 82 (1, {slug}, {displayName}, {kind}, 'active', {branding}, {allowChoice}, {createdAt}, {updatedAt})`, 83 { 84 slug: settings.slug, 85 displayName: settings.displayName, 86 kind: settings.kind || 'realm', 87 branding: JSON.stringify(settings.branding || {}), 88 allowChoice: settings.allowSessionDurationChoice === false ? 0 : 1, 89 createdAt: now, 90 updatedAt: now, 91 } 92 ); 93 } 94 95 export function normalizeHost(host) { 96 let value = String(host || '').trim().toLowerCase(); 97 if (!value) return ''; 98 if (value.startsWith('[')) { 99 const end = value.indexOf(']'); 100 if (end !== -1) value = value.slice(0, end + 1); 101 } else { 102 const colon = value.indexOf(':'); 103 if (colon !== -1) value = value.slice(0, colon); 104 } 105 return value.replace(/\.$/, ''); 106 } 107 108 export function validateRealmHostname(raw) { 109 const invalid = (message) => new HttpError(400, 'invalid_request', message); 110 111 if (typeof raw !== 'string') throw invalid('host must be a string'); 112 const value = raw.trim(); 113 if (!value) throw invalid('host is required'); 114 if (/\s/.test(value)) throw invalid('host must not contain spaces'); 115 if (value.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) { 116 throw invalid('host must not include a scheme such as https://'); 117 } 118 if (value.includes('@')) throw invalid('host must not include @'); 119 if (value.includes('/')) throw invalid('host must not include a path'); 120 if (value.includes('*')) throw invalid('wildcard hostnames are not supported'); 121 122 const lower = value.toLowerCase(); 123 if (lower.startsWith('[')) { 124 const bracketEnd = lower.indexOf(']'); 125 if (bracketEnd === -1 || bracketEnd !== lower.length - 1) { 126 throw invalid('enter a valid IPv6 host without a port'); 127 } 128 } else if (lower.includes(':')) { 129 throw invalid('host must not include a port'); 130 } 131 132 if (lower.length > 253) throw invalid('host must be 253 characters or fewer'); 133 if (lower.startsWith('.') || lower.endsWith('.')) { 134 throw invalid('host must not start or end with a dot'); 135 } 136 137 const normalized = normalizeHost(value); 138 if (!normalized) throw invalid('host is required'); 139 if (normalized !== lower) throw invalid('host must not include a port or trailing dot'); 140 141 if (!normalized.startsWith('[')) { 142 const labels = normalized.split('.'); 143 if (labels.length < 2) throw invalid('enter a complete hostname such as login.acme.test'); 144 for (const label of labels) { 145 if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) { 146 throw invalid('host labels must use lowercase letters, numbers and hyphens'); 147 } 148 if (label.length > 63) throw invalid('each host label must be 63 characters or fewer'); 149 } 150 } 151 152 return normalized; 153 } 154 155 export function normalizeEmailDomain(domain) { 156 const value = String(domain || '').trim().toLowerCase().replace(/\.$/, ''); 157 if (!value || value.includes('@')) { 158 throw new Error(`invalid email domain: ${JSON.stringify(domain)}`); 159 } 160 return value; 161 } 162 163 export async function initRealms(cfg) { 164 await closeRealms(); 165 166 dialect = cfg.database.dialect; 167 realmsPath = path.resolve(cfg.database.realms); 168 const systemPath = path.resolve(cfg.database.path); 169 170 fs.mkdirSync(realmsPath, { recursive: true }); 171 fs.mkdirSync(path.dirname(systemPath), { recursive: true }); 172 173 systemDb = await openDatabase({ dialect, path: systemPath }); 174 await migrateSystem(systemDb); 175 } 176 177 export async function closeRealms() { 178 for (const db of realmDbs.values()) { 179 await db.close(); 180 } 181 realmDbs.clear(); 182 183 if (systemDb) { 184 await systemDb.close(); 185 systemDb = null; 186 } 187 } 188 189 export function getSystemDatabase() { 190 if (!systemDb) throw new Error('realm registry is not initialized'); 191 return systemDb; 192 } 193 194 export async function removeRealmDatabase(realm) { 195 if (!realmsPath) throw new Error('realm registry is not initialized'); 196 197 const fullPath = path.resolve(realmsPath, realm.db_file); 198 if (path.dirname(fullPath) !== realmsPath) { 199 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 200 } 201 202 const db = realmDbs.get(realm.id); 203 if (db) { 204 realmDbs.delete(realm.id); 205 await db.close(); 206 } 207 208 removeRealmFiles(fullPath); 209 } 210 211 export async function openRealmDatabase(realm) { 212 const cached = realmDbs.get(realm.id); 213 if (cached) return cached; 214 215 const fullPath = path.resolve(realmsPath, realm.db_file); 216 if (path.dirname(fullPath) !== realmsPath) { 217 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 218 } 219 if (!fs.existsSync(fullPath)) { 220 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 221 } 222 223 const db = await openDatabase({ dialect, path: fullPath }); 224 await migrateRealm(db, `realm ${realm.slug}`); 225 await seedRealmDefaults(db); 226 realmDbs.set(realm.id, db); 227 return db; 228 } 229 230 export async function realmMetadata(realm) { 231 const db = await openRealmDatabase(realm); 232 const settings = await db.get( 233 `SELECT slug, display_name, status, branding, allow_session_duration_choice 234 FROM realm_settings 235 WHERE id = 1` 236 ); 237 238 if (!settings || settings.status !== 'active') { 239 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 240 } 241 242 return { 243 slug: settings.slug, 244 display_name: settings.display_name, 245 branding: normalizeBrandingObject(settings.branding), 246 allow_session_duration_choice: Boolean(settings.allow_session_duration_choice), 247 }; 248 } 249 250 export async function resolveRealm({ host, slug } = {}) { 251 if (!systemDb) throw new Error('realm registry is not initialized'); 252 253 const normalizedHost = normalizeHost(host); 254 if (normalizedHost) { 255 const byClientHost = await systemDb.get( 256 `SELECT r.id, r.slug, r.db_file, r.owner_user_id, r.created_at 257 FROM oidc_client_hosts h 258 JOIN client_realms cr ON cr.client_id = h.client_id 259 JOIN realms r ON r.id = cr.realm_id 260 WHERE h.host = {host}`, 261 { host: normalizedHost } 262 ); 263 if (byClientHost) { 264 if (slug && slug !== byClientHost.slug) { 265 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 266 } 267 return byClientHost; 268 } 269 270 const byHost = await systemDb.get( 271 `SELECT r.id, r.slug, r.db_file, r.owner_user_id, r.created_at 272 FROM realm_hosts h 273 JOIN realms r ON r.id = h.realm_id 274 WHERE h.host = {host}`, 275 { host: normalizedHost } 276 ); 277 if (byHost) { 278 if (slug && slug !== byHost.slug) { 279 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 280 } 281 return byHost; 282 } 283 } 284 285 if (slug) { 286 const bySlug = await systemDb.get( 287 'SELECT id, slug, db_file, owner_user_id, created_at FROM realms WHERE slug = {slug}', 288 { slug } 289 ); 290 if (bySlug) return bySlug; 291 } 292 293 throw new HttpError(404, 'unknown_realm', 'Unknown realm'); 294 } 295 296 export async function createRealm({ 297 slug, 298 displayName, 299 branding = {}, 300 hosts = [], 301 ownerUserId = null, 302 allowSessionDurationChoice = true, 303 }) { 304 if (!systemDb) throw new Error('realm registry is not initialized'); 305 const normalizedSlug = normalizeRealmSlug(slug); 306 307 const existing = await systemDb.get('SELECT id FROM realms WHERE slug = {slug}', { 308 slug: normalizedSlug, 309 }); 310 if (existing) throw new Error(`realm already exists: ${normalizedSlug}`); 311 312 const id = crypto.randomUUID(); 313 const dbFile = `${id}.sqlite`; 314 const fullPath = path.join(realmsPath, dbFile); 315 316 const db = await openDatabase({ dialect, path: fullPath }); 317 try { 318 await migrateRealm(db, `realm ${normalizedSlug}`); 319 await writeRealmSettings(db, { 320 slug: normalizedSlug, 321 displayName, 322 kind: 'realm', 323 branding, 324 allowSessionDurationChoice, 325 }); 326 await seedRealmDefaults(db); 327 } catch (e) { 328 await db.close(); 329 removeRealmFiles(fullPath); 330 throw e; 331 } 332 333 try { 334 await systemDb.run( 335 `INSERT INTO realms (id, slug, db_file, owner_user_id, created_at) 336 VALUES ({id}, {slug}, {dbFile}, {ownerUserId}, {createdAt})`, 337 { id, slug: normalizedSlug, dbFile, ownerUserId, createdAt: Date.now() } 338 ); 339 340 for (const host of hosts) { 341 await addRealmHost(id, host); 342 } 343 } catch (e) { 344 await systemDb.run('DELETE FROM realms WHERE id = {id}', { id }); 345 await db.close(); 346 removeRealmFiles(fullPath); 347 throw e; 348 } 349 350 realmDbs.set(id, db); 351 return { id, slug: normalizedSlug, db_file: dbFile, owner_user_id: ownerUserId }; 352 } 353 354 export async function addRealmHost(realmId, host) { 355 if (!systemDb) throw new Error('realm registry is not initialized'); 356 const normalized = normalizeHost(host); 357 if (!normalized || normalized !== String(host).trim().toLowerCase()) { 358 throw new Error(`invalid realm hostname: ${JSON.stringify(host)}`); 359 } 360 await systemDb.run( 361 'INSERT INTO realm_hosts (host, realm_id, created_at) VALUES ({host}, {realmId}, {createdAt})', 362 { host: normalized, realmId, createdAt: Date.now() } 363 ); 364 } 365 366 export async function listRealmHosts(systemDb, realmId) { 367 if (!systemDb) throw new Error('realm registry is not initialized'); 368 return systemDb.all( 369 `SELECT host, created_at FROM realm_hosts 370 WHERE realm_id = {realmId} 371 ORDER BY created_at DESC, host ASC`, 372 { realmId } 373 ); 374 } 375 376 export async function removeRealmHost(systemDb, realmId, host) { 377 if (!systemDb) throw new Error('realm registry is not initialized'); 378 const normalized = normalizeHost(host); 379 if (!normalized) return false; 380 const result = await systemDb.run( 381 'DELETE FROM realm_hosts WHERE host = {host} AND realm_id = {realmId}', 382 { host: normalized, realmId } 383 ); 384 return result.changes > 0; 385 } 386 387 export async function addClientRealm(clientId, realmId) { 388 if (!systemDb) throw new Error('realm registry is not initialized'); 389 const value = String(clientId || '').trim(); 390 if (!/^[a-z0-9][a-z0-9-]*$/.test(value)) { 391 throw new Error(`invalid client id: ${JSON.stringify(clientId)}`); 392 } 393 if (isSystemClient(value)) { 394 throw new Error(`client id is reserved: ${value}`); 395 } 396 const existing = await findClientRealm(value); 397 if (existing) { 398 if (existing.realm_id === realmId) return existing; 399 throw new Error(`client id is already assigned: ${value}`); 400 } 401 await systemDb.run( 402 'INSERT INTO client_realms (client_id, realm_id, created_at) VALUES ({clientId}, {realmId}, {createdAt})', 403 { clientId: value, realmId, createdAt: Date.now() } 404 ); 405 return findClientRealm(value); 406 } 407 408 export async function findClientRealm(clientId) { 409 if (!systemDb) throw new Error('realm registry is not initialized'); 410 return systemDb.get( 411 `SELECT cr.client_id, cr.realm_id, r.slug, r.db_file, r.owner_user_id 412 FROM client_realms cr 413 LEFT JOIN realms r ON r.id = cr.realm_id 414 WHERE cr.client_id = {clientId}`, 415 { clientId } 416 ); 417 } 418 419 export async function addOidcClientHost(clientId, host) { 420 if (!systemDb) throw new Error('realm registry is not initialized'); 421 const normalized = normalizeHost(host); 422 if (!normalized || normalized !== String(host).trim().toLowerCase()) { 423 throw new Error(`invalid client hostname: ${JSON.stringify(host)}`); 424 } 425 const mapping = await findClientRealm(clientId); 426 if (!mapping || !mapping.realm_id) { 427 throw new Error(`unknown client: ${clientId}`); 428 } 429 await systemDb.run( 430 `INSERT INTO oidc_client_hosts (host, client_id, created_at) 431 VALUES ({host}, {clientId}, {createdAt})`, 432 { host: normalized, clientId, createdAt: Date.now() } 433 ); 434 } 435 436 export async function findOidcClientHost(host) { 437 if (!systemDb) throw new Error('realm registry is not initialized'); 438 const normalized = normalizeHost(host); 439 if (!normalized) return null; 440 return systemDb.get( 441 `SELECT h.host, h.client_id, cr.realm_id, r.slug, r.db_file, r.owner_user_id 442 FROM oidc_client_hosts h 443 JOIN client_realms cr ON cr.client_id = h.client_id 444 JOIN realms r ON r.id = cr.realm_id 445 WHERE h.host = {host}`, 446 { host: normalized } 447 ); 448 } 449 450 export async function findRealmHost(host) { 451 if (!systemDb) throw new Error('realm registry is not initialized'); 452 const normalized = normalizeHost(host); 453 if (!normalized) return null; 454 return systemDb.get( 455 `SELECT r.id, r.slug, r.db_file, r.owner_user_id 456 FROM realm_hosts h 457 JOIN realms r ON r.id = h.realm_id 458 WHERE h.host = {host}`, 459 { host: normalized } 460 ); 461 } 462 463 export async function listOidcClientHosts(systemDb, clientId) { 464 if (!systemDb) throw new Error('realm registry is not initialized'); 465 return systemDb.all( 466 `SELECT host, created_at FROM oidc_client_hosts 467 WHERE client_id = {clientId} 468 ORDER BY created_at DESC, host ASC`, 469 { clientId } 470 ); 471 } 472 473 export async function removeOidcClientHost(systemDb, clientId, host) { 474 if (!systemDb) throw new Error('realm registry is not initialized'); 475 const normalized = normalizeHost(host); 476 if (!normalized) return false; 477 const result = await systemDb.run( 478 'DELETE FROM oidc_client_hosts WHERE host = {host} AND client_id = {clientId}', 479 { host: normalized, clientId } 480 ); 481 return result.changes > 0; 482 } 483 484 export async function addRealmEmailDomain(realmId, domain, { verified = true } = {}) { 485 if (!systemDb) throw new Error('realm registry is not initialized'); 486 const normalized = normalizeEmailDomain(domain); 487 const existing = await systemDb.get( 488 'SELECT domain FROM realm_email_domains WHERE domain = {domain}', 489 { domain: normalized } 490 ); 491 if (existing) throw new Error(`email domain is already assigned: ${normalized}`); 492 const now = Date.now(); 493 await systemDb.run( 494 `INSERT INTO realm_email_domains 495 (domain, realm_id, verified, verification_token, verified_at, created_at) 496 VALUES 497 ({domain}, {realmId}, {verified}, {token}, {verifiedAt}, {createdAt})`, 498 { 499 domain: normalized, 500 realmId, 501 verified: verified ? 1 : 0, 502 token: verified ? null : crypto.randomBytes(24).toString('base64url'), 503 verifiedAt: verified ? now : null, 504 createdAt: now, 505 } 506 ); 507 } 508 509 export async function findRealmByEmailDomain(domain) { 510 if (!systemDb) throw new Error('realm registry is not initialized'); 511 const normalized = normalizeEmailDomain(domain); 512 return systemDb.get( 513 `SELECT r.id, r.slug, r.db_file, r.owner_user_id 514 FROM realm_email_domains d 515 JOIN realms r ON r.id = d.realm_id 516 WHERE d.domain = {domain} AND d.verified = 1`, 517 { domain: normalized } 518 ); 519 } 520 521 export async function findRealmBySlug(slug) { 522 if (!systemDb) throw new Error('realm registry is not initialized'); 523 return systemDb.get( 524 'SELECT id, slug, db_file, owner_user_id FROM realms WHERE slug = {slug}', 525 { slug } 526 ); 527 } 528 529 export async function findRealmById(id) { 530 if (!systemDb) throw new Error('realm registry is not initialized'); 531 return systemDb.get( 532 'SELECT id, slug, db_file, owner_user_id, created_at FROM realms WHERE id = {id}', 533 { id } 534 ); 535 } 536 537 export function validateRealmEmailDomain(raw) { 538 const invalid = (message) => new HttpError(400, 'invalid_request', message); 539 540 if (typeof raw !== 'string') throw invalid('domain must be a string'); 541 const value = raw.trim(); 542 if (!value) throw invalid('email domain is required'); 543 if (/\s/.test(value)) throw invalid('email domain must not contain spaces'); 544 545 const lower = value.toLowerCase(); 546 const domain = lower.replace(/\.$/, ''); 547 if (!domain) throw invalid('email domain is required'); 548 if (domain.includes('@')) throw invalid('enter the domain without the @ symbol'); 549 if (domain.includes('://') || /^[a-z][a-z0-9+.-]*:\/\//i.test(lower)) { 550 throw invalid('email domain must not include a scheme such as https://'); 551 } 552 if (domain.includes('/')) throw invalid('email domain must not include a path'); 553 if (domain.includes('*')) throw invalid('wildcard domains are not supported'); 554 if (domain.includes(':')) throw invalid('email domain must not include a port'); 555 if (lower.endsWith('.')) throw invalid('email domain must not end with a dot'); 556 if (domain.startsWith('.')) throw invalid('email domain must not start with a dot'); 557 if (domain.length > 253) throw invalid('email domain must be 253 characters or fewer'); 558 559 const labels = domain.split('.'); 560 if (labels.length < 2) throw invalid('enter a complete domain such as acme.test'); 561 for (const label of labels) { 562 if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) { 563 throw invalid('domain labels may use lowercase letters, numbers and hyphens'); 564 } 565 if (label.length > 63) throw invalid('each domain label must be 63 characters or fewer'); 566 } 567 568 return domain; 569 } 570 571 function lookupDomain(domain) { 572 return String(domain || '').trim().toLowerCase().replace(/\.$/, ''); 573 } 574 575 export async function listRealmEmailDomains(targetDb, realmId) { 576 const db = targetDb || systemDb; 577 if (!db) throw new Error('realm registry is not initialized'); 578 return db.all( 579 `SELECT domain, verified, verification_token, verified_at, created_at 580 FROM realm_email_domains 581 WHERE realm_id = {realmId} 582 ORDER BY created_at DESC, domain ASC`, 583 { realmId } 584 ); 585 } 586 587 export async function findRealmEmailDomainOwner(targetDb, domain) { 588 const db = targetDb || systemDb; 589 if (!db) throw new Error('realm registry is not initialized'); 590 const value = lookupDomain(domain); 591 if (!value) return null; 592 return db.get( 593 `SELECT d.domain, d.verified, d.realm_id, r.slug 594 FROM realm_email_domains d 595 JOIN realms r ON r.id = d.realm_id 596 WHERE d.domain = {domain}`, 597 { domain: value } 598 ); 599 } 600 601 export async function getRealmEmailDomain(targetDb, realmId, domain) { 602 const db = targetDb || systemDb; 603 if (!db) throw new Error('realm registry is not initialized'); 604 const value = lookupDomain(domain); 605 if (!value) return null; 606 return db.get( 607 `SELECT domain, realm_id, verified, verification_token, verified_at, created_at 608 FROM realm_email_domains 609 WHERE domain = {domain} AND realm_id = {realmId}`, 610 { domain: value, realmId } 611 ); 612 } 613 614 export async function removeRealmEmailDomain(targetDb, realmId, domain) { 615 const db = targetDb || systemDb; 616 if (!db) throw new Error('realm registry is not initialized'); 617 const value = lookupDomain(domain); 618 if (!value) return false; 619 const result = await db.run( 620 'DELETE FROM realm_email_domains WHERE domain = {domain} AND realm_id = {realmId}', 621 { domain: value, realmId } 622 ); 623 return result.changes > 0; 624 } 625 626 export async function markRealmEmailDomainVerified(targetDb, realmId, domain) { 627 const db = targetDb || systemDb; 628 if (!db) throw new Error('realm registry is not initialized'); 629 const value = lookupDomain(domain); 630 if (!value) return false; 631 const result = await db.run( 632 `UPDATE realm_email_domains 633 SET verified = 1, verified_at = {now}, verification_token = NULL 634 WHERE domain = {domain} AND realm_id = {realmId} AND verified = 0`, 635 { domain: value, realmId, now: Date.now() } 636 ); 637 return result.changes > 0; 638 }