auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

oidc.js (25947B)


      1 import crypto from 'node:crypto';
      2 import { app } from '../app.js';
      3 import { normalizeBrandingObject } from '../lib/admin-branding.js';
      4 import {
      5   serveAppDocument,
      6   systemClientPostLogoutUris,
      7   systemClientRedirectUris,
      8 } from '../lib/apps.js';
      9 import { isUserBanned } from '../lib/bans.js';
     10 import { consentStatus, getConsent, recordConsent } from '../lib/consents.js';
     11 import { HttpError } from '../lib/http/http-error.js';
     12 import {
     13   authenticateClient,
     14   getClient,
     15   getSystemClient,
     16   postLogoutRedirectAllowed,
     17   redirectUriAllowed,
     18 } from '../lib/oidc/clients.js';
     19 import {
     20   canonicalIssuer,
     21   endpointBase,
     22   endpointUrls,
     23   resolveOidcContext,
     24   systemIssuer,
     25 } from '../lib/oidc/context.js';
     26 import { getJwks, signToken, verifyToken } from '../lib/oidc/keys.js';
     27 import {
     28   clearAuthRequestCookie,
     29   clearAuthRequestSelection,
     30   completeAuthRequest,
     31   createAuthRequest,
     32   createAuthorizationCode,
     33   deleteAuthRequest,
     34   getAuthRequest,
     35   purgeExpired,
     36   readAuthRequestId,
     37   selectAuthRequestAccount,
     38   setAuthRequestCookie,
     39 } from '../lib/oidc/requests.js';
     40 import { canUseClient } from '../lib/policy.js';
     41 import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../lib/realm.js';
     42 import { issueRefreshToken, rotateRefreshToken } from '../lib/refresh-tokens.js';
     43 import { getSystemBranding } from '../lib/system-settings.js';
     44 import {
     45   authenticateRequest,
     46   bindSessionRealm,
     47   clearSessionCookie,
     48   destroySession,
     49   findActiveSessionById,
     50   getSessionRealmBinding,
     51   listSessionAccounts,
     52   requestToken,
     53   sessionMatchesContext,
     54 } from '../lib/session.js';
     55 import { canUseSystemClient } from '../lib/system-clients.js';
     56 import {
     57   findUserById,
     58   getMembership,
     59   getPrimaryEmail,
     60   getUserRoles,
     61 } from '../lib/users.js';
     62 
     63 const ACCESS_TOKEN_TTL = 300;
     64 
     65 function oidcError(status, error, description, headers = {}) {
     66   return new app.HttpResponse(
     67     status,
     68     { error, error_description: description },
     69     { 'cache-control': 'no-store', ...headers }
     70   );
     71 }
     72 
     73 function redirect(res, location) {
     74   return new app.HttpResponse(302, undefined, { location });
     75 }
     76 
     77 function withQuery(url, params) {
     78   const target = new URL(url);
     79   for (const [key, value] of Object.entries(params)) {
     80     if (value !== undefined && value !== null && value !== '') {
     81       target.searchParams.set(key, String(value));
     82     }
     83   }
     84   return target.toString();
     85 }
     86 
     87 function bearerToken(req) {
     88   const header = String(req.headers.authorization || '');
     89   return header.startsWith('Bearer ') ? header.slice(7) : null;
     90 }
     91 
     92 function accessDenied(res, redirectUri, state) {
     93   return redirect(
     94     res,
     95     withQuery(redirectUri, {
     96       error: 'access_denied',
     97       error_description: 'The user is not allowed to use this client',
     98       state,
     99     })
    100   );
    101 }
    102 
    103 function tokenStore(context, systemDb, realmDb) {
    104   if (context.systemClient) {
    105     return { db: systemDb, table: 'system_signing_keys' };
    106   }
    107   return { db: realmDb, table: 'signing_keys' };
    108 }
    109 
    110 function tokenIssuer(context) {
    111   return context.systemClient
    112     ? systemIssuer(app.config.server.public_url)
    113     : canonicalIssuer(app.config.server.public_url, context.realm.slug);
    114 }
    115 
    116 function systemCallbacks(context, client) {
    117   return client.system_client ? systemClientRedirectUris(context, client.client_id) : [];
    118 }
    119 
    120 async function discovery(context, client) {
    121   const systemBranding = await getSystemBranding(getSystemDatabase());
    122   const realm = context.realm ? await realmMetadata(context.realm) : null;
    123   const urls = endpointUrls(context);
    124   const branding = {
    125     ...systemBranding,
    126     ...(realm?.branding || {}),
    127     ...normalizeBrandingObject(client.branding),
    128   };
    129   const scopes = String(client.scopes || 'openid profile email')
    130     .split(/\s+/)
    131     .filter(Boolean);
    132 
    133   return new app.HttpOk(
    134     {
    135       issuer: tokenIssuer(context),
    136       client_id: client.client_id,
    137       client_name: client.name,
    138       realm: context.realm?.slug ?? null,
    139       display_name: client.name,
    140       branding,
    141       access_mode: client.access_mode,
    142       system_client: Boolean(client.system_client),
    143       allow_session_duration_choice: realm?.allow_session_duration_choice ?? true,
    144       authorization_endpoint: urls.authorize,
    145       token_endpoint: urls.token,
    146       userinfo_endpoint: urls.userinfo,
    147       jwks_uri: urls.jwks,
    148       end_session_endpoint: urls.logout,
    149       response_types_supported: ['code'],
    150       grant_types_supported: client.system_client
    151         ? ['authorization_code', 'refresh_token']
    152         : ['authorization_code'],
    153       subject_types_supported: ['public'],
    154       id_token_signing_alg_values_supported: ['ES256'],
    155       scopes_supported: scopes,
    156       token_endpoint_auth_methods_supported: [client.token_endpoint_auth_method || 'none'],
    157       code_challenge_methods_supported: ['S256'],
    158       claims_supported: [
    159         'iss',
    160         'sub',
    161         'aud',
    162         'exp',
    163         'iat',
    164         'auth_time',
    165         'nonce',
    166         'name',
    167         'preferred_username',
    168         'email',
    169         'email_verified',
    170         'roles',
    171       ],
    172       require_pkce: Boolean(client.require_pkce),
    173     },
    174     { 'cache-control': 'no-cache' }
    175   );
    176 }
    177 
    178 async function authorize(context, client, req, res) {
    179   const url = new URL(req.url, context.origin);
    180   const params = url.searchParams;
    181   const systemDb = getSystemDatabase();
    182   const realmDb = context.realm ? await openRealmDatabase(context.realm) : null;
    183   const store = context.systemClient ? systemDb : realmDb;
    184   await purgeExpired(store);
    185 
    186   const pendingId = readAuthRequestId(req, context);
    187   let pending = await getAuthRequest(store, pendingId);
    188   if (pending && (pending.completed_at || pending.client_id !== client.client_id)) {
    189     await deleteAuthRequest(store, pending.id);
    190     clearAuthRequestCookie(res, req, context);
    191     pending = null;
    192   }
    193 
    194   const callbacks = systemCallbacks(context, client);
    195   let redirectUri = params.get('redirect_uri');
    196   let state = params.get('state');
    197   let scope = params.get('scope');
    198   let nonce = params.get('nonce');
    199   let codeChallenge = params.get('code_challenge');
    200   let codeChallengeMethod = params.get('code_challenge_method');
    201   const requestedClientId = params.get('client_id');
    202 
    203   const fail = (error, description) => {
    204     const target = pending?.redirect_uri || redirectUri;
    205     if (!target) return oidcError(400, error, description);
    206     return redirect(
    207       res,
    208       withQuery(target, {
    209         error,
    210         error_description: description,
    211         state: pending?.state || state,
    212       })
    213     );
    214   };
    215 
    216   if (pending) {
    217     const mismatch =
    218       (redirectUri && redirectUri !== pending.redirect_uri) ||
    219       (requestedClientId && requestedClientId !== pending.client_id) ||
    220       (params.has('response_type') && params.get('response_type') !== 'code') ||
    221       (scope && scope !== pending.scope) ||
    222       (params.has('state') && state !== pending.state) ||
    223       (params.has('nonce') && nonce !== pending.nonce) ||
    224       (codeChallenge && codeChallenge !== pending.code_challenge) ||
    225       (codeChallengeMethod && codeChallengeMethod !== pending.code_challenge_method);
    226 
    227     if (mismatch) {
    228       await deleteAuthRequest(store, pending.id);
    229       clearAuthRequestCookie(res, req, context);
    230       pending = null;
    231     } else {
    232       redirectUri = pending.redirect_uri;
    233       state = pending.state;
    234       scope = pending.scope;
    235       nonce = pending.nonce;
    236       codeChallenge = pending.code_challenge;
    237       codeChallengeMethod = pending.code_challenge_method;
    238     }
    239   }
    240 
    241   if (!pending) {
    242     if (!redirectUri) {
    243       return oidcError(400, 'invalid_request', 'redirect_uri is required');
    244     }
    245     if (!redirectUriAllowed(client, redirectUri, callbacks)) {
    246       return oidcError(400, 'invalid_request', 'redirect_uri is not registered');
    247     }
    248     if (params.get('response_type') !== 'code') {
    249       return fail('unsupported_response_type', 'Only response_type=code is supported');
    250     }
    251     if ((requestedClientId || context.clientId) !== client.client_id) {
    252       return fail('invalid_request', 'client_id does not match the requested client');
    253     }
    254     if (!scope) scope = 'openid';
    255     if (!scope.split(/\s+/).includes('openid')) {
    256       return fail('invalid_scope', 'The openid scope is required');
    257     }
    258     if (client.require_pkce && (!codeChallenge || codeChallengeMethod !== 'S256')) {
    259       return fail('invalid_request', 'PKCE with S256 is required');
    260     }
    261   }
    262 
    263   const auth = await authenticateRequest({
    264     systemDb,
    265     realmDb,
    266     req,
    267     res,
    268     context,
    269   });
    270 
    271   let allowed = false;
    272   if (auth) {
    273     if (client.system_client) {
    274       allowed = await canUseSystemClient(systemDb, { user: auth.user, client });
    275     } else {
    276       allowed =
    277         canUseClient({
    278           user: auth.user,
    279           membership: auth.membership,
    280           roles: auth.roles,
    281           client,
    282           realm: context.realm,
    283         }) &&
    284         !(await isUserBanned(realmDb, {
    285           userId: auth.user.id,
    286           clientId: client.client_id,
    287         }));
    288     }
    289   }
    290 
    291   if (auth && !allowed) {
    292     if (pending) {
    293       await deleteAuthRequest(store, pending.id);
    294       clearAuthRequestCookie(res, req, context);
    295     }
    296     return accessDenied(res, redirectUri, state);
    297   }
    298 
    299   if (!pending) {
    300     pending = {
    301       id: await createAuthRequest(store, {
    302         clientId: client.client_id,
    303         redirectUri,
    304         scope,
    305         state,
    306         nonce,
    307         codeChallenge,
    308         codeChallengeMethod,
    309       }),
    310     };
    311 
    312     if (!auth) {
    313       setAuthRequestCookie(res, req, context, pending.id);
    314       return redirect(res, endpointUrls(context).login);
    315     }
    316   }
    317 
    318   if (!auth) {
    319     setAuthRequestCookie(res, req, context, pending.id);
    320     return redirect(res, endpointUrls(context).login);
    321   }
    322 
    323   const accounts = await listSessionAccounts(systemDb, auth.group);
    324   const selected = Boolean(
    325     pending.user_id &&
    326       pending.session_id &&
    327       pending.session_id === auth.session.id &&
    328       pending.user_id === auth.user.id
    329   );
    330   if ((pending.user_id || pending.session_id) && !selected) {
    331     await clearAuthRequestSelection(store, pending.id);
    332   }
    333   if (!selected && accounts.length >= 2) {
    334     setAuthRequestCookie(res, req, context, pending.id);
    335     return redirect(res, endpointUrls(context).login);
    336   }
    337 
    338   if (context.realm) {
    339     const binding = await getSessionRealmBinding(
    340       systemDb,
    341       auth.session.id,
    342       context.realm.id
    343     );
    344     if (binding?.revoked_at) {
    345       await clearAuthRequestSelection(store, pending.id);
    346       setAuthRequestCookie(res, req, context, pending.id);
    347       const login = new URL(endpointUrls(context).login);
    348       login.searchParams.set('reauth', '1');
    349       return redirect(res, login.toString());
    350     }
    351     await bindSessionRealm(systemDb, auth.session.id, context.realm.id);
    352   }
    353 
    354   const consent = client.system_client
    355     ? null
    356     : await getConsent(systemDb, {
    357         userId: auth.user.id,
    358         realmId: context.realm.id,
    359         clientId: client.client_id,
    360       });
    361   const consentState = consentStatus({
    362     client,
    363     user: auth.user,
    364     realm: context.realm,
    365     consent,
    366     scope,
    367   });
    368 
    369   if (consentState.required) {
    370     await selectAuthRequestAccount(store, pending.id, {
    371       userId: auth.user.id,
    372       sessionId: auth.session.id,
    373       authTime: auth.session.auth_time,
    374     });
    375     setAuthRequestCookie(res, req, context, pending.id);
    376     return redirect(res, endpointUrls(context).consent);
    377   }
    378 
    379   if (consentState.autoGrant) {
    380     await recordConsent(systemDb, {
    381       userId: auth.user.id,
    382       realmId: context.realm.id,
    383       clientId: client.client_id,
    384       scopes: scope,
    385       grantedVia: 'trusted',
    386     });
    387   }
    388 
    389   await completeAuthRequest(store, pending.id, {
    390     userId: auth.user.id,
    391     sessionId: auth.session.id,
    392     authTime: auth.session.auth_time,
    393   });
    394 
    395   const request = await getAuthRequest(store, pending.id);
    396   const code = await createAuthorizationCode(store, request);
    397   await deleteAuthRequest(store, pending.id);
    398   clearAuthRequestCookie(res, req, context);
    399 
    400   return redirect(res, withQuery(redirectUri, { code, state }));
    401 }
    402 
    403 function verifyPkce(codeVerifier, challenge) {
    404   if (!codeVerifier || !challenge) return false;
    405   const computed = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
    406   const left = Buffer.from(computed);
    407   const right = Buffer.from(challenge);
    408   return left.length === right.length && crypto.timingSafeEqual(left, right);
    409 }
    410 
    411 async function accessTokenResponse({
    412   systemDb,
    413   realmDb,
    414   context,
    415   client,
    416   user,
    417   scope,
    418   sessionId,
    419   authTime,
    420   nonce,
    421   includeIdToken = true,
    422 }) {
    423   const store = tokenStore(context, systemDb, realmDb);
    424   const issuer = tokenIssuer(context);
    425   const email = await getPrimaryEmail(systemDb, user.id);
    426   const roles = context.systemClient ? [] : await getUserRoles(realmDb, user.id);
    427 
    428   const accessClaims = {
    429     sub: user.id,
    430     client_id: client.client_id,
    431     scope,
    432     roles,
    433     sid: sessionId || undefined,
    434   };
    435   const accessToken = await signToken(store.db, accessClaims, {
    436     issuer,
    437     audience: client.client_id,
    438     expiresIn: ACCESS_TOKEN_TTL,
    439     table: store.table,
    440   });
    441 
    442   const response = {
    443     access_token: accessToken,
    444     token_type: 'Bearer',
    445     expires_in: ACCESS_TOKEN_TTL,
    446     scope,
    447   };
    448 
    449   if (includeIdToken) {
    450     const idClaims = {
    451       sub: user.id,
    452       email: email?.email,
    453       email_verified: Boolean(email?.verified),
    454       name: user.display_name || user.username,
    455       preferred_username: user.username,
    456       roles,
    457       auth_time: authTime,
    458       sid: sessionId || undefined,
    459       nonce: nonce || undefined,
    460     };
    461     response.id_token = await signToken(store.db, idClaims, {
    462       issuer,
    463       audience: client.client_id,
    464       expiresIn: ACCESS_TOKEN_TTL,
    465       table: store.table,
    466     });
    467   }
    468 
    469   return response;
    470 }
    471 
    472 async function token(context, client, req) {
    473   if (req.method !== 'POST') {
    474     return oidcError(405, 'invalid_request', 'POST is required');
    475   }
    476 
    477   const body = req.body || {};
    478   if (!authenticateClient(req, client, body)) {
    479     return oidcError(401, 'invalid_client', 'Client authentication failed', {
    480       'www-authenticate': 'Basic realm="oidc"',
    481     });
    482   }
    483 
    484   const systemDb = getSystemDatabase();
    485   const realmDb = context.realm ? await openRealmDatabase(context.realm) : null;
    486   const store = tokenStore(context, systemDb, realmDb);
    487 
    488   if (body.grant_type === 'authorization_code') {
    489     const code = await store.db.get(
    490       `SELECT id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce,
    491               code_challenge, code_challenge_method, session_id, auth_time,
    492               expires_at, consumed_at
    493          FROM authorization_codes
    494         WHERE id = {id}`,
    495       { id: crypto.createHash('sha256').update(String(body.code || '')).digest('hex') }
    496     );
    497 
    498     if (
    499       !code ||
    500       code.consumed_at ||
    501       code.expires_at <= Date.now() ||
    502       code.client_id !== client.client_id
    503     ) {
    504       return oidcError(400, 'invalid_grant', 'The authorization code is invalid');
    505     }
    506     if (body.redirect_uri !== code.redirect_uri) {
    507       return oidcError(400, 'invalid_grant', 'redirect_uri does not match');
    508     }
    509     if (code.code_challenge) {
    510       if (
    511         code.code_challenge_method !== 'S256' ||
    512         !verifyPkce(body.code_verifier, code.code_challenge)
    513       ) {
    514         return oidcError(400, 'invalid_grant', 'PKCE verification failed');
    515       }
    516     } else if (client.require_pkce) {
    517       return oidcError(400, 'invalid_grant', 'PKCE is required');
    518     }
    519 
    520     await store.db.run('UPDATE authorization_codes SET consumed_at = {now} WHERE id = {id}', {
    521       now: Date.now(),
    522       id: code.id,
    523     });
    524 
    525     const user = await findUserById(systemDb, code.user_id);
    526     if (!user || user.status !== 'active') {
    527       return oidcError(400, 'invalid_grant', 'The user is not available');
    528     }
    529 
    530     if (client.system_client) {
    531       if (!(await canUseSystemClient(systemDb, { user, client }))) {
    532         return oidcError(400, 'invalid_grant', 'The user no longer has access to this client');
    533       }
    534     } else {
    535       const membership = await getMembership(realmDb, user.id);
    536       const roles = await getUserRoles(realmDb, user.id);
    537       if (
    538         !canUseClient({
    539           user,
    540           membership,
    541           roles,
    542           client,
    543           realm: context.realm,
    544         }) ||
    545         (await isUserBanned(realmDb, {
    546           userId: user.id,
    547           clientId: client.client_id,
    548         }))
    549       ) {
    550         return oidcError(400, 'invalid_grant', 'The user no longer has access to this client');
    551       }
    552     }
    553 
    554     if (!client.system_client) {
    555       const consent = await getConsent(systemDb, {
    556         userId: user.id,
    557         realmId: context.realm.id,
    558         clientId: client.client_id,
    559       });
    560       const consentState = consentStatus({
    561         client,
    562         user,
    563         realm: context.realm,
    564         consent,
    565         scope: code.scope,
    566       });
    567       if (consentState.required) {
    568         return oidcError(400, 'invalid_grant', 'The user has not consented to this client');
    569       }
    570       if (consentState.autoGrant) {
    571         await recordConsent(systemDb, {
    572           userId: user.id,
    573           realmId: context.realm.id,
    574           clientId: client.client_id,
    575           scopes: code.scope,
    576           grantedVia: 'trusted',
    577         });
    578       }
    579     }
    580 
    581     const response = await accessTokenResponse({
    582       systemDb,
    583       realmDb,
    584       context,
    585       client,
    586       user,
    587       scope: code.scope,
    588       sessionId: code.session_id,
    589       authTime: code.auth_time,
    590       nonce: code.nonce,
    591     });
    592 
    593     if (client.system_client && code.session_id) {
    594       const refresh = await issueRefreshToken(systemDb, {
    595         sessionId: code.session_id,
    596         userId: user.id,
    597         realmId: context.realm?.id ?? null,
    598         clientId: client.client_id,
    599         scopes: code.scope,
    600       });
    601       response.refresh_token = refresh.token;
    602     }
    603 
    604     return new app.HttpOk(response, { 'cache-control': 'no-store' });
    605   }
    606 
    607   if (body.grant_type === 'refresh_token') {
    608     if (!client.system_client) {
    609       return oidcError(400, 'unsupported_grant_type', 'Only authorization_code is supported');
    610     }
    611 
    612     const rotated = await rotateRefreshToken(systemDb, body.refresh_token, {
    613       async validate(row, tx) {
    614         if (row.client_id !== client.client_id) return false;
    615         if (row.realm_id !== (context.realm?.id ?? null)) return false;
    616 
    617         const session = await findActiveSessionById(tx, row.session_id);
    618         if (!session || session.user_id !== row.user_id) return false;
    619         if (!sessionMatchesContext(session, context)) return false;
    620 
    621         const user = await findUserById(tx, row.user_id);
    622         if (!user || user.status !== 'active') return false;
    623 
    624         if (client.system_client) {
    625           if (!(await canUseSystemClient(tx, { user, client }))) return false;
    626         } else {
    627           const consent = await getConsent(tx, {
    628             userId: row.user_id,
    629             realmId: row.realm_id,
    630             clientId: row.client_id,
    631           });
    632           const consentState = consentStatus({
    633             client,
    634             user,
    635             realm: context.realm,
    636             consent,
    637             scope: row.scopes,
    638           });
    639           if (consentState.required) return false;
    640         }
    641 
    642         if (row.realm_id) {
    643           if (
    644             !client.system_client &&
    645             (!realmDb ||
    646               (await isUserBanned(realmDb, {
    647                 userId: row.user_id,
    648                 clientId: row.client_id,
    649               })))
    650           ) {
    651             return false;
    652           }
    653           const binding = await getSessionRealmBinding(tx, row.session_id, row.realm_id);
    654           if (!binding || binding.revoked_at) return false;
    655         }
    656         return true;
    657       },
    658     });
    659 
    660     if (rotated.status !== 'ok') {
    661       return oidcError(400, 'invalid_grant', 'The refresh token is invalid');
    662     }
    663 
    664     const user = await findUserById(systemDb, rotated.row.user_id);
    665     if (!user || user.status !== 'active') {
    666       return oidcError(400, 'invalid_grant', 'The user is not available');
    667     }
    668 
    669     const response = await accessTokenResponse({
    670       systemDb,
    671       realmDb,
    672       context,
    673       client,
    674       user,
    675       scope: rotated.row.scopes,
    676       sessionId: rotated.row.session_id,
    677       includeIdToken: false,
    678     });
    679     response.refresh_token = rotated.token;
    680     return new app.HttpOk(response, { 'cache-control': 'no-store' });
    681   }
    682 
    683   return oidcError(400, 'unsupported_grant_type', 'Only authorization_code is supported');
    684 }
    685 
    686 async function userinfo(context, client, req) {
    687   const tokenValue = bearerToken(req);
    688   if (!tokenValue) {
    689     return oidcError(401, 'invalid_token', 'A bearer token is required', {
    690       'www-authenticate': 'Bearer',
    691     });
    692   }
    693 
    694   const systemDb = getSystemDatabase();
    695   const realmDb = context.realm ? await openRealmDatabase(context.realm) : null;
    696   const store = tokenStore(context, systemDb, realmDb);
    697   let payload;
    698   try {
    699     payload = await verifyToken(store.db, tokenValue, {
    700       issuer: tokenIssuer(context),
    701       audience: client.client_id,
    702       table: store.table,
    703     });
    704   } catch {
    705     return oidcError(401, 'invalid_token', 'The access token is invalid', {
    706       'www-authenticate': 'Bearer error="invalid_token"',
    707     });
    708   }
    709 
    710   if (payload.client_id !== client.client_id || !payload.sub) {
    711     return oidcError(401, 'invalid_token', 'The access token does not belong to this client', {
    712       'www-authenticate': 'Bearer error="invalid_token"',
    713     });
    714   }
    715 
    716   const user = await findUserById(systemDb, payload.sub);
    717   if (!user || user.status !== 'active') {
    718     return oidcError(401, 'invalid_token', 'The user is not available');
    719   }
    720   if (client.system_client && !(await canUseSystemClient(systemDb, { user, client }))) {
    721     return oidcError(401, 'invalid_token', 'The user no longer has access to this client');
    722   }
    723   if (
    724     !client.system_client &&
    725     (!realmDb ||
    726       (await isUserBanned(realmDb, {
    727         userId: user.id,
    728         clientId: client.client_id,
    729       })))
    730   ) {
    731     return oidcError(401, 'invalid_token', 'The user no longer has access to this client');
    732   }
    733 
    734   const email = await getPrimaryEmail(systemDb, user.id);
    735   const roles = client.system_client ? [] : await getUserRoles(realmDb, user.id);
    736 
    737   return new app.HttpOk({
    738     sub: user.id,
    739     name: user.display_name || user.username,
    740     preferred_username: user.username,
    741     email: email?.email,
    742     email_verified: Boolean(email?.verified),
    743     roles,
    744     is_system_admin: Boolean(user.is_system_admin),
    745   });
    746 }
    747 
    748 async function logout(context, client, req, res) {
    749   const url = new URL(req.url, context.origin);
    750   const postLogoutUri = url.searchParams.get('post_logout_redirect_uri');
    751   const state = url.searchParams.get('state');
    752   const callbacks = client.system_client
    753     ? systemClientPostLogoutUris(context, client.client_id)
    754     : [];
    755 
    756   if (!postLogoutRedirectAllowed(client, postLogoutUri, callbacks)) {
    757     return oidcError(400, 'invalid_request', 'post_logout_redirect_uri is not registered');
    758   }
    759 
    760   const systemDb = getSystemDatabase();
    761   const realmDb = context.realm ? await openRealmDatabase(context.realm) : null;
    762   const store = tokenStore(context, systemDb, realmDb);
    763   const idTokenHint = url.searchParams.get('id_token_hint');
    764   if (idTokenHint) {
    765     try {
    766       await verifyToken(store.db, idTokenHint, {
    767         issuer: tokenIssuer(context),
    768         audience: client.client_id,
    769         table: store.table,
    770       });
    771     } catch {
    772       return oidcError(400, 'invalid_request', 'id_token_hint is invalid');
    773     }
    774   }
    775 
    776   const result = await destroySession(systemDb, requestToken(req));
    777   if (result.groupDeleted) clearSessionCookie(res, req);
    778   clearAuthRequestCookie(res, req, context);
    779 
    780   if (postLogoutUri) {
    781     return redirect(res, withQuery(postLogoutUri, { state }));
    782   }
    783   return new app.HttpOk({ ok: true });
    784 }
    785 
    786 export default {
    787   mount: '/oidc',
    788   name: 'oidc',
    789   async handler(req, res) {
    790     try {
    791       const context = await resolveOidcContext(req, {
    792         publicUrl: app.config.server.public_url,
    793       });
    794       if (context.action === 'login' || context.action === 'consent') {
    795         serveAppDocument(res, 'login');
    796         return;
    797       }
    798       if (context.action === 'callback') {
    799         throw new HttpError(404, 'not_found', 'Not found');
    800       }
    801 
    802       const systemDb = getSystemDatabase();
    803       const realmDb = context.realm ? await openRealmDatabase(context.realm) : null;
    804       const client = context.systemClient
    805         ? getSystemClient(context.clientId)
    806         : await getClient(realmDb, context.clientId);
    807       if (!client || !client.enabled) {
    808         throw new HttpError(404, 'unknown_client', 'Unknown client');
    809       }
    810 
    811       let result;
    812       switch (context.action) {
    813         case 'openid-configuration':
    814           result = await discovery(context, client);
    815           break;
    816         case 'jwks':
    817           result = context.systemClient
    818             ? new app.HttpOk(await getJwks(systemDb, { table: 'system_signing_keys' }))
    819             : new app.HttpOk(await getJwks(realmDb));
    820           break;
    821         case 'authorize':
    822           result = await authorize(context, client, req, res);
    823           break;
    824         case 'token':
    825           result = await token(context, client, req);
    826           break;
    827         case 'userinfo':
    828           result = await userinfo(context, client, req);
    829           break;
    830         case 'logout':
    831           result = await logout(context, client, req, res);
    832           break;
    833         default:
    834           throw new HttpError(404, 'not_found', 'Not found');
    835       }
    836 
    837       if (result) result.send(res);
    838     } catch (e) {
    839       if (res.headersSent) {
    840         res.end();
    841         return;
    842       }
    843       if (e instanceof app.HttpError) {
    844         e.toResponse().send(res);
    845         return;
    846       }
    847       console.error(e);
    848       new app.HttpError(500, 'internal_error', 'Internal server error').toResponse().send(res);
    849     }
    850   },
    851 };