auth

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

index.js (4089B)


      1 import bodyParser from 'body-parser';
      2 import cors from 'cors';
      3 import http from 'node:http';
      4 import path from 'node:path';
      5 import { fileURLToPath, pathToFileURL } from 'node:url';
      6 import morgan from 'morgan';
      7 import scandir from '@finwo/scandir';
      8 
      9 import { app } from './app.js';
     10 import { loadConfig } from './lib/config.js';
     11 import { closeRealms, initRealms } from './lib/realm.js';
     12 import { migrateProviderSecrets } from './lib/secrets.js';
     13 
     14 const here = path.dirname(fileURLToPath(import.meta.url));
     15 
     16 const cfg = loadConfig();
     17 app.config = cfg;
     18 
     19 async function loadModules(dir) {
     20   const files = [];
     21   scandir.sync(dir, (file) => files.push(file), ['js'], false);
     22   files.sort();
     23   const modules = [];
     24   for (const file of files) {
     25     modules.push(await import(pathToFileURL(file).href));
     26   }
     27   return modules;
     28 }
     29 
     30 for (const mod of await loadModules(path.join(here, 'lib', 'http'))) {
     31   Object.assign(app, mod);
     32 }
     33 
     34 const browserOrigins = new Set(
     35   [cfg.server.public_url, cfg.apps?.admin, cfg.apps?.account]
     36     .filter(Boolean)
     37     .map((value) => new URL(value).origin)
     38 );
     39 
     40 app.use(morgan('tiny'));
     41 app.use(
     42   cors({
     43     origin(origin, callback) {
     44       callback(null, !origin || browserOrigins.has(origin));
     45     },
     46   })
     47 );
     48 app.use(bodyParser.json({ limit: '64kb' }));
     49 app.use(bodyParser.urlencoded({ extended: false, limit: '16kb' }));
     50 
     51 const routes = [];
     52 for (const mod of await loadModules(path.join(here, 'controller'))) {
     53   const exported = mod.default ?? mod.route ?? mod;
     54   for (const route of Array.isArray(exported) ? exported : [exported]) {
     55     if (!route) continue;
     56     if (route.mount) {
     57       app.use(route.mount, route.handler);
     58       continue;
     59     }
     60     if (!route.method || !route.path) continue;
     61     if (route.name) {
     62       app.manifest.push({
     63         method: route.method,
     64         path: route.path,
     65         name: route.name,
     66       });
     67     }
     68     routes.push(route);
     69   }
     70 }
     71 
     72 routes.sort((A, B) => {
     73   const aparts = A.path.split('/');
     74   const bparts = B.path.split('/');
     75   for (let i = 0; i < Math.min(aparts.length, bparts.length); i += 1) {
     76     if (aparts[i].startsWith(':') && !bparts[i].startsWith(':')) return 1;
     77     if (!aparts[i].startsWith(':') && bparts[i].startsWith(':')) return -1;
     78   }
     79   return bparts.length - aparts.length;
     80 });
     81 
     82 for (const route of routes) {
     83   app[route.method](route.path, async (req, res, ...args) => {
     84     try {
     85       const result = await route.handler(req, res, ...args);
     86       if (result instanceof app.HttpResponse) result.send(res);
     87     } catch (e) {
     88       if (res.headersSent) {
     89         res.end();
     90         return;
     91       }
     92       if (e instanceof app.HttpError) {
     93         e.toResponse().send(res);
     94         return;
     95       }
     96       console.error(e);
     97       new app.HttpError(500, 'internal_error', 'Internal server error').toResponse().send(res);
     98     }
     99   });
    100 }
    101 
    102 await initRealms(cfg);
    103 
    104 const migratedSecrets = await migrateProviderSecrets();
    105 if (migratedSecrets > 0) {
    106   console.log(`encrypted ${migratedSecrets} provider client secret(s)`);
    107 }
    108 
    109 const server = http.createServer((req, res) => {
    110   app(req, res, (err) => {
    111     if (err) {
    112       const status = err.status || err.statusCode || 500;
    113       const code = err.type === 'entity.parse.failed' ? 'invalid_json' : 'internal_error';
    114       res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
    115       res.end(JSON.stringify({ error: { code, message: err.message || 'Request failed' } }));
    116       return;
    117     }
    118 
    119     if (res.headersSent) {
    120       res.end();
    121       return;
    122     }
    123     res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
    124     res.end('Not found');
    125   });
    126 });
    127 
    128 server.listen(cfg.server.port, cfg.server.host, () => {
    129   console.log(`Listening on ${cfg.server.host}:${cfg.server.port}`);
    130 });
    131 
    132 let shuttingDown = false;
    133 
    134 async function shutdown(signal) {
    135   if (shuttingDown) return;
    136   shuttingDown = true;
    137   console.log(`${signal} received, shutting down`);
    138   server.close();
    139   await closeRealms();
    140 }
    141 
    142 for (const signal of ['SIGINT', 'SIGTERM']) {
    143   process.once(signal, () => {
    144     shutdown(signal).finally(() => process.exit(0));
    145   });
    146 }