auth

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

requests.js (6318B)


      1 import crypto from 'node:crypto';
      2 import { parseCookie, stringifySetCookie } from 'cookie';
      3 
      4 const AUTH_REQUEST_TTL = 10 * 60;
      5 const CODE_TTL = 60;
      6 
      7 function authRequestScopeName(scope) {
      8   if (scope.systemClient) return `system_${scope.clientId}`;
      9   if (!scope.realm?.slug) throw new Error('auth request scope requires a realm');
     10   return scope.realm.slug;
     11 }
     12 
     13 export function authRequestCookieName(scope) {
     14   return `auth_request_${authRequestScopeName(scope)}`;
     15 }
     16 
     17 function secureRequest(req) {
     18   if (req.socket?.encrypted) return true;
     19   const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim().toLowerCase();
     20   return proto === 'https';
     21 }
     22 
     23 function appendSetCookie(res, value) {
     24   const existing = res.getHeader('Set-Cookie');
     25   if (!existing) {
     26     res.setHeader('Set-Cookie', value);
     27     return;
     28   }
     29   const values = Array.isArray(existing) ? existing : [existing];
     30   res.setHeader('Set-Cookie', [...values, value]);
     31 }
     32 
     33 export function setAuthRequestCookie(res, req, scope, id, ttl = AUTH_REQUEST_TTL) {
     34   appendSetCookie(
     35     res,
     36     stringifySetCookie({
     37       name: authRequestCookieName(scope),
     38       value: id,
     39       httpOnly: true,
     40       sameSite: 'lax',
     41       path: '/',
     42       maxAge: ttl,
     43       secure: secureRequest(req),
     44     })
     45   );
     46 }
     47 
     48 export function clearAuthRequestCookie(res, req, scope) {
     49   appendSetCookie(
     50     res,
     51     stringifySetCookie({
     52       name: authRequestCookieName(scope),
     53       value: '',
     54       httpOnly: true,
     55       sameSite: 'lax',
     56       path: '/',
     57       maxAge: 0,
     58       secure: secureRequest(req),
     59     })
     60   );
     61 }
     62 
     63 export function readAuthRequestId(req, scope) {
     64   const cookies = parseCookie(req.headers.cookie || '');
     65   return cookies[authRequestCookieName(scope)] || null;
     66 }
     67 
     68 export async function purgeExpired(db, now = Date.now()) {
     69   await db.run('DELETE FROM auth_requests WHERE expires_at <= {now}', { now });
     70   await db.run('DELETE FROM authorization_codes WHERE expires_at <= {now}', { now });
     71 }
     72 
     73 export async function createAuthRequest(db, data, now = Date.now()) {
     74   const id = crypto.randomBytes(24).toString('base64url');
     75   await db.run(
     76     `INSERT INTO auth_requests
     77       (id, client_id, redirect_uri, scope, state, nonce, code_challenge,
     78        code_challenge_method, created_at, expires_at)
     79      VALUES
     80       ({id}, {clientId}, {redirectUri}, {scope}, {state}, {nonce}, {codeChallenge},
     81        {codeChallengeMethod}, {createdAt}, {expiresAt})`,
     82     {
     83       id,
     84       clientId: data.clientId,
     85       redirectUri: data.redirectUri,
     86       scope: data.scope,
     87       state: data.state || null,
     88       nonce: data.nonce || null,
     89       codeChallenge: data.codeChallenge || null,
     90       codeChallengeMethod: data.codeChallengeMethod || null,
     91       createdAt: now,
     92       expiresAt: now + AUTH_REQUEST_TTL * 1000,
     93     }
     94   );
     95   return id;
     96 }
     97 
     98 export async function getAuthRequest(db, id, now = Date.now()) {
     99   if (!id) return null;
    100   const request = await db.get(
    101     `SELECT id, client_id, redirect_uri, scope, state, nonce, code_challenge,
    102             code_challenge_method, session_id, user_id, auth_time,
    103             created_at, expires_at, completed_at
    104        FROM auth_requests
    105       WHERE id = {id}`,
    106     { id }
    107   );
    108   if (!request) return null;
    109   if (request.expires_at <= now) {
    110     await db.run('DELETE FROM auth_requests WHERE id = {id}', { id });
    111     return null;
    112   }
    113   return request;
    114 }
    115 
    116 export async function selectAuthRequestAccount(
    117   db,
    118   id,
    119   { userId, sessionId, authTime }
    120 ) {
    121   if (!id) return;
    122   await db.run(
    123     `UPDATE auth_requests
    124         SET user_id = {userId}, session_id = {sessionId}, auth_time = {authTime}
    125       WHERE id = {id} AND completed_at IS NULL`,
    126     { id, userId, sessionId, authTime }
    127   );
    128 }
    129 
    130 export async function clearAuthRequestSelection(db, id) {
    131   if (!id) return;
    132   await db.run(
    133     `UPDATE auth_requests
    134         SET user_id = NULL, session_id = NULL, auth_time = NULL
    135       WHERE id = {id} AND completed_at IS NULL`,
    136     { id }
    137   );
    138 }
    139 
    140 export async function completeAuthRequest(db, id, { userId, sessionId, authTime }, now = Date.now()) {
    141   await db.run(
    142     `UPDATE auth_requests
    143         SET user_id = {userId}, session_id = {sessionId}, auth_time = {authTime}, completed_at = {now}
    144       WHERE id = {id}`,
    145     { id, userId, sessionId, authTime, now }
    146   );
    147 }
    148 
    149 export async function deleteAuthRequest(db, id) {
    150   if (!id) return;
    151   await db.run('DELETE FROM auth_requests WHERE id = {id}', { id });
    152 }
    153 
    154 export async function createAuthorizationCode(db, request, now = Date.now()) {
    155   const code = crypto.randomBytes(32).toString('base64url');
    156   const id = crypto.createHash('sha256').update(code).digest('hex');
    157 
    158   await db.run(
    159     `INSERT INTO authorization_codes
    160       (id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce,
    161        code_challenge, code_challenge_method, session_id, auth_time,
    162        created_at, expires_at)
    163      VALUES
    164       ({id}, {authRequestId}, {clientId}, {userId}, {redirectUri}, {scope}, {nonce},
    165        {codeChallenge}, {codeChallengeMethod}, {sessionId}, {authTime},
    166        {createdAt}, {expiresAt})`,
    167     {
    168       id,
    169       authRequestId: request.id,
    170       clientId: request.client_id,
    171       userId: request.user_id,
    172       redirectUri: request.redirect_uri,
    173       scope: request.scope,
    174       nonce: request.nonce,
    175       codeChallenge: request.code_challenge,
    176       codeChallengeMethod: request.code_challenge_method,
    177       sessionId: request.session_id,
    178       authTime: request.auth_time,
    179       createdAt: now,
    180       expiresAt: now + CODE_TTL * 1000,
    181     }
    182   );
    183 
    184   return code;
    185 }
    186 
    187 export async function consumeAuthorizationCode(db, code, clientId, now = Date.now()) {
    188   if (!code) return null;
    189   const id = crypto.createHash('sha256').update(String(code)).digest('hex');
    190 
    191   return db.transaction(async (tx) => {
    192     const row = await tx.get(
    193       `SELECT id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce,
    194               code_challenge, code_challenge_method, session_id, auth_time,
    195               expires_at, consumed_at
    196          FROM authorization_codes
    197         WHERE id = {id}`,
    198       { id }
    199     );
    200     if (!row || row.consumed_at || row.expires_at <= now || row.client_id !== clientId) {
    201       return null;
    202     }
    203     await tx.run('UPDATE authorization_codes SET consumed_at = {now} WHERE id = {id}', { now, id });
    204     return row;
    205   });
    206 }