admin-clients.js (26211B)
1 import crypto from 'node:crypto'; 2 import { 3 applyBrandingPatch, 4 hasBrandingPatch, 5 normalizeBrandingPatch, 6 serializeBranding, 7 } from './admin-branding.js'; 8 import { addClientRealm, findClientRealm } from './realm.js'; 9 import { hashClientSecret } from './oidc/clients.js'; 10 import { inClause } from './db/query.js'; 11 import { HttpError } from './http/http-error.js'; 12 import { pagedResult, searchClause } from './pagination.js'; 13 import { destroySessionById } from './session.js'; 14 15 const DEFAULT_SCOPES = 'openid profile email'; 16 const CLIENT_ID_MAX_LENGTH = 64; 17 const NAME_MAX_LENGTH = 100; 18 const URI_MAX_LENGTH = 2048; 19 const MAX_URI_COUNT = 10; 20 const MAX_SCOPE_COUNT = 50; 21 const MAX_ROLE_COUNT = 20; 22 const RESERVED_CLIENT_IDS = new Set(['admin', 'account']); 23 const CLIENT_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/; 24 const ACCESS_MODES = new Set(['internal', 'members', 'public']); 25 const CONSENT_MODES = new Set(['remembered', 'trusted']); 26 const TOKEN_AUTH_METHODS = new Set(['none', 'client_secret_basic']); 27 28 function invalidRequest(message, code = 'invalid_request') { 29 return new HttpError(400, code, message); 30 } 31 32 function notFound(message, code = 'client_not_found') { 33 return new HttpError(404, code, message); 34 } 35 36 function conflict(message, code = 'client_id_exists') { 37 return new HttpError(409, code, message); 38 } 39 40 function isPlainObject(value) { 41 return value !== null && typeof value === 'object' && !Array.isArray(value); 42 } 43 44 function parseJson(raw, fallback) { 45 try { 46 return JSON.parse(raw || 'null') ?? fallback; 47 } catch { 48 return fallback; 49 } 50 } 51 52 function assertBody(body) { 53 if (!isPlainObject(body)) { 54 throw invalidRequest('Request body must be a JSON object'); 55 } 56 } 57 58 function assertKnownFields(body, allowed) { 59 for (const field of Object.keys(body)) { 60 if (!allowed.has(field)) { 61 throw invalidRequest(`Unknown field: ${field}`); 62 } 63 } 64 } 65 66 function validateEnum(value, values, field) { 67 if (!values.has(value)) { 68 throw invalidRequest(`${field} must be one of ${[...values].join(', ')}`); 69 } 70 return value; 71 } 72 73 function validateBoolean(value, field) { 74 if (typeof value !== 'boolean') { 75 throw invalidRequest(`${field} must be a boolean`); 76 } 77 return value; 78 } 79 80 function validateClientId(value) { 81 if (typeof value !== 'string') { 82 throw invalidRequest('client_id must be a string', 'invalid_client_id'); 83 } 84 const clientId = value.trim(); 85 if (!CLIENT_ID_PATTERN.test(clientId) || clientId.length > CLIENT_ID_MAX_LENGTH) { 86 throw invalidRequest( 87 'client_id must contain only lowercase letters, digits, and hyphens, and must start with a letter or digit', 88 'invalid_client_id' 89 ); 90 } 91 if (RESERVED_CLIENT_IDS.has(clientId)) { 92 throw invalidRequest('This client_id is reserved', 'reserved_client_id'); 93 } 94 return clientId; 95 } 96 97 function validateName(value) { 98 if (typeof value !== 'string') { 99 throw invalidRequest('name must be a string'); 100 } 101 const name = value.trim(); 102 if (!name || name.length > NAME_MAX_LENGTH) { 103 throw invalidRequest(`name must be between 1 and ${NAME_MAX_LENGTH} characters`); 104 } 105 return name; 106 } 107 108 export function normalizeScopes(value) { 109 let raw = value; 110 if (raw === undefined || raw === null) raw = DEFAULT_SCOPES; 111 if (Array.isArray(raw)) raw = raw.join(' '); 112 if (typeof raw !== 'string') { 113 throw invalidRequest('scopes must be a string or an array of strings'); 114 } 115 116 const scopes = [...new Set(raw.trim().split(/\s+/).filter(Boolean))]; 117 if (!scopes.includes('openid')) { 118 throw invalidRequest('scopes must include openid'); 119 } 120 if (scopes.length > MAX_SCOPE_COUNT) { 121 throw invalidRequest(`scopes may contain at most ${MAX_SCOPE_COUNT} entries`); 122 } 123 for (const scope of scopes) { 124 if (!/^[\x21-\x7e]+$/.test(scope)) { 125 throw invalidRequest('scopes must contain only printable non-whitespace characters'); 126 } 127 } 128 return scopes.join(' '); 129 } 130 131 export function normalizeUriList(value, field, { required = false } = {}) { 132 if (value === undefined || value === null || (Array.isArray(value) && value.length === 0)) { 133 if (required) { 134 throw invalidRequest(`${field} must contain at least one URL`); 135 } 136 return []; 137 } 138 139 let values; 140 if (Array.isArray(value)) { 141 values = value; 142 } else if (typeof value === 'string') { 143 values = value.trim().split(/\s+/); 144 } else { 145 throw invalidRequest(`${field} must be an array of URLs`); 146 } 147 148 if (values.length > MAX_URI_COUNT) { 149 throw invalidRequest(`${field} may contain at most ${MAX_URI_COUNT} URLs`); 150 } 151 152 const result = new Set(); 153 for (const item of values) { 154 if (typeof item !== 'string') { 155 throw invalidRequest(`${field} must contain only strings`); 156 } 157 const uri = item.trim(); 158 if (!uri || uri.length > URI_MAX_LENGTH) { 159 throw invalidRequest( 160 `${field} URLs must be between 1 and ${URI_MAX_LENGTH} characters` 161 ); 162 } 163 if (uri.includes('*')) { 164 throw invalidRequest(`${field} URLs cannot contain wildcards`); 165 } 166 167 let parsed; 168 try { 169 parsed = new URL(uri); 170 } catch { 171 throw invalidRequest(`${field} URLs must be absolute`); 172 } 173 if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { 174 throw invalidRequest(`${field} URLs must use http or https`); 175 } 176 if (parsed.username || parsed.password) { 177 throw invalidRequest(`${field} URLs cannot contain credentials`); 178 } 179 if (parsed.hash) { 180 throw invalidRequest(`${field} URLs cannot contain fragments`); 181 } 182 result.add(uri); 183 } 184 185 if (required && result.size === 0) { 186 throw invalidRequest(`${field} must contain at least one URL`); 187 } 188 return [...result]; 189 } 190 191 function mapMappingError(error) { 192 const message = String(error?.message || ''); 193 if (/reserved/.test(message)) { 194 return invalidRequest('This client_id is reserved', 'reserved_client_id'); 195 } 196 if (/invalid client id/.test(message)) { 197 return invalidRequest('client_id is invalid', 'invalid_client_id'); 198 } 199 if (/already assigned/.test(message)) { 200 return conflict(); 201 } 202 return error; 203 } 204 205 function mapDatabaseError(error) { 206 if (/UNIQUE constraint failed: oidc_clients\.client_id/.test(String(error?.message || ''))) { 207 return conflict(); 208 } 209 return error; 210 } 211 212 async function getKnownRoleSet(db) { 213 const roles = await db.all('SELECT slug FROM roles'); 214 return new Set(roles.map((role) => role.slug)); 215 } 216 217 function validateRoles(value, knownRoles) { 218 if (value === undefined || value === null) return []; 219 if (!Array.isArray(value)) { 220 throw invalidRequest('required_roles must be an array'); 221 } 222 if (value.length > MAX_ROLE_COUNT) { 223 throw invalidRequest(`required_roles may contain at most ${MAX_ROLE_COUNT} entries`); 224 } 225 226 const result = new Set(); 227 for (const item of value) { 228 if (typeof item !== 'string') { 229 throw invalidRequest('required_roles must contain only strings'); 230 } 231 const slug = item.trim(); 232 if (!slug) { 233 throw invalidRequest('required_roles cannot contain empty values'); 234 } 235 if (!knownRoles.has(slug)) { 236 throw invalidRequest(`Unknown role: ${slug}`, 'unknown_role'); 237 } 238 result.add(slug); 239 } 240 return [...result]; 241 } 242 243 async function loadRoles(db, id) { 244 const rows = await db.all( 245 `SELECT r.slug 246 FROM oidc_client_roles cr 247 JOIN roles r ON r.id = cr.role_id 248 WHERE cr.client_id = {id} 249 ORDER BY r.slug ASC`, 250 { id } 251 ); 252 return rows.map((row) => row.slug); 253 } 254 255 function serializeClient(row, requiredRoles) { 256 return { 257 client_id: row.client_id, 258 name: row.name, 259 access_mode: row.access_mode, 260 ...serializeBranding(row.branding), 261 enabled: Boolean(row.enabled), 262 scopes: row.scopes || DEFAULT_SCOPES, 263 required_roles: requiredRoles, 264 redirect_uris: parseJson(row.redirect_uris, []), 265 post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), 266 token_endpoint_auth_method: row.token_endpoint_auth_method || 'none', 267 require_pkce: Boolean(row.require_pkce), 268 consent_mode: row.consent_mode || 'remembered', 269 has_secret: Boolean(row.client_secret_hash), 270 created_at: row.created_at, 271 updated_at: row.updated_at, 272 }; 273 } 274 275 export async function getAdminClientRow(db, clientId) { 276 return db.get( 277 `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, 278 branding, client_secret_hash, token_endpoint_auth_method, require_pkce, 279 post_logout_redirect_uris, consent_mode, created_at, updated_at 280 FROM oidc_clients 281 WHERE client_id = {clientId}`, 282 { clientId } 283 ); 284 } 285 286 export async function loadAdminClient(db, clientId) { 287 const row = await getAdminClientRow(db, clientId); 288 if (!row) return null; 289 return serializeClient(row, await loadRoles(db, row.id)); 290 } 291 292 export async function listAdminRealmClients(systemDb, realmDb, realmId) { 293 const mappedRows = await systemDb.all( 294 'SELECT client_id FROM client_realms WHERE realm_id = {realmId} ORDER BY client_id ASC', 295 { realmId } 296 ); 297 const mapped = new Set(mappedRows.map((row) => row.client_id)); 298 if (mapped.size === 0) return []; 299 300 const rows = await realmDb.all( 301 `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, 302 branding, client_secret_hash, token_endpoint_auth_method, require_pkce, 303 post_logout_redirect_uris, consent_mode, created_at, updated_at 304 FROM oidc_clients 305 ORDER BY name COLLATE NOCASE ASC, client_id ASC` 306 ); 307 const roleRows = await realmDb.all( 308 `SELECT c.client_id, r.slug 309 FROM oidc_client_roles cr 310 JOIN roles r ON r.id = cr.role_id 311 JOIN oidc_clients c ON c.id = cr.client_id 312 ORDER BY r.slug ASC` 313 ); 314 315 const rolesByClient = new Map(); 316 for (const role of roleRows) { 317 const current = rolesByClient.get(role.client_id) || []; 318 current.push(role.slug); 319 rolesByClient.set(role.client_id, current); 320 } 321 322 return rows 323 .filter((row) => mapped.has(row.client_id)) 324 .map((row) => serializeClient(row, rolesByClient.get(row.client_id) || [])); 325 } 326 327 const CLIENT_SEARCH_COLUMNS = ['client_id', 'name']; 328 const CLIENT_ID_CHUNK_SIZE = 500; 329 330 function mappedClientsClause(clientIds) { 331 const conditions = []; 332 const params = {}; 333 for (let start = 0; start < clientIds.length; start += CLIENT_ID_CHUNK_SIZE) { 334 const clause = inClause( 335 `mappedChunk${conditions.length}`, 336 clientIds.slice(start, start + CLIENT_ID_CHUNK_SIZE) 337 ); 338 conditions.push(`client_id IN (${clause.sql})`); 339 Object.assign(params, clause.params); 340 } 341 return { sql: `(${conditions.join(' OR ')})`, params }; 342 } 343 344 export async function listAdminRealmClientsPage(systemDb, realmDb, realmId, { pagination }) { 345 const mappedRows = await systemDb.all( 346 'SELECT client_id FROM client_realms WHERE realm_id = {realmId}', 347 { realmId } 348 ); 349 const emptyPage = { limit: pagination.limit, offset: pagination.offset, total: 0 }; 350 if (mappedRows.length === 0) { 351 return pagedResult('clients', [], emptyPage); 352 } 353 354 const mappedClause = mappedClientsClause(mappedRows.map((row) => row.client_id)); 355 let filter = mappedClause.sql; 356 const params = { ...mappedClause.params, limit: pagination.limit, offset: pagination.offset }; 357 if (pagination.q) { 358 const search = searchClause(pagination.q, CLIENT_SEARCH_COLUMNS); 359 filter += ` AND ${search.clause}`; 360 Object.assign(params, search.params); 361 } 362 363 const rows = await realmDb.all( 364 `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, 365 branding, client_secret_hash, token_endpoint_auth_method, require_pkce, 366 post_logout_redirect_uris, consent_mode, created_at, updated_at 367 FROM oidc_clients 368 WHERE ${filter} 369 ORDER BY name COLLATE NOCASE ASC, client_id ASC 370 LIMIT {limit} OFFSET {offset}`, 371 params 372 ); 373 const count = await realmDb.get( 374 `SELECT COUNT(*) AS total FROM oidc_clients WHERE ${filter}`, 375 params 376 ); 377 378 const clients = []; 379 if (rows.length > 0) { 380 const pageClause = inClause('roleClientId', rows.map((row) => row.client_id)); 381 const roleRows = await realmDb.all( 382 `SELECT c.client_id, r.slug 383 FROM oidc_client_roles cr 384 JOIN roles r ON r.id = cr.role_id 385 JOIN oidc_clients c ON c.id = cr.client_id 386 WHERE c.client_id IN (${pageClause.sql}) 387 ORDER BY r.slug ASC`, 388 pageClause.params 389 ); 390 const rolesByClient = new Map(); 391 for (const role of roleRows) { 392 const current = rolesByClient.get(role.client_id) || []; 393 current.push(role.slug); 394 rolesByClient.set(role.client_id, current); 395 } 396 for (const row of rows) { 397 clients.push(serializeClient(row, rolesByClient.get(row.client_id) || [])); 398 } 399 } 400 401 return pagedResult('clients', clients, { 402 limit: pagination.limit, 403 offset: pagination.offset, 404 total: count.total, 405 }); 406 } 407 408 export async function listAdminRealmRoles(realmDb) { 409 return realmDb.all( 410 'SELECT slug, name FROM roles ORDER BY name COLLATE NOCASE ASC, slug ASC' 411 ); 412 } 413 414 function currentClientState(row) { 415 return { 416 name: row.name, 417 access_mode: row.access_mode, 418 enabled: Boolean(row.enabled), 419 scopes: row.scopes || DEFAULT_SCOPES, 420 redirect_uris: parseJson(row.redirect_uris, []), 421 post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), 422 token_endpoint_auth_method: row.token_endpoint_auth_method || 'none', 423 require_pkce: Boolean(row.require_pkce), 424 consent_mode: row.consent_mode || 'remembered', 425 }; 426 } 427 428 export function normalizeCreateInput(body) { 429 assertBody(body); 430 assertKnownFields( 431 body, 432 new Set([ 433 'client_id', 434 'name', 435 'access_mode', 436 'enabled', 437 'scopes', 438 'required_roles', 439 'redirect_uris', 440 'post_logout_redirect_uris', 441 'token_endpoint_auth_method', 442 'require_pkce', 443 'consent_mode', 444 'logo_url', 445 'primary_color', 446 ]) 447 ); 448 449 const clientId = validateClientId(body.client_id); 450 const name = validateName(body.name); 451 const accessMode = validateEnum( 452 body.access_mode === undefined ? 'members' : body.access_mode, 453 ACCESS_MODES, 454 'access_mode' 455 ); 456 const consentMode = validateEnum( 457 body.consent_mode === undefined ? 'remembered' : body.consent_mode, 458 CONSENT_MODES, 459 'consent_mode' 460 ); 461 const enabled = validateBoolean(body.enabled === undefined ? true : body.enabled, 'enabled'); 462 const method = validateEnum( 463 body.token_endpoint_auth_method === undefined ? 'none' : body.token_endpoint_auth_method, 464 TOKEN_AUTH_METHODS, 465 'token_endpoint_auth_method' 466 ); 467 let requirePkce = validateBoolean( 468 body.require_pkce === undefined ? true : body.require_pkce, 469 'require_pkce' 470 ); 471 if (method === 'none') requirePkce = true; 472 473 return { 474 clientId, 475 name, 476 accessMode, 477 enabled, 478 scopes: normalizeScopes(body.scopes), 479 requiredRoles: body.required_roles ?? [], 480 redirectUris: normalizeUriList(body.redirect_uris, 'redirect_uris', { required: true }), 481 postLogoutRedirectUris: normalizeUriList( 482 body.post_logout_redirect_uris, 483 'post_logout_redirect_uris' 484 ), 485 tokenEndpointAuthMethod: method, 486 requirePkce, 487 consentMode, 488 branding: normalizeBrandingPatch(body), 489 }; 490 } 491 492 export async function normalizeUpdateInput(body, db) { 493 assertBody(body); 494 if (Object.hasOwn(body, 'client_id')) { 495 throw invalidRequest('client_id cannot be updated'); 496 } 497 assertKnownFields( 498 body, 499 new Set([ 500 'name', 501 'access_mode', 502 'enabled', 503 'scopes', 504 'required_roles', 505 'redirect_uris', 506 'post_logout_redirect_uris', 507 'token_endpoint_auth_method', 508 'require_pkce', 509 'consent_mode', 510 'logo_url', 511 'primary_color', 512 ]) 513 ); 514 515 const knownRoles = await getKnownRoleSet(db); 516 const result = {}; 517 if (Object.hasOwn(body, 'name')) result.name = validateName(body.name); 518 if (Object.hasOwn(body, 'access_mode')) { 519 result.accessMode = validateEnum(body.access_mode, ACCESS_MODES, 'access_mode'); 520 } 521 if (Object.hasOwn(body, 'enabled')) result.enabled = validateBoolean(body.enabled, 'enabled'); 522 if (Object.hasOwn(body, 'consent_mode')) { 523 result.consentMode = validateEnum(body.consent_mode, CONSENT_MODES, 'consent_mode'); 524 } 525 if (Object.hasOwn(body, 'scopes')) result.scopes = normalizeScopes(body.scopes); 526 if (Object.hasOwn(body, 'required_roles')) { 527 result.requiredRoles = validateRoles(body.required_roles, knownRoles); 528 } 529 if (Object.hasOwn(body, 'redirect_uris')) { 530 result.redirectUris = normalizeUriList(body.redirect_uris, 'redirect_uris', { required: true }); 531 } 532 if (Object.hasOwn(body, 'post_logout_redirect_uris')) { 533 result.postLogoutRedirectUris = normalizeUriList( 534 body.post_logout_redirect_uris, 535 'post_logout_redirect_uris' 536 ); 537 } 538 if (Object.hasOwn(body, 'token_endpoint_auth_method')) { 539 result.tokenEndpointAuthMethod = validateEnum( 540 body.token_endpoint_auth_method, 541 TOKEN_AUTH_METHODS, 542 'token_endpoint_auth_method' 543 ); 544 } 545 if (Object.hasOwn(body, 'require_pkce')) { 546 result.requirePkce = validateBoolean(body.require_pkce, 'require_pkce'); 547 } 548 Object.assign(result, normalizeBrandingPatch(body)); 549 if (Object.keys(result).length === 0) { 550 throw invalidRequest('At least one field must be provided'); 551 } 552 return result; 553 } 554 555 async function insertClientRoles(tx, clientId, roles) { 556 for (const slug of roles) { 557 const role = await tx.get('SELECT id FROM roles WHERE slug = {slug}', { slug }); 558 if (!role) { 559 throw invalidRequest(`Unknown role: ${slug}`, 'unknown_role'); 560 } 561 await tx.run( 562 'INSERT INTO oidc_client_roles (client_id, role_id) VALUES ({clientId}, {roleId})', 563 { clientId, roleId: role.id } 564 ); 565 } 566 } 567 568 export function generateClientSecret() { 569 return crypto.randomBytes(32).toString('base64url'); 570 } 571 572 export async function createAdminRealmClient({ systemDb, realmDb, realmId, input }) { 573 const mapping = await findClientRealm(input.clientId); 574 if (mapping) { 575 throw conflict(); 576 } 577 const existing = await getAdminClientRow(realmDb, input.clientId); 578 if (existing) { 579 throw conflict(); 580 } 581 582 const knownRoles = await getKnownRoleSet(realmDb); 583 const requiredRoles = validateRoles(input.requiredRoles, knownRoles); 584 const clientId = crypto.randomUUID(); 585 const now = Date.now(); 586 const branding = applyBrandingPatch('{}', input.branding); 587 const clientSecret = 588 input.tokenEndpointAuthMethod === 'client_secret_basic' ? generateClientSecret() : null; 589 590 try { 591 await realmDb.transaction(async (tx) => { 592 await tx.run( 593 `INSERT INTO oidc_clients 594 (id, client_id, name, redirect_uris, scopes, access_mode, enabled, branding, 595 client_secret_hash, token_endpoint_auth_method, require_pkce, 596 post_logout_redirect_uris, consent_mode, created_at, updated_at) 597 VALUES 598 ({id}, {clientId}, {name}, {redirectUris}, {scopes}, {accessMode}, {enabled}, {branding}, 599 {clientSecretHash}, {tokenEndpointAuthMethod}, {requirePkce}, 600 {postLogoutRedirectUris}, {consentMode}, {createdAt}, {updatedAt})`, 601 { 602 id: clientId, 603 clientId: input.clientId, 604 name: input.name, 605 redirectUris: JSON.stringify(input.redirectUris), 606 scopes: input.scopes, 607 accessMode: input.accessMode, 608 enabled: input.enabled ? 1 : 0, 609 branding, 610 clientSecretHash: clientSecret ? hashClientSecret(clientSecret) : null, 611 tokenEndpointAuthMethod: input.tokenEndpointAuthMethod, 612 requirePkce: input.requirePkce ? 1 : 0, 613 postLogoutRedirectUris: JSON.stringify(input.postLogoutRedirectUris), 614 consentMode: input.consentMode, 615 createdAt: now, 616 updatedAt: now, 617 } 618 ); 619 await insertClientRoles(tx, clientId, requiredRoles); 620 }); 621 } catch (error) { 622 throw mapDatabaseError(error); 623 } 624 625 try { 626 await addClientRealm(input.clientId, realmId); 627 } catch (error) { 628 await realmDb.run('DELETE FROM oidc_client_roles WHERE client_id = {id}', { id: clientId }); 629 await realmDb.run('DELETE FROM oidc_clients WHERE id = {id}', { id: clientId }); 630 throw mapMappingError(error); 631 } 632 633 const client = await loadAdminClient(realmDb, input.clientId); 634 if (!client) { 635 throw new HttpError(500, 'internal_error', 'Client was not created'); 636 } 637 return { client, client_secret: clientSecret }; 638 } 639 640 export async function updateAdminRealmClient({ 641 realmDb, 642 clientId, 643 body, 644 }) { 645 const row = await getAdminClientRow(realmDb, clientId); 646 if (!row) { 647 throw notFound(); 648 } 649 650 const current = currentClientState(row); 651 const input = await normalizeUpdateInput(body, realmDb); 652 const tokenEndpointAuthMethod = 653 input.tokenEndpointAuthMethod ?? current.token_endpoint_auth_method; 654 let requirePkce = input.requirePkce ?? current.require_pkce; 655 if (tokenEndpointAuthMethod === 'none') { 656 requirePkce = true; 657 } 658 if (tokenEndpointAuthMethod === 'none' && input.requirePkce === false) { 659 throw invalidRequest('Public clients must require PKCE'); 660 } 661 if (tokenEndpointAuthMethod === 'client_secret_basic' && !row.client_secret_hash) { 662 throw new HttpError( 663 409, 664 'client_secret_required', 665 'A client secret is required for client_secret_basic' 666 ); 667 } 668 669 const next = { 670 name: input.name ?? current.name, 671 accessMode: input.accessMode ?? current.access_mode, 672 enabled: input.enabled ?? current.enabled, 673 scopes: input.scopes ?? current.scopes, 674 redirectUris: input.redirectUris ?? current.redirect_uris, 675 postLogoutRedirectUris: 676 input.postLogoutRedirectUris ?? current.post_logout_redirect_uris, 677 tokenEndpointAuthMethod, 678 requirePkce, 679 consentMode: input.consentMode ?? current.consent_mode, 680 }; 681 const branding = hasBrandingPatch(input) 682 ? applyBrandingPatch(row.branding, input) 683 : row.branding; 684 const clientSecretHash = 685 tokenEndpointAuthMethod === 'client_secret_basic' ? row.client_secret_hash : null; 686 const now = Date.now(); 687 688 try { 689 await realmDb.transaction(async (tx) => { 690 await tx.run( 691 `UPDATE oidc_clients 692 SET name = {name}, redirect_uris = {redirectUris}, scopes = {scopes}, 693 access_mode = {accessMode}, enabled = {enabled}, branding = {branding}, 694 client_secret_hash = {clientSecretHash}, 695 token_endpoint_auth_method = {tokenEndpointAuthMethod}, 696 require_pkce = {requirePkce}, 697 post_logout_redirect_uris = {postLogoutRedirectUris}, 698 consent_mode = {consentMode}, updated_at = {updatedAt} 699 WHERE id = {id}`, 700 { 701 name: next.name, 702 redirectUris: JSON.stringify(next.redirectUris), 703 scopes: next.scopes, 704 accessMode: next.accessMode, 705 enabled: next.enabled ? 1 : 0, 706 branding, 707 clientSecretHash, 708 tokenEndpointAuthMethod: next.tokenEndpointAuthMethod, 709 requirePkce: next.requirePkce ? 1 : 0, 710 postLogoutRedirectUris: JSON.stringify(next.postLogoutRedirectUris), 711 consentMode: next.consentMode, 712 updatedAt: now, 713 id: row.id, 714 } 715 ); 716 717 if (Object.hasOwn(input, 'requiredRoles')) { 718 await tx.run('DELETE FROM oidc_client_roles WHERE client_id = {id}', { id: row.id }); 719 await insertClientRoles(tx, row.id, input.requiredRoles); 720 } 721 }); 722 } catch (error) { 723 throw mapDatabaseError(error); 724 } 725 726 const client = await loadAdminClient(realmDb, clientId); 727 if (!client) { 728 throw new HttpError(500, 'internal_error', 'Client was not updated'); 729 } 730 return client; 731 } 732 733 export async function rotateAdminClientSecret({ realmDb, clientId }) { 734 const row = await getAdminClientRow(realmDb, clientId); 735 if (!row) { 736 throw notFound(); 737 } 738 739 const clientSecret = generateClientSecret(); 740 await realmDb.run( 741 `UPDATE oidc_clients 742 SET client_secret_hash = {hash}, token_endpoint_auth_method = 'client_secret_basic', 743 updated_at = {updatedAt} 744 WHERE id = {id}`, 745 { 746 hash: hashClientSecret(clientSecret), 747 updatedAt: Date.now(), 748 id: row.id, 749 } 750 ); 751 752 const client = await loadAdminClient(realmDb, clientId); 753 if (!client) { 754 throw new HttpError(500, 'internal_error', 'Client secret was not updated'); 755 } 756 return { client, client_secret: clientSecret }; 757 } 758 759 async function deleteRealmClientState(realmDb, clientId, rowId) { 760 await realmDb.transaction(async (tx) => { 761 await tx.run('DELETE FROM oidc_client_roles WHERE client_id = {id}', { id: rowId }); 762 await tx.run('DELETE FROM auth_requests WHERE client_id = {clientId}', { clientId }); 763 await tx.run('DELETE FROM authorization_codes WHERE client_id = {clientId}', { clientId }); 764 await tx.run('DELETE FROM app_bans WHERE client_id = {clientId}', { clientId }); 765 await tx.run('DELETE FROM oidc_clients WHERE id = {id}', { id: rowId }); 766 }); 767 } 768 769 export async function deleteAdminRealmClient({ systemDb, realmDb, realmId, clientId }) { 770 const mapping = await findClientRealm(clientId); 771 if (mapping && mapping.realm_id !== realmId) { 772 throw notFound(); 773 } 774 775 const row = await getAdminClientRow(realmDb, clientId); 776 if (!row && !mapping) { 777 throw notFound(); 778 } 779 780 if (row) { 781 await deleteRealmClientState(realmDb, clientId, row.id); 782 } 783 784 const now = Date.now(); 785 await systemDb.transaction(async (tx) => { 786 const sessions = await tx.all( 787 'SELECT id FROM sessions WHERE realm_id = {realmId} AND client_id = {clientId}', 788 { realmId, clientId } 789 ); 790 for (const session of sessions) { 791 await destroySessionById(tx, session.id, now); 792 } 793 794 await tx.run( 795 'DELETE FROM refresh_tokens WHERE realm_id = {realmId} AND client_id = {clientId}', 796 { realmId, clientId } 797 ); 798 await tx.run( 799 'DELETE FROM client_consents WHERE realm_id = {realmId} AND client_id = {clientId}', 800 { realmId, clientId } 801 ); 802 if (mapping) { 803 await tx.run('DELETE FROM client_realms WHERE client_id = {clientId}', { clientId }); 804 } 805 }); 806 807 return { removed: true }; 808 }