miolo 0.9.24 → 0.9.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -21,12 +21,12 @@ var nodemailer = require('nodemailer');
21
21
  var tinguir = require('tinguir');
22
22
  var util = require('node:util');
23
23
  var winston = require('winston');
24
+ var fs = require('node:fs');
24
25
  var koa_body_parser = require('koa-better-body');
25
26
  var koa_convert = require('koa-convert');
26
27
  var koa_compress = require('koa-compress');
27
28
  var node_zlib = require('node:zlib');
28
29
  var ratelimit = require('koa-ratelimit');
29
- var fs = require('node:fs');
30
30
  var https = require('node:https');
31
31
  var koa_mount = require('koa-mount');
32
32
  var koa_serve = require('koa-static');
@@ -902,6 +902,48 @@ function init_logger_to_mail(config, emailer) {
902
902
  return MailerLogger;
903
903
  }
904
904
 
905
+ /**
906
+ * https://gist.github.com/suprememoocow/5133080
907
+ *
908
+ * https://github.com/winstonjs/winston/issues/943
909
+ *
910
+ * A function for reopening a winston File logging transport post logrotation on a HUP signal.
911
+ * To send a HUP to your node service, use the postrotate configuration option from logrotate.
912
+ * `postrotate kill -HUP ‘cat /var/run/mynodeservice.pid‘`
913
+ */
914
+ function reopenTransportOnHupSignal(fileTransport) {
915
+ process.on('SIGHUP', function () {
916
+ var fullname = path.join(fileTransport.dirname, fileTransport._getFile(false));
917
+ console.log("[miolo][file-logger] SIGHUP received. Check if we need to re-open log file " + fullname + "...");
918
+ function reopen() {
919
+ console.log("[miolo][file-logger] Reopening " + fullname + "...");
920
+ try {
921
+ if (fileTransport._stream) {
922
+ fileTransport._stream.end();
923
+ fileTransport._stream.destroySoon();
924
+ }
925
+ var stream = fs.createWriteStream(fullname, fileTransport.options);
926
+ stream.setMaxListeners(Infinity);
927
+ fileTransport._size = 0;
928
+ fileTransport._stream = stream;
929
+ fileTransport.once('flush', function () {
930
+ fileTransport.opening = false;
931
+ fileTransport.emit('open', fullname);
932
+ });
933
+ fileTransport.flush();
934
+ console.log("[miolo][file-logger] Reopened " + fullname + " successfully");
935
+ } catch (error) {
936
+ console.error("[miolo][file-logger] Error reopening " + fullname + ": " + error.toString());
937
+ }
938
+ }
939
+ fs.stat(fullname, function (err) {
940
+ if (err && err.code == 'ENOENT') {
941
+ return reopen();
942
+ }
943
+ });
944
+ });
945
+ }
946
+
905
947
  var combine = winston.format.combine,
906
948
  timestamp = winston.format.timestamp;
907
949
  winston.format._label;
@@ -956,14 +998,19 @@ var init_logger = function init_logger(config, emailer, prefix) {
956
998
  //
957
999
  // File transport
958
1000
  //
1001
+ // logrotate's copytruncate seems not enough
1002
+ // https://github.com/winstonjs/winston/issues/943
1003
+ // https://gist.github.com/suprememoocow/5133080
959
1004
  if ((config == null || (_config$file = config.file) == null ? void 0 : _config$file.enabled) === true) {
960
1005
  var _config$file2, _config$file3;
961
- _log_transports.push(new winston.transports.File({
1006
+ var fileTransport = new winston.transports.File({
962
1007
  filename: (config == null || (_config$file2 = config.file) == null ? void 0 : _config$file2.filename) || '/var/log/miolo.log',
963
1008
  level: (config == null || (_config$file3 = config.file) == null ? void 0 : _config$file3.level) || (config == null ? void 0 : config.level) || 'info',
964
1009
  humanReadableUnhandledException: true,
965
1010
  handleExceptions: true
966
- }));
1011
+ });
1012
+ reopenTransportOnHupSignal(fileTransport);
1013
+ _log_transports.push(fileTransport);
967
1014
  }
968
1015
 
969
1016
  //
@@ -1088,7 +1135,7 @@ var init_body_middleware = function init_body_middleware(app) {
1088
1135
  * @param ctx
1089
1136
  */
1090
1137
 
1091
- var _ONLY_WARN = [401];
1138
+ var _ONLY_WARN = [401, 403];
1092
1139
  function init_catcher_middleware(app) {
1093
1140
  var logger = app.context.miolo.logger;
1094
1141
  function catcher_middleware(_x) {
@@ -1262,7 +1309,7 @@ function ipsum_config() {
1262
1309
  name: 'IPsum',
1263
1310
  cronTime: '0 0 * * *',
1264
1311
  onTick: function onTick(miolo, _onCompleted) {
1265
- var folder = miolo.config.ratelimit.ipsum_folder || _IPSUM_DEF_FOLDER;
1312
+ var folder = miolo.config.http.ratelimit.ipsum_folder || _IPSUM_DEF_FOLDER;
1266
1313
  ipsum_update(folder, function (ips) {
1267
1314
  miolo.logger.info("[SERVER][" + tinguir.cyan('IPsum') + "] File downloaded. " + tinguir.green(ips.length) + " ips will be " + tinguir.yellow('blacklisted') + "!");
1268
1315
  }, miolo.logger);
@@ -1275,6 +1322,7 @@ function ipsum_read_ips(folder, callback, logger) {
1275
1322
  folder = _IPSUM_DEF_FOLDER;
1276
1323
  }
1277
1324
  var ldbg = logger ? logger.debug : console.log;
1325
+ var lwarn = logger ? logger.warn : console.log;
1278
1326
  var ips = _ipsum_ips_from_file(folder, logger);
1279
1327
  if (ips.length > 0) {
1280
1328
  if (callback) {
@@ -1283,13 +1331,34 @@ function ipsum_read_ips(folder, callback, logger) {
1283
1331
  ldbg("[SERVER][" + tinguir.cyan('IPsum') + "] File contains " + ips.length + " ips");
1284
1332
  return ips;
1285
1333
  } else {
1286
- ldbg("[SERVER][" + tinguir.cyan('IPsum') + "] File is empty. Launching update...");
1334
+ lwarn("[SERVER][" + tinguir.cyan('IPsum') + "] File is empty. Launching update...");
1287
1335
  ipsum_update(folder, callback, logger);
1288
1336
  return [];
1289
1337
  }
1290
1338
  }
1291
1339
 
1292
- var CUSTOM_BLACKLIST_IPS = ['52.212.247.108', '170.106.82.193', '54.218.32.58', '205.210.31.240 ', '134.122.52.203', '165.232.105.25'];
1340
+ var CUSTOM_BLACKLIST_IPS = ['52.212.247.108',
1341
+ // Amazon Data Services Ireland
1342
+ '54.218.32.58',
1343
+ // Amazon.com, Inc. AMAZO-ZPDX4
1344
+ '170.106.82.193',
1345
+ // Asia Pacific Network Information Centre (APNIC)
1346
+ '110.166.71.39',
1347
+ // Asia Pacific Network Information Centre (APNIC)
1348
+ '205.210.31.240 ',
1349
+ // Palo Alto Networks, Inc (PAN-22)
1350
+ '134.122.52.203',
1351
+ // DigitalOcean, LLC (DO-13)
1352
+ '165.232.105.25',
1353
+ // DigitalOcean, LLC (DO-13)
1354
+ '66.249.73.200',
1355
+ // Google
1356
+ '35.206.153.204',
1357
+ // Google
1358
+ '199.244.88.227',
1359
+ // Sundance International LLC (SIL-58)
1360
+ '198.12.222.107' // GoDaddy.com, LLC (GODAD)
1361
+ ];
1293
1362
 
1294
1363
  function init_rate_limit_middleware(app, config) {
1295
1364
  /* eslint-disable no-unused-vars */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.24
2
+ * miolo v0.9.25
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import e from"node:http";import r from"koa";import{createHttpTerminator as t}from"http-terminator";import o from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import l from"nodemailer";import{uncolor as c,gray as u,magenta as s,cyan as d,yellow as f,red_light as v,red as m,green as p,cyan_light as h,blue as g,green_bold as y,yellow_bold as b}from"tinguir";import S,{promisify as E}from"node:util";import x,{transports as _,createLogger as R,format as w}from"winston";import k from"koa-better-body";import O from"koa-convert";import C from"koa-compress";import{constants as q}from"node:zlib";import P from"koa-ratelimit";import M,{readFileSync as j}from"node:fs";import L from"node:https";import I from"koa-mount";import J from"koa-static";import T from"koa-favicon";import{performance as F}from"node:perf_hooks";import{Reader as V}from"@maxmind/geoip2-node";import A from"@koa/router";import U from"jwt-simple";import N from"koa-passport";import z from"passport-local";import B from"koa-session";import D from"koa-redis";import G from"@koa/cors";import W from"koa-proxies";import Y from"qs";import{renderToString as H}from"react-dom/server";import{CronJob as K}from"cron";import X from"node:os";import Z from"diskspace";import Q from"redis";function $(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function ee(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?$(Object(t),!0).forEach((function(r){oe(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):$(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function re(e,r,t,o,n,i,a){try{var l=e[i](a),c=l.value}catch(u){return void t(u)}l.done?r(c):Promise.resolve(c).then(o,n)}function te(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){re(i,o,n,a,l,"next",e)}function l(e){re(i,o,n,a,l,"throw",e)}a(void 0)}))}}function oe(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"==typeof r?r:String(r)}(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var ne=i(import.meta.url),ie=n.dirname(ne),ae={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(ie,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,ratelimit:{max:1e3,duration:6e4,errorMessage:"Rate Limit reached",whitelist_ips:[],blacklist_ips:[],ipsum_folder:"/var/ipsum"},request:{lazy:1,slow:2,onStart:void 0,onDone:void 0,geoip:{enabled:!1,db:"/var/lib/GeoIP/GeoLite2-City.mmdb",local_ips:["127.0.0.1"]}}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:864e5,secure:!0,sameSite:null}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0,level:"silly"},file:{enabled:!0,level:"silly",filename:"/var/log/miolo.log"},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},mail:{silent:!0,options:{port:25,host:"mail.com",authMethod:"PLAIN",secure:!1,tls:{rejectUnauthorized:!1},logger:!1,debug:!1},defaults:{name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},auth:{},render:{},middlewares:[],cron:[]};function le(e){var{options:r,defaults:t,silent:o}=e,n=l.createTransport(r,t);function i(){return(i=te((function*(e){if(!0===o)return console.info("*********************************"),console.info("This mail will not be send (emailing is disabled):"),console.info(e),console.info("*********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var r=n.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(t){return{error:t,ok:!1}}}))).apply(this,arguments)}var a={send:function(e){return i.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),n.verify((function(e,r){e?(console.error("[miolo][Verify][MAILER] Verifying ERROR"),console.error(e)):console.info("[miolo][Verify][MAILER] Verifyed OK: Server is ready to take our messages")}))},options:r,defaults:t,silent:o};return a}var{combine:ce,timestamp:ue,_label:se,printf:de,errors:fe}=w,ve=function(e,r){var t,o,n,i,a,l,p=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",h={silly:u,debug:s,verbose:d,info:f,warn:v,error:m},g={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},y=de((r=>{var t,o=h[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),i="[".concat(p,"] ").concat(o(n)," ").concat(o(g[r.level])," ").concat(r.message);return r.stack?"".concat(i,"\n").concat(r.stack):i})),b=[];!0===(null==e||null===(t=e.console)||void 0===t?void 0:t.enabled)&&b.push(new _.Console({humanReadableUnhandledException:!0,level:(null==e||null===(i=e.console)||void 0===i?void 0:i.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));!0===(null==e||null===(o=e.file)||void 0===o?void 0:o.enabled)&&b.push(new _.File({filename:(null==e||null===(a=e.file)||void 0===a?void 0:a.filename)||"/var/log/miolo.log",level:(null==e||null===(l=e.file)||void 0===l?void 0:l.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(!0===(null==e||null===(n=e.mail)||void 0===n?void 0:n.enabled)){var E=function(e,r){var t=function(t){x.Transport.call(this,t),t=t||{},this.level=e.level||"info",this.ename=(null==e?void 0:e.name)||r.defaults.name,this.to=e.to||r.defaults.to,this.from=e.from||r.defaults.from,this.humanReadableUnhandledException=t.humanReadableUnhandledException||!0,this.handleExceptions=t.handleExceptions||!0,this.json=t.json||!1,this.colorize=t.colorize||!1};return S.inherits(t,x.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n=this,i="",a="";try{try{i=t.message.split("\n")[0]}catch(s){i=t.message.toString()}i=c(i)}catch(d){i="Could not create a title for the error (".concat(d.toString(),")")}try{try{a=c(t.message)}catch(d){a=t.message.toString()}}catch(d){a="Could not create a body for the error (".concat(d.toString(),")")}var l="".concat(null==e?void 0:e.name," [").concat(t.level.toUpperCase(),"] ").concat(i),u={from:this.from,to:this.to,subject:l,text:a};r.send(u,(function(){n.emit("logged"),o(null,!0)}))},t}(e.mail,r);_.MailerLogger=E,b.push(new _.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return R({level:(null==e?void 0:e.level)||"silly",format:ce(fe({stack:!0}),ue(),y),transports:b})},me=(e,r)=>{var t=le(r.mail),o=ve(r.log,t,null==r?void 0:r.name),n=ee(ee({},r.db.options),{},{log:o}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:ee({},r),emailer:t,logger:o,db:i};function c(){return(c=te((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=l},pe=[401];var he="/var/ipsum",ge="ipsum.txt",ye="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",be=1;function Se(e,r){var t=r?r.error:console.error;if(!e)return[];try{var o=[];return e.split("\n").filter((e=>e.indexOf("#")<0)).map((e=>{var[r,t]=e.split("\t");parseInt(t)>=be&&o.push(r)})),o}catch(n){return t("[SERVER][".concat(d("IPsum"),"] Error getting IPs from content")),[]}}function Ee(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:he,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,o=t?t.error:console.error,i=t?t.debug:console.log;if(M.existsSync(e))try{i("[SERVER][".concat(d("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ye,t=arguments.length>2?arguments[2]:void 0,o=t?t.error:console.error;L.get(r,(r=>{var t=[];r.on("data",(e=>{t.push(e)})).on("end",(()=>{var r=Buffer.concat(t).toString();e(r)}))})).on("error",(r=>{o("[SERVER][".concat(d("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((o=>{var a=n.join(e,ge);M.writeFileSync(a,o,{encoding:"utf8",flag:"w"});var l=o.split("\n").length,c=Se(o,t),u=c.length;i("[SERVER][".concat(d("IPsum"),"] File downloaded. ").concat(l," ips on the list (").concat(u," appearing in ").concat(be," or more lists)")),r&&r(c)}))}catch(a){o("[SERVER][".concat(d("IPsum"),"] Error ").concat(a," updating the file"))}else o("[SERVER][".concat(d("IPsum"),"] Folder ").concat(e," does not exist"))}function xe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:he,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,o=t?t.debug:console.log,i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:he,r=arguments.length>1?arguments[1]:void 0,t=r?r.error:console.error;if(!M.existsSync(e))return r&&t("[SERVER][".concat(d("IPsum"),"] Folder ").concat(e," does not exist")),[];var o=n.join(e,ge);return M.existsSync(o)?Se(M.readFileSync(o,{encoding:"utf8"}),r):(r&&t("[SERVER][".concat(d("IPsum"),"] File ").concat(o," does not exist")),[])}(e,t);return i.length>0?(r&&r(i),o("[SERVER][".concat(d("IPsum"),"] File contains ").concat(i.length," ips")),i):(o("[SERVER][".concat(d("IPsum"),"] File is empty. Launching update...")),Ee(e,r,t),[])}var _e=["52.212.247.108","170.106.82.193","54.218.32.58","205.210.31.240 ","134.122.52.203","165.232.105.25"];var Re=i(import.meta.url),we=n.dirname(Re),ke=n.resolve(we,"./miolo.ico"),Oe=n.resolve(we,"../../../.."),Ce=void 0,qe=["127.0.0.1"];var Pe=function(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(qe.indexOf(e)>=0)return{local:!0,country:"",city:""};try{var o,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/var/lib/GeoIP/GeoLite2-City.mmdb",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["127.0.0.1"],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;try{if(null!=Ce)return Ce;qe=[...qe,...r||[]];var o=M.readFileSync(e);return Ce=V.openBuffer(o)}catch(n){return t.error("[geoip] Error initing:"),void t.error(n)}}(null==r?void 0:r.db,null==r?void 0:r.local_ipds,t),i=n.city(e);return{country:i.country.isoCode,city:null===(o=i.city)||void 0===o||null===(o=o.names)||void 0===o?void 0:o.en}}catch(a){t.error("[geoip] Error localizing IP ".concat(e,":")),t.error(a)}return{country:"",city:""}},Me={total:0};var je=i(import.meta.url),Le=n.dirname(je),Ie=j(n.resolve(Le,"./robots.txt"),"utf8");var Je=(e,r,t)=>{var o=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(t||{})}catch(n){}return function(e,r){var t=Math.random().toString(),o=null==e?void 0:e.secret;o||(o="miolo_unsafe_secret",r.error("Guest token made with an unsafe secret string. Please, configure your own through session.secret."));var n={admin:!1,buid:t};return U.encode(n,o)}(t||{},o)};function i(){return i=te((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),o.debug("Guest token conceeded"));var a=function(e){var r,t=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(t)&&(t=86400);var o=new Date;return o.setSeconds(o.getSeconds()+t),{expires:o,httpOnly:!1}}(t);e.cookies.set("token",i,a),e.session={user:{name:"guest"},authenticated:!0,token:i},yield r()})),i.apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))},Te=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=te((function*(r,n){var i;try{i=(e=>{var r,t=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(t)try{t=t.replace("Basic ","");try{t=Buffer.from(t,"base64").toString()}catch(i){t=atob(t)}var[o,n]=t.split(":");return{username:o,password:n}}catch(i){return}})(r.request)}catch(c){}var a=()=>{r.session={user:void 0,authenticated:!1},r.body={user:void 0,authenticated:!1},r.response.status=401,r.response.headers["WWW-Authenticate"]='Basic realm="'+o.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield t(i.username,i.password,e.context.miolo);if(!1===l||null==l)return a();r.session={user:l,authenticated:!0},yield n()}))).apply(this,arguments)}o||(o="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(I(r,i))))},Fe=new D;var Ve=(e,r,t)=>r(null,e.id),Ae=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},Ue=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},Ne=(e,r,t)=>{var{get_user_id:o,find_user_by_id:n,local_auth_user:i,url_login:a,url_logout:l,url_login_redirect:c,url_logout_redirect:u}=r,s=o||Ve,d=n||Ae,f=i||Ue,v=a||"/login",m=l||"/logout",p=new z.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));function h(){return(h=te((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(t){}yield r()}))).apply(this,arguments)}!function(e,r){e.keys=[r.secret||"*secret*"];var t=ee({store:Fe},r.options||{});e.use(B(t,e))}(e,t),N.serializeUser(((r,t)=>{process.nextTick((function(){s(r,t,e.context.miolo)}))})),N.deserializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),N.use(p),e.use(N.initialize()),e.use(N.session()),e.use((function(e,r){return h.apply(this,arguments)}));var g=function(){var e=te((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,yield e.logout(),e.body={user:void 0,authenticated:!1},null!=u&&e.redirect(u)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,t){return e.apply(this,arguments)}}(),y=new A;y.post(v,((e,r)=>N.authenticate("local",function(){var r=te((function*(r,t,o,n){if(!1!==t)return e.session.user=e.state.user,e.session.authenticated=!0,e.body={user:t,authenticated:!0},null!=c&&e.redirect(c),yield e.login(t);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:o,error:r},e.response.status=401}));return function(e,t,o,n){return r.apply(this,arguments)}}())(e))),y.get(m,g),y.post(m,g),e.use(y.routes())},ze=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},Be=(e,r)=>{var t=e.context.miolo.logger;ze(r,"cors",(r=>{if("simple"==r)t.debug("Setting CORS the simple way"),e.use(function(){var e=te((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,t){return e.apply(this,arguments)}}());else{var o=(e=>"object"==typeof e?e:{})(r);t.debug("Setting CORS headers for ".concat(JSON.stringify(o))),e.use(G(o))}})),ze(r,"proxy",(r=>{var[o,n]=(e=>{var r,t,o,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(t=e)||void 0===t?void 0:t.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(o=e)||void 0===o?void 0:o.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);t.debug("Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(W(o,n))}))},De=function(){var e=te((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Ge=function(){var e=te((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),We={require:!1,action:"redirect",redirect_url:"/",error_code:401},Ye={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},He=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.bodyField)||(null==e?void 0:e.bodyField),a=(null==r?void 0:r.before)||(null==e?void 0:e.before)||De,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Ge,c=o(We,(null==e?void 0:e.auth)||{},(null==r?void 0:r.auth)||{}),u=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var f={name:d.name,url:(null==d?void 0:d.url)||d.name,mode:(null==d?void 0:d.mode)||"rw",bodyField:(null==d?void 0:d.bodyField)||i,useUserFields:o(Ye,(null==d?void 0:d.useUserFields)||{}),auth:o(c,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};u.push(f)}}u.length>0&&t.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),t};function Ke(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?Y.parse(r):{}}function Xe(e,r,t,o){t.map((t=>{var n=t.prefix;t.routes.map((t=>{var i=e.getModel(t.name);if(i){for(var a=function(){var e=te((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=t.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(o.error("[miolo-router] Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(o.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(o.error("[miolo-router] Crud path ".concat(t.url," specified auth but no action")),e.body={})),i)}));return function(r,t){return e.apply(this,arguments)}}(),l=function(){var e=te((function*(e,r,n){var i,l={};try{var c;if(!(yield a(e,r)))return void(e.body={});var u=!0;if(null!=t&&t.before&&(u=yield t.before(e)),!u)return void(e.body={});var s=null==e||null===(c=e.session)||void 0===c||null===(c=c.user)||void 0===c?void 0:c.id,d={};!0===t.useUserFields.use&&(d=t.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield n(f),null!=t&&t.after&&(l=yield t.after(e,l))}catch(v){o.error("[miolo-router] Unexpected error on CRUD ".concat(t.name,"-").concat(r)),o.error(v)}i=l,l=null==t.bodyField?i:{[t.bodyField]:i},e.body=l}));return function(r,t,o){return e.apply(this,arguments)}}(),c=function(){var e=te((function*(e){yield l(e,"r",function(){var r=te((function*(r){var t=Ke(e.request.url),o={transaction:void 0};return yield i.read(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=te((function*(e){yield l(e,"r",function(){var r=te((function*(r){var t=Ke(e.request.url),o={transaction:void 0};return yield i.keyList(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=te((function*(e){yield l(e,"r",function(){var r=te((function*(r){var t=Ke(e.request.url),o={transaction:void 0};return yield i.find(t.id,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=te((function*(e){yield l(e,"r",function(){var r=te((function*(r){var t=Ke(e.request.url),o={transaction:void 0};return yield i.distinct(t.distinct_field,t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=te((function*(e){yield l(e,"w",function(){var r=te((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.created_by&&(o[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(o,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=te((function*(e){yield l(e,"w",function(){var r=te((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.last_update_by&&(o[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(o,{id:o.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=function(){var e=te((function*(e){yield l(e,"w",function(){var r=te((function*(r){var t=e.request.fields,o={transaction:void 0};return yield i.delete({id:t.id},o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=n?"/".concat(n,"/").concat(t.url):"/".concat(t.url);p.indexOf("//")>=0;)p=p.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(t.name," to ").concat(p));var h=t.mode.indexOf("r")>=0,g=t.mode.indexOf("w")>=0,y=t.mode.indexOf("u")>=0||g;h&&(r.get("".concat(p,"/find"),(e=>s(e))),r.get("".concat(p,"/read"),(e=>c(e))),r.get("".concat(p,"/distinct"),(e=>d(e))),r.get("".concat(p,"/key_list"),(e=>u(e)))),y&&(r.post("".concat(p,"/save"),(e=>f(e))),r.post("".concat(p,"/update"),(e=>v(e)))),g&&r.post("".concat(p,"/delete"),(e=>m(e)))}else o.error("[miolo-router] Could not get model for ".concat(t.name))}))}))}var Ze=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.before)||(null==e?void 0:e.before)||De,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Ge,l=o(We,(null==r?void 0:r.auth)||{},(null==e?void 0:e.auth)||{}),c=[];for(var u of n)if(u.url&&u.callback){var s={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:u.callback,auth:o(l,(null==u?void 0:u.auth)||{}),before:(null==u?void 0:u.before)||i,after:(null==u?void 0:u.after)||a};c.push(s)}t.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),t};function Qe(e,r,t){var o=e.context.miolo.logger,n=new A;try{var i=He(t),a=Ze(t),l=i.length>0,c=a.length>0;if(!l&&!c)throw"[miolo-router] Could not get any route from the passed <routes> param";l&&Xe(r,n,i,o),c&&function(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n,i=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");t.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i));var a=function(){var e=te((function*(e){var o,n=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"POST"===r.method)||(n||("error"==i.action?(t.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(t.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(t.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=te((function*(e){var o={};try{try{var n;if("GET"==r.method&&(null===(n=e.request)||void 0===n||!n.fields)&&e.request.url.indexOf("?")>0){var i=Ke(e.request.url);i&&(e.request.fields=i)}}catch(c){t.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield a(e)))return;var l=!0;if(null!=r&&r.before&&(l=yield r.before(e)),!l)return;o=yield r.callback(e),null!=r&&r.after&&(o=yield r.after(e,o))}catch(u){t.error("[miolo-router] Unexpected error on Query ".concat(r.name)),t.error(u)}return o}));return function(r){return e.apply(this,arguments)}}(),c=r.method.toLowerCase();e[c](i,(e=>l(e,r)))}))}))}(n,a,o)}catch(u){o.error(u),o.error("[miolo-router] Error initing the router. Probably config objects are not ok"),o.error("[miolo-router] connOrConfig:"),o.error(null==r?void 0:r.config),o.error("[miolo-router] routes:"),o.error(t)}e.use(n.routes())}var $e=i(import.meta.url),er=n.dirname($e),rr=j(n.resolve(er,"fallback_index.html"),"utf8");function tr(e){return e?e/1e6:0}function or(e){return e?e/1e6:0}function nr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(tr(X.freemem()),2),n=Math.round(tr(X.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")):t.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")),Z.check("/",(function(e,r){var o=Math.round(or(r.used),2),n=Math.round(or(r.total),2),i=Math.round(or(r.free),2);i<1?t.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)")):t.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function ir(e,r){var t=e.context.miolo,o=t.logger,n=[nr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Ee(e.config.ratelimit.ipsum_folder||he,(r=>{e.logger.info("[SERVER][".concat(d("IPsum"),"] File downloaded. ").concat(p(r.length)," ips will be ").concat(f("blacklisted"),"!"))}),e.logger)},start:!0},...r||[]],i=[];n.map((e=>{var r=e.name,o=function(e,r){var t,o=e.logger,n=null!=r&&null!==(t=r.onTick)&&void 0!==t&&t.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new K((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{try{o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(y("ticks!"))),r.onTick(e,t)}catch(n){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(y("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),o.error(t)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,running:!0===(null==e?void 0:e.start)})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||o.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),o.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(y("manually started!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),o.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function ar(n,i){var a,l,c,u=new r,v=function(e){var r,t=o(ae,e);return t.auth_type=function(e){var r,t,o;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.credentials?"credentials":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.custom?"custom":"guest"}(e),t.use_catcher=!(null==t||null===(r=t.http)||void 0===r||!r.catcher_url),t}(n);me(u,v),Be(u,v.http),(e=>{e.use(C({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:q.Z_SYNC_FLUSH},deflate:{flush:q.Z_SYNC_FLUSH},br:!1})),e.use(O(k({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(u),function(e){var r=e.context.miolo.logger;function t(){return(t=te((function*(e){if(e){var t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),pe.indexOf(t)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(t,": ").concat(e.message)):r.error(e),this.headerSent||!this.writable)return r.debug("headers were already sent, returning early"),void(e.headerSent=!0);this.type="json",this.status=t,this.body=JSON.stringify(this.body||"",null,2),this.length=Buffer.byteLength(this.body),this.res.end(this.body)}}))).apply(this,arguments)}e.context.onerror=function(e){return t.apply(this,arguments)}}(u),function(e,r){var t=e.context.miolo,o=e=>e.headers["x-real-ip"]||e.ip||"127.0.0.1",n=xe(null==r?void 0:r.ipsum_folder,void 0,t.logger),i={driver:"memory",db:new Map,id:o,headers:{remaining:"Rate-Limit-Remaining",reset:"Rate-Limit-Reset",total:"Rate-Limit-Total"},disableHeader:!1,max:(null==r?void 0:r.max)||1e3,duration:(null==r?void 0:r.duration)||6e4,errorMessage:(null==r?void 0:r.errorMessage)||"Rate Limit reached",whitelist:(null==r?void 0:r.whitelist)||(e=>{var t=(null==r?void 0:r.whitelist_ips)||[];return!!t&&t.indexOf(o(e))>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var t=o(e),i=[...n,..._e,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(t)>=0;return i&&e.miolo.logger.info("Rejecting ".concat(f("blacklisted")," ").concat(s(t))),i})};e.use(P(i))}(u,null===(a=v.http)||void 0===a?void 0:a.ratelimit),((e,r)=>{var{favicon:t,folders:o}=r,n=t||ke;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(Oe,""))),e.use(T(n)),Object.entries(o)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(Oe,""))),e.use(I(i,J(a,{index:!1})))})(u,null===(l=v.http)||void 0===l?void 0:l.static),function(e,r){var t=function(){var e=te((function*(e,r){return{}}));return function(r,t){return e.apply(this,arguments)}}(),o=function(){var e=te((function*(e,r,t){}));return function(r,t,o){return e.apply(this,arguments)}}(),n={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2,onStart:(null==r?void 0:r.onStart)||t,onDone:(null==r?void 0:r.onDone)||o,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=te((function*(e,r){var t,o,i,a,l,c,u=e.miolo.logger,v=e.headers["x-real-ip"]||"127.0.0.1",g=F.now();e.request.body=ee(ee({},e.request.fields),e.request.files),Me.total+=1,Me[v]=(Me[v]||0)+1,e.requestId=Me.total,e.request.ip=v;var y=!0===(null==n||null===(t=n.geoip)||void 0===t?void 0:t.enabled),b={};y&&(b=Pe(v,n.geoip,u)),e.request.geoip=b;var S=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,E=y?!0===(null===(o=b)||void 0===o?void 0:o.local)?"":null!==(i=b)&&void 0!==i&&i.country?null!==(a=b)&&void 0!==a&&a.city?" (".concat(null===(l=b)||void 0===l?void 0:l.city,", ").concat(b.country,")"):" (".concat(b.country,")"):"":"",x="".concat(s(v)).concat(E," ").concat(d(e.request.method)," ").concat(d(S)," [").concat(h(Me[v]),"/").concat(h(e.requestId),"]"),_=null!=e.request.body?JSON.stringify(e.request.body):"";u.info("".concat(x," - START")),u.debug("".concat(x," - Body: ").concat(_));var R=yield n.onStart(e,{started:g,description:"pending"});yield r();var w=null==e||null===(c=e.session)||void 0===c?void 0:c.user,k="";null!=w&&(null!=w&&w.id?k=" - uid ".concat(null==w?void 0:w.id):null!=w&&w.token&&(k=" - token ".concat(null==w?void 0:w.token)));var O,C=e.response.status,q=C;200==C?O=p:C>200&&C<=299?(O=f,e.response.redirected&&e.response.url&&(q+=" -> ".concat(e.response.url))):O=m;var P="[".concat(O(q),"]"),M=parseFloat((F.now()-g)/1e3).toFixed(2),j=M<n.lazy?p:M<n.slow?f:m,L=M<n.lazy?"Ok":M<n.slow?"lazy":"slow",I=null!=e.session?JSON.stringify(e.session):"";u.debug("".concat(x," - Session: ").concat(I));var J=null!=e.body?JSON.stringify(e.body):"";u.debug("".concat(x," - Response: ").concat(J)),yield n.onDone(e,R,{started:g,elapsed:M,description:L}),u.info("".concat(x," - DONE ").concat(P).concat(k," (").concat(j(L),": ").concat(j(M),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(u,null==v||null===(c=v.http)||void 0===c?void 0:c.request),function(e){function r(){return(r=te((function*(e){e.body=Ie}))).apply(this,arguments)}var t=new A;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(u),v.use_catcher&&function(e,r){function t(){return t=te((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(f("[JS Warning]")," on ").concat(g(o),": ").concat(JSON.stringify(t.msg),"\n")+"".concat(f("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(m("[JS Error]")," on ").concat(g(o),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(m("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(m("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(m("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(m("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(m("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),t.apply(this,arguments)}var o=new A;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(u,v.http.catcher_url),"guest"==v.auth_type&&Je(u,v.auth.guest,null==v?void 0:v.session),"basic"==v.auth_type&&Te(u,v.auth.basic),"credentials"==v.auth_type&&Ne(u,v.auth.credentials,null==v?void 0:v.session),"custom"==v.auth_type&&((e,r)=>{var t=e.context.miolo.logger;try{var o=r(e);if("function"==typeof o)e.use(o);else if(Array.isArray(o)){var n=new A;o.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){t.error("Custom auth error: ".concat(i,"'"))}})(u,v.auth.custom);var y=null==v?void 0:v.middlewares;if(y&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(u,y),null!=v&&v.routes){var b=u.context.miolo.db.getConnection();Qe(u,b,v.routes)}null!=(null==i?void 0:i.middleware)?u.use(i.middleware):function(e,r,t,o){var n=(null==r?void 0:r.html)||rr;n.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),n.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var i=function(){var e=te((function*(e){var t={};try{var o;null!=r&&null!==(o=r.ssr)&&void 0!==o&&o.loader&&(t=yield r.ssr.loader(e))}catch(c){var n,i="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(n=e.request)||void 0===n?void 0:n.fields)||{})),a=null!=c&&c.stack?"".concat(c.toString(),"\n").concat(c.stack):c.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return t}));return function(r){return e.apply(this,arguments)}}(),a=(e,r,t)=>{var o,n,i=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:t,extra:null==e?void 0:e.extra}},l=(e,t)=>{var o="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?o=H(r.ssr.renderer(e,t)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware):\n".concat(a.toString())),o="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(t,null,2)).replace("{children}",o)};function c(){return(c=te((function*(e){var r,n,c={hostname:null==t?void 0:t.hostname,port:null==t?void 0:t.port,catcher_url:null==t?void 0:t.catcher_url,login_url:null==o||null===(r=o.credentials)||void 0===r?void 0:r.url_login,logout_url:null==o||null===(n=o.credentials)||void 0===n?void 0:n.url_logout},u=yield i(e),s=a(e,c,u),d=l(e,s);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(d,"utf8")," bytes")),e.body=d}))).apply(this,arguments)}e.use((function(e){return c.apply(this,arguments)}))}(u,i,v.http,null==v?void 0:v.auth);var S=function(){var r=te((function*(){var r=e.createServer(u.callback());yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(r,v.http.port,v.http.hostname),u.context.miolo.logger.info("miolo is listening on ".concat(v.http.hostname,":").concat(v.http.port)),u.server=r;var o=t({server:r});return u.stop_server=te((function*(){yield o.terminate(),u.context.miolo.logger.info("miolo has been shutdowned from ".concat(v.http.hostname,":").concat(v.http.port))})),ir(u,null==v?void 0:v.cron),u}));return function(){return r.apply(this,arguments)}}();return u.run=S,u}function lr(e){var r=Q.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(s("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof Q.ReplyError?"".concat(s("REDIS")," ").concat(m("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(m("Error "+e.code)," ").concat(e.toString())}catch(t){r="".concat(s("REDIS")," ").concat(m("Error ")," ").concat(t)}console.error(r)})),t=E(r.get).bind(r),o=E(r.exists).bind(r),n=E(r.set).bind(r),i=E(r.del).bind(r);function a(){return(a=te((function*(e){return yield t(e)}))).apply(this,arguments)}function l(){return(l=te((function*(e){return 1==(yield o(e))}))).apply(this,arguments)}function c(){return c=te((function*(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",t))})),c.apply(this,arguments)}function u(){return(u=te((function*(e){return(yield i(e))>=1}))).apply(this,arguments)}var d={get:function(e){return a.apply(this,arguments)},exists:function(e){return l.apply(this,arguments)},set:function(e,r){return c.apply(this,arguments)},del:function(e){return u.apply(this,arguments)}};return d}export{ar as miolo,lr as miolo_cacher,le as miolo_emailer,ve as miolo_logger};
11
+ import e from"node:http";import r from"koa";import{createHttpTerminator as o}from"http-terminator";import t from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import l from"nodemailer";import{uncolor as c,gray as u,magenta as s,cyan as d,yellow as f,red_light as v,red as m,green as p,cyan_light as h,blue as g,green_bold as y,yellow_bold as b}from"tinguir";import S,{promisify as E}from"node:util";import x,{transports as _,createLogger as R,format as w}from"winston";import k,{readFileSync as O}from"node:fs";import C from"koa-better-body";import q from"koa-convert";import P from"koa-compress";import{constants as M}from"node:zlib";import j from"koa-ratelimit";import I from"node:https";import L from"koa-mount";import T from"koa-static";import F from"koa-favicon";import{performance as J}from"node:perf_hooks";import{Reader as V}from"@maxmind/geoip2-node";import U from"@koa/router";import N from"jwt-simple";import A from"koa-passport";import z from"passport-local";import B from"koa-session";import D from"koa-redis";import G from"@koa/cors";import W from"koa-proxies";import H from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as K}from"cron";import X from"node:os";import Z from"diskspace";import Q from"redis";function $(e,r){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),o.push.apply(o,t)}return o}function ee(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?$(Object(o),!0).forEach((function(r){te(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):$(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function re(e,r,o,t,n,i,a){try{var l=e[i](a),c=l.value}catch(u){return void o(u)}l.done?r(c):Promise.resolve(c).then(t,n)}function oe(e){return function(){var r=this,o=arguments;return new Promise((function(t,n){var i=e.apply(r,o);function a(e){re(i,t,n,a,l,"next",e)}function l(e){re(i,t,n,a,l,"throw",e)}a(void 0)}))}}function te(e,r,o){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var t=o.call(e,r||"default");if("object"!=typeof t)return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"==typeof r?r:String(r)}(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var ne=i(import.meta.url),ie=n.dirname(ne),ae={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(ie,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,ratelimit:{max:1e3,duration:6e4,errorMessage:"Rate Limit reached",whitelist_ips:[],blacklist_ips:[],ipsum_folder:"/var/ipsum"},request:{lazy:1,slow:2,onStart:void 0,onDone:void 0,geoip:{enabled:!1,db:"/var/lib/GeoIP/GeoLite2-City.mmdb",local_ips:["127.0.0.1"]}}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:864e5,secure:!0,sameSite:null}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0,level:"silly"},file:{enabled:!0,level:"silly",filename:"/var/log/miolo.log"},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},mail:{silent:!0,options:{port:25,host:"mail.com",authMethod:"PLAIN",secure:!1,tls:{rejectUnauthorized:!1},logger:!1,debug:!1},defaults:{name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},auth:{},render:{},middlewares:[],cron:[]};function le(e){var{options:r,defaults:o,silent:t}=e,n=l.createTransport(r,o);function i(){return(i=oe((function*(e){if(!0===t)return console.info("*********************************"),console.info("This mail will not be send (emailing is disabled):"),console.info(e),console.info("*********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var r=n.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(o){return{error:o,ok:!1}}}))).apply(this,arguments)}var a={send:function(e){return i.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),n.verify((function(e,r){e?(console.error("[miolo][Verify][MAILER] Verifying ERROR"),console.error(e)):console.info("[miolo][Verify][MAILER] Verifyed OK: Server is ready to take our messages")}))},options:r,defaults:o,silent:t};return a}function ce(e){process.on("SIGHUP",(function(){var r=n.join(e.dirname,e._getFile(!1));console.log("[miolo][file-logger] SIGHUP received. Check if we need to re-open log file ".concat(r,"...")),k.stat(r,(function(o){if(o&&"ENOENT"==o.code)return function(){console.log("[miolo][file-logger] Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroySoon());var o=k.createWriteStream(r,e.options);o.setMaxListeners(1/0),e._size=0,e._stream=o,e.once("flush",(function(){e.opening=!1,e.emit("open",r)})),e.flush(),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(t){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(t.toString()))}}()}))}))}var{combine:ue,timestamp:se,_label:de,printf:fe,errors:ve}=w,me=function(e,r){var o,t,n,i,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",l={silly:u,debug:s,verbose:d,info:f,warn:v,error:m},p={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},h=fe((r=>{var o,t=l[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(o=e.format)||void 0===o?void 0:o.locale)||"en"),i="[".concat(a,"] ").concat(t(n)," ").concat(t(p[r.level])," ").concat(r.message);return r.stack?"".concat(i,"\n").concat(r.stack):i})),g=[];!0===(null==e||null===(o=e.console)||void 0===o?void 0:o.enabled)&&g.push(new _.Console({humanReadableUnhandledException:!0,level:(null==e||null===(i=e.console)||void 0===i?void 0:i.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(t=e.file)||void 0===t?void 0:t.enabled)){var y,b,E=new _.File({filename:(null==e||null===(y=e.file)||void 0===y?void 0:y.filename)||"/var/log/miolo.log",level:(null==e||null===(b=e.file)||void 0===b?void 0:b.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0});ce(E),g.push(E)}if(!0===(null==e||null===(n=e.mail)||void 0===n?void 0:n.enabled)){var w=function(e,r){var o=function(o){x.Transport.call(this,o),o=o||{},this.level=e.level||"info",this.ename=(null==e?void 0:e.name)||r.defaults.name,this.to=e.to||r.defaults.to,this.from=e.from||r.defaults.from,this.humanReadableUnhandledException=o.humanReadableUnhandledException||!0,this.handleExceptions=o.handleExceptions||!0,this.json=o.json||!1,this.colorize=o.colorize||!1};return S.inherits(o,x.Transport),o.prototype.name="MailerLogger",o.prototype.log=function(o,t){var n=this,i="",a="";try{try{i=o.message.split("\n")[0]}catch(s){i=o.message.toString()}i=c(i)}catch(d){i="Could not create a title for the error (".concat(d.toString(),")")}try{try{a=c(o.message)}catch(d){a=o.message.toString()}}catch(d){a="Could not create a body for the error (".concat(d.toString(),")")}var l="".concat(null==e?void 0:e.name," [").concat(o.level.toUpperCase(),"] ").concat(i),u={from:this.from,to:this.to,subject:l,text:a};r.send(u,(function(){n.emit("logged"),t(null,!0)}))},o}(e.mail,r);_.MailerLogger=w,g.push(new _.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return R({level:(null==e?void 0:e.level)||"silly",format:ue(ve({stack:!0}),se(),h),transports:g})},pe=(e,r)=>{var o=le(r.mail),t=me(r.log,o,null==r?void 0:r.name),n=ee(ee({},r.db.options),{},{log:t}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:ee({},r),emailer:o,logger:t,db:i};function c(){return(c=oe((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=l},he=[401,403];var ge="/var/ipsum",ye="ipsum.txt",be="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",Se=1;function Ee(e,r){var o=r?r.error:console.error;if(!e)return[];try{var t=[];return e.split("\n").filter((e=>e.indexOf("#")<0)).map((e=>{var[r,o]=e.split("\t");parseInt(o)>=Se&&t.push(r)})),t}catch(n){return o("[SERVER][".concat(d("IPsum"),"] Error getting IPs from content")),[]}}function xe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ge,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,t=o?o.error:console.error,i=o?o.debug:console.log;if(k.existsSync(e))try{i("[SERVER][".concat(d("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:be,o=arguments.length>2?arguments[2]:void 0,t=o?o.error:console.error;I.get(r,(r=>{var o=[];r.on("data",(e=>{o.push(e)})).on("end",(()=>{var r=Buffer.concat(o).toString();e(r)}))})).on("error",(r=>{t("[SERVER][".concat(d("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((t=>{var a=n.join(e,ye);k.writeFileSync(a,t,{encoding:"utf8",flag:"w"});var l=t.split("\n").length,c=Ee(t,o),u=c.length;i("[SERVER][".concat(d("IPsum"),"] File downloaded. ").concat(l," ips on the list (").concat(u," appearing in ").concat(Se," or more lists)")),r&&r(c)}))}catch(a){t("[SERVER][".concat(d("IPsum"),"] Error ").concat(a," updating the file"))}else t("[SERVER][".concat(d("IPsum"),"] Folder ").concat(e," does not exist"))}function _e(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ge,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,t=o?o.debug:console.log,i=o?o.warn:console.log,a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ge,r=arguments.length>1?arguments[1]:void 0,o=r?r.error:console.error;if(!k.existsSync(e))return r&&o("[SERVER][".concat(d("IPsum"),"] Folder ").concat(e," does not exist")),[];var t=n.join(e,ye);return k.existsSync(t)?Ee(k.readFileSync(t,{encoding:"utf8"}),r):(r&&o("[SERVER][".concat(d("IPsum"),"] File ").concat(t," does not exist")),[])}(e,o);return a.length>0?(r&&r(a),t("[SERVER][".concat(d("IPsum"),"] File contains ").concat(a.length," ips")),a):(i("[SERVER][".concat(d("IPsum"),"] File is empty. Launching update...")),xe(e,r,o),[])}var Re=["52.212.247.108","54.218.32.58","170.106.82.193","110.166.71.39","205.210.31.240 ","134.122.52.203","165.232.105.25","66.249.73.200","35.206.153.204","199.244.88.227","198.12.222.107"];var we=i(import.meta.url),ke=n.dirname(we),Oe=n.resolve(ke,"./miolo.ico"),Ce=n.resolve(ke,"../../../.."),qe=void 0,Pe=["127.0.0.1"];var Me=function(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(Pe.indexOf(e)>=0)return{local:!0,country:"",city:""};try{var t,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/var/lib/GeoIP/GeoLite2-City.mmdb",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["127.0.0.1"],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;try{if(null!=qe)return qe;Pe=[...Pe,...r||[]];var t=k.readFileSync(e);return qe=V.openBuffer(t)}catch(n){return o.error("[geoip] Error initing:"),void o.error(n)}}(null==r?void 0:r.db,null==r?void 0:r.local_ipds,o),i=n.city(e);return{country:i.country.isoCode,city:null===(t=i.city)||void 0===t||null===(t=t.names)||void 0===t?void 0:t.en}}catch(a){o.error("[geoip] Error localizing IP ".concat(e,":")),o.error(a)}return{country:"",city:""}},je={total:0};var Ie=i(import.meta.url),Le=n.dirname(Ie),Te=O(n.resolve(Le,"./robots.txt"),"utf8");var Fe=(e,r,o)=>{var t=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(o||{})}catch(n){}return function(e,r){var o=Math.random().toString(),t=null==e?void 0:e.secret;t||(t="miolo_unsafe_secret",r.error("Guest token made with an unsafe secret string. Please, configure your own through session.secret."));var n={admin:!1,buid:o};return N.encode(n,t)}(o||{},t)};function i(){return i=oe((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),t.debug("Guest token conceeded"));var a=function(e){var r,o=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(o)&&(o=86400);var t=new Date;return t.setSeconds(t.getSeconds()+o),{expires:t,httpOnly:!1}}(o);e.cookies.set("token",i,a),e.session={user:{name:"guest"},authenticated:!0,token:i},yield r()})),i.apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))},Je=(e,r)=>{var{auth_user:o,realm:t,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=oe((function*(r,n){var i;try{i=(e=>{var r,o=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(o)try{o=o.replace("Basic ","");try{o=Buffer.from(o,"base64").toString()}catch(i){o=atob(o)}var[t,n]=o.split(":");return{username:t,password:n}}catch(i){return}})(r.request)}catch(c){}var a=()=>{r.session={user:void 0,authenticated:!1},r.body={user:void 0,authenticated:!1},r.response.status=401,r.response.headers["WWW-Authenticate"]='Basic realm="'+t.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield o(i.username,i.password,e.context.miolo);if(!1===l||null==l)return a();r.session={user:l,authenticated:!0},yield n()}))).apply(this,arguments)}t||(t="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(L(r,i))))},Ve=new D;var Ue=(e,r,o)=>r(null,e.id),Ne=(e,r,o)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},Ae=(e,r,o,t)=>{o(Error("You need to define auth.passport.local_auth_user"),null)},ze=(e,r,o)=>{var{get_user_id:t,find_user_by_id:n,local_auth_user:i,url_login:a,url_logout:l,url_login_redirect:c,url_logout_redirect:u}=r,s=t||Ue,d=n||Ne,f=i||Ae,v=a||"/login",m=l||"/logout",p=new z.Strategy(((r,o,t)=>{f(r,o,t,e.context.miolo)}));function h(){return(h=oe((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(o){}yield r()}))).apply(this,arguments)}!function(e,r){e.keys=[r.secret||"*secret*"];var o=ee({store:Ve},r.options||{});e.use(B(o,e))}(e,o),A.serializeUser(((r,o)=>{process.nextTick((function(){s(r,o,e.context.miolo)}))})),A.deserializeUser(((r,o)=>{process.nextTick((function(){d(r,o,e.context.miolo)}))})),A.use(p),e.use(A.initialize()),e.use(A.session()),e.use((function(e,r){return h.apply(this,arguments)}));var g=function(){var e=oe((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,yield e.logout(),e.body={user:void 0,authenticated:!1},null!=u&&e.redirect(u)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,o){return e.apply(this,arguments)}}(),y=new U;y.post(v,((e,r)=>A.authenticate("local",function(){var r=oe((function*(r,o,t,n){if(!1!==o)return e.session.user=e.state.user,e.session.authenticated=!0,e.body={user:o,authenticated:!0},null!=c&&e.redirect(c),yield e.login(o);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:t,error:r},e.response.status=401}));return function(e,o,t,n){return r.apply(this,arguments)}}())(e))),y.get(m,g),y.post(m,g),e.use(y.routes())},Be=(e,r,o)=>{try{var t=e[r];if(null!=t&&0!=t)return o(t)}catch(n){}},De=(e,r)=>{var o=e.context.miolo.logger;Be(r,"cors",(r=>{if("simple"==r)o.debug("Setting CORS the simple way"),e.use(function(){var e=oe((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,o){return e.apply(this,arguments)}}());else{var t=(e=>"object"==typeof e?e:{})(r);o.debug("Setting CORS headers for ".concat(JSON.stringify(t))),e.use(G(t))}})),Be(r,"proxy",(r=>{var[t,n]=(e=>{var r,o,t,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(o=e)||void 0===o?void 0:o.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(t=e)||void 0===t?void 0:t.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);o.debug("Setting Proxy for ".concat(t," to ").concat(n.target," ")),e.use(W(t,n))}))},Ge=function(){var e=oe((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),We=function(){var e=oe((function*(e,r){return r}));return function(r,o){return e.apply(this,arguments)}}(),He={require:!1,action:"redirect",redirect_url:"/",error_code:401},Ye={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Ke=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var o=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.bodyField)||(null==e?void 0:e.bodyField),a=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ge,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||We,c=t(He,(null==e?void 0:e.auth)||{},(null==r?void 0:r.auth)||{}),u=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var f={name:d.name,url:(null==d?void 0:d.url)||d.name,mode:(null==d?void 0:d.mode)||"rw",bodyField:(null==d?void 0:d.bodyField)||i,useUserFields:t(Ye,(null==d?void 0:d.useUserFields)||{}),auth:t(c,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};u.push(f)}}u.length>0&&o.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),o};function Xe(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?H.parse(r):{}}function Ze(e,r,o,t){o.map((o=>{var n=o.prefix;o.routes.map((o=>{var i=e.getModel(o.name);if(i){for(var a=function(){var e=oe((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=o.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(t.error("[miolo-router] Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(t.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(t.error("[miolo-router] Crud path ".concat(o.url," specified auth but no action")),e.body={})),i)}));return function(r,o){return e.apply(this,arguments)}}(),l=function(){var e=oe((function*(e,r,n){var i,l={};try{var c;if(!(yield a(e,r)))return void(e.body={});var u=!0;if(null!=o&&o.before&&(u=yield o.before(e)),!u)return void(e.body={});var s=null==e||null===(c=e.session)||void 0===c||null===(c=c.user)||void 0===c?void 0:c.id,d={};!0===o.useUserFields.use&&(d=o.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield n(f),null!=o&&o.after&&(l=yield o.after(e,l))}catch(v){t.error("[miolo-router] Unexpected error on CRUD ".concat(o.name,"-").concat(r)),t.error(v)}i=l,l=null==o.bodyField?i:{[o.bodyField]:i},e.body=l}));return function(r,o,t){return e.apply(this,arguments)}}(),c=function(){var e=oe((function*(e){yield l(e,"r",function(){var r=oe((function*(r){var o=Xe(e.request.url),t={transaction:void 0};return yield i.read(o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=oe((function*(e){yield l(e,"r",function(){var r=oe((function*(r){var o=Xe(e.request.url),t={transaction:void 0};return yield i.keyList(o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=oe((function*(e){yield l(e,"r",function(){var r=oe((function*(r){var o=Xe(e.request.url),t={transaction:void 0};return yield i.find(o.id,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=oe((function*(e){yield l(e,"r",function(){var r=oe((function*(r){var o=Xe(e.request.url),t={transaction:void 0};return yield i.distinct(o.distinct_field,o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=oe((function*(e){yield l(e,"w",function(){var r=oe((function*(r){var o,t=e.request.fields;null!=r&&null!==(o=r.fieldNames)&&void 0!==o&&o.created_by&&(t[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(t,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=oe((function*(e){yield l(e,"w",function(){var r=oe((function*(r){var o,t=e.request.fields;null!=r&&null!==(o=r.fieldNames)&&void 0!==o&&o.last_update_by&&(t[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(t,{id:t.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=function(){var e=oe((function*(e){yield l(e,"w",function(){var r=oe((function*(r){var o=e.request.fields,t={transaction:void 0};return yield i.delete({id:o.id},t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=n?"/".concat(n,"/").concat(o.url):"/".concat(o.url);p.indexOf("//")>=0;)p=p.replace(/\/\//g,"/");t.info("[miolo-router] Routing table ".concat(o.name," to ").concat(p));var h=o.mode.indexOf("r")>=0,g=o.mode.indexOf("w")>=0,y=o.mode.indexOf("u")>=0||g;h&&(r.get("".concat(p,"/find"),(e=>s(e))),r.get("".concat(p,"/read"),(e=>c(e))),r.get("".concat(p,"/distinct"),(e=>d(e))),r.get("".concat(p,"/key_list"),(e=>u(e)))),y&&(r.post("".concat(p,"/save"),(e=>f(e))),r.post("".concat(p,"/update"),(e=>v(e)))),g&&r.post("".concat(p,"/delete"),(e=>m(e)))}else t.error("[miolo-router] Could not get model for ".concat(o.name))}))}))}var Qe=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var o=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ge,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||We,l=t(He,(null==r?void 0:r.auth)||{},(null==e?void 0:e.auth)||{}),c=[];for(var u of n)if(u.url&&u.callback){var s={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:u.callback,auth:t(l,(null==u?void 0:u.auth)||{}),before:(null==u?void 0:u.before)||i,after:(null==u?void 0:u.after)||a};c.push(s)}o.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),o};function $e(e,r,o){var t=e.context.miolo.logger,n=new U;try{var i=Ke(o),a=Qe(o),l=i.length>0,c=a.length>0;if(!l&&!c)throw"[miolo-router] Could not get any route from the passed <routes> param";l&&Ze(r,n,i,t),c&&function(e,r,o){r.map((r=>{var t=r.prefix;r.routes.map((r=>{for(var n,i=t?"/".concat(t,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");o.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i));var a=function(){var e=oe((function*(e){var t,n=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"POST"===r.method)||(n||("error"==i.action?(o.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(o.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(o.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=oe((function*(e){var t={};try{try{var n;if("GET"==r.method&&(null===(n=e.request)||void 0===n||!n.fields)&&e.request.url.indexOf("?")>0){var i=Xe(e.request.url);i&&(e.request.fields=i)}}catch(c){o.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield a(e)))return;var l=!0;if(null!=r&&r.before&&(l=yield r.before(e)),!l)return;t=yield r.callback(e),null!=r&&r.after&&(t=yield r.after(e,t))}catch(u){o.error("[miolo-router] Unexpected error on Query ".concat(r.name)),o.error(u)}return t}));return function(r){return e.apply(this,arguments)}}(),c=r.method.toLowerCase();e[c](i,(e=>l(e,r)))}))}))}(n,a,t)}catch(u){t.error(u),t.error("[miolo-router] Error initing the router. Probably config objects are not ok"),t.error("[miolo-router] connOrConfig:"),t.error(null==r?void 0:r.config),t.error("[miolo-router] routes:"),t.error(o)}e.use(n.routes())}var er=i(import.meta.url),rr=n.dirname(er),or=O(n.resolve(rr,"fallback_index.html"),"utf8");function tr(e){return e?e/1e6:0}function nr(e){return e?e/1e6:0}function ir(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var o,t,n,i;o=e.logger,t=Math.round(tr(X.freemem()),2),n=Math.round(tr(X.totalmem()),2),(i=Math.round(100*t/n,2))>80?o.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")):o.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")),Z.check("/",(function(e,r){var t=Math.round(nr(r.used),2),n=Math.round(nr(r.total),2),i=Math.round(nr(r.free),2);i<1?o.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)")):o.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function ar(e,r){var o=e.context.miolo,t=o.logger,n=[ir(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{xe(e.config.http.ratelimit.ipsum_folder||ge,(r=>{e.logger.info("[SERVER][".concat(d("IPsum"),"] File downloaded. ").concat(p(r.length)," ips will be ").concat(f("blacklisted"),"!"))}),e.logger)},start:!0},...r||[]],i=[];n.map((e=>{var r=e.name,t=function(e,r){var o,t=e.logger,n=null!=r&&null!==(o=r.onTick)&&void 0!==o&&o.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new K((null==r?void 0:r.cronTime)||"*/5 * * * *",(o=>{try{t.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(y("ticks!"))),r.onTick(e,o)}catch(n){t.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),t.error(n)}}),(()=>{if(t.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(y("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(o){t.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),t.error(o)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(o,e);i.push({name:r,job:t,running:!0===(null==e?void 0:e.start)})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||t.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,t.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){t.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),t.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,t.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(y("manually started!")))}catch(r){t.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),t.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function lr(n,i){var a,l,c,u=new r,v=function(e){var r,o=t(ae,e);return o.auth_type=function(e){var r,o,t;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.credentials?"credentials":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.custom?"custom":"guest"}(e),o.use_catcher=!(null==o||null===(r=o.http)||void 0===r||!r.catcher_url),o}(n);pe(u,v),De(u,v.http),(e=>{e.use(P({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:M.Z_SYNC_FLUSH},deflate:{flush:M.Z_SYNC_FLUSH},br:!1})),e.use(q(C({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(u),function(e){var r=e.context.miolo.logger;function o(){return(o=oe((function*(e){if(e){var o=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof o&&(o=500):(o=406,e.message="Unsupported type"),he.indexOf(o)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(o,": ").concat(e.message)):r.error(e),this.headerSent||!this.writable)return r.debug("headers were already sent, returning early"),void(e.headerSent=!0);this.type="json",this.status=o,this.body=JSON.stringify(this.body||"",null,2),this.length=Buffer.byteLength(this.body),this.res.end(this.body)}}))).apply(this,arguments)}e.context.onerror=function(e){return o.apply(this,arguments)}}(u),function(e,r){var o=e.context.miolo,t=e=>e.headers["x-real-ip"]||e.ip||"127.0.0.1",n=_e(null==r?void 0:r.ipsum_folder,void 0,o.logger),i={driver:"memory",db:new Map,id:t,headers:{remaining:"Rate-Limit-Remaining",reset:"Rate-Limit-Reset",total:"Rate-Limit-Total"},disableHeader:!1,max:(null==r?void 0:r.max)||1e3,duration:(null==r?void 0:r.duration)||6e4,errorMessage:(null==r?void 0:r.errorMessage)||"Rate Limit reached",whitelist:(null==r?void 0:r.whitelist)||(e=>{var o=(null==r?void 0:r.whitelist_ips)||[];return!!o&&o.indexOf(t(e))>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var o=t(e),i=[...n,...Re,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(o)>=0;return i&&e.miolo.logger.info("Rejecting ".concat(f("blacklisted")," ").concat(s(o))),i})};e.use(j(i))}(u,null===(a=v.http)||void 0===a?void 0:a.ratelimit),((e,r)=>{var{favicon:o,folders:t}=r,n=o||Oe;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(Ce,""))),e.use(F(n)),Object.entries(t)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(Ce,""))),e.use(L(i,T(a,{index:!1})))})(u,null===(l=v.http)||void 0===l?void 0:l.static),function(e,r){var o=function(){var e=oe((function*(e,r){return{}}));return function(r,o){return e.apply(this,arguments)}}(),t=function(){var e=oe((function*(e,r,o){}));return function(r,o,t){return e.apply(this,arguments)}}(),n={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2,onStart:(null==r?void 0:r.onStart)||o,onDone:(null==r?void 0:r.onDone)||t,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=oe((function*(e,r){var o,t,i,a,l,c,u=e.miolo.logger,v=e.headers["x-real-ip"]||"127.0.0.1",g=J.now();e.request.body=ee(ee({},e.request.fields),e.request.files),je.total+=1,je[v]=(je[v]||0)+1,e.requestId=je.total,e.request.ip=v;var y=!0===(null==n||null===(o=n.geoip)||void 0===o?void 0:o.enabled),b={};y&&(b=Me(v,n.geoip,u)),e.request.geoip=b;var S=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,E=y?!0===(null===(t=b)||void 0===t?void 0:t.local)?"":null!==(i=b)&&void 0!==i&&i.country?null!==(a=b)&&void 0!==a&&a.city?" (".concat(null===(l=b)||void 0===l?void 0:l.city,", ").concat(b.country,")"):" (".concat(b.country,")"):"":"",x="".concat(s(v)).concat(E," ").concat(d(e.request.method)," ").concat(d(S)," [").concat(h(je[v]),"/").concat(h(e.requestId),"]"),_=null!=e.request.body?JSON.stringify(e.request.body):"";u.info("".concat(x," - START")),u.debug("".concat(x," - Body: ").concat(_));var R=yield n.onStart(e,{started:g,description:"pending"});yield r();var w=null==e||null===(c=e.session)||void 0===c?void 0:c.user,k="";null!=w&&(null!=w&&w.id?k=" - uid ".concat(null==w?void 0:w.id):null!=w&&w.token&&(k=" - token ".concat(null==w?void 0:w.token)));var O,C=e.response.status,q=C;200==C?O=p:C>200&&C<=299?(O=f,e.response.redirected&&e.response.url&&(q+=" -> ".concat(e.response.url))):O=m;var P="[".concat(O(q),"]"),M=parseFloat((J.now()-g)/1e3).toFixed(2),j=M<n.lazy?p:M<n.slow?f:m,I=M<n.lazy?"Ok":M<n.slow?"lazy":"slow",L=null!=e.session?JSON.stringify(e.session):"";u.debug("".concat(x," - Session: ").concat(L));var T=null!=e.body?JSON.stringify(e.body):"";u.debug("".concat(x," - Response: ").concat(T)),yield n.onDone(e,R,{started:g,elapsed:M,description:I}),u.info("".concat(x," - DONE ").concat(P).concat(k," (").concat(j(I),": ").concat(j(M),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(u,null==v||null===(c=v.http)||void 0===c?void 0:c.request),function(e){function r(){return(r=oe((function*(e){e.body=Te}))).apply(this,arguments)}var o=new U;o.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(o.routes())}(u),v.use_catcher&&function(e,r){function o(){return o=oe((function*(e){var{error:r,warning:o,path:t,agent:n}=e.request.body,i=e.miolo.logger;if(o){var a="".concat(f("[JS Warning]")," on ").concat(g(t),": ").concat(JSON.stringify(o.msg),"\n")+"".concat(f("[JS Warning]")," File => ").concat(o.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(o.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(o.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(o.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(m("[JS Error]")," on ").concat(g(t),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(m("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(m("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(m("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(m("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(m("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),o.apply(this,arguments)}var t=new U;t.post(r,(function(e){return o.apply(this,arguments)})),e.use(t.routes())}(u,v.http.catcher_url),"guest"==v.auth_type&&Fe(u,v.auth.guest,null==v?void 0:v.session),"basic"==v.auth_type&&Je(u,v.auth.basic),"credentials"==v.auth_type&&ze(u,v.auth.credentials,null==v?void 0:v.session),"custom"==v.auth_type&&((e,r)=>{var o=e.context.miolo.logger;try{var t=r(e);if("function"==typeof t)e.use(t);else if(Array.isArray(t)){var n=new U;t.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){o.error("Custom auth error: ".concat(i,"'"))}})(u,v.auth.custom);var y=null==v?void 0:v.middlewares;if(y&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(u,y),null!=v&&v.routes){var b=u.context.miolo.db.getConnection();$e(u,b,v.routes)}null!=(null==i?void 0:i.middleware)?u.use(i.middleware):function(e,r,o,t){var n=(null==r?void 0:r.html)||or;n.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),n.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var i=function(){var e=oe((function*(e){var o={};try{var t;null!=r&&null!==(t=r.ssr)&&void 0!==t&&t.loader&&(o=yield r.ssr.loader(e))}catch(c){var n,i="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(n=e.request)||void 0===n?void 0:n.fields)||{})),a=null!=c&&c.stack?"".concat(c.toString(),"\n").concat(c.stack):c.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return o}));return function(r){return e.apply(this,arguments)}}(),a=(e,r,o)=>{var t,n,i=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:o,extra:null==e?void 0:e.extra}},l=(e,o)=>{var t="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?t=Y(r.ssr.renderer(e,o)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware):\n".concat(a.toString())),t="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(o,null,2)).replace("{children}",t)};function c(){return(c=oe((function*(e){var r,n,c={hostname:null==o?void 0:o.hostname,port:null==o?void 0:o.port,catcher_url:null==o?void 0:o.catcher_url,login_url:null==t||null===(r=t.credentials)||void 0===r?void 0:r.url_login,logout_url:null==t||null===(n=t.credentials)||void 0===n?void 0:n.url_logout},u=yield i(e),s=a(e,c,u),d=l(e,s);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(d,"utf8")," bytes")),e.body=d}))).apply(this,arguments)}e.use((function(e){return c.apply(this,arguments)}))}(u,i,v.http,null==v?void 0:v.auth);var S=function(){var r=oe((function*(){var r=e.createServer(u.callback());yield((e,r,o)=>new Promise(((t,n)=>{e.listen(r,o,(e=>{e?n(e):t()}))})))(r,v.http.port,v.http.hostname),u.context.miolo.logger.info("miolo is listening on ".concat(v.http.hostname,":").concat(v.http.port)),u.server=r;var t=o({server:r});return u.stop_server=oe((function*(){yield t.terminate(),u.context.miolo.logger.info("miolo has been shutdowned from ".concat(v.http.hostname,":").concat(v.http.port))})),ar(u,null==v?void 0:v.cron),u}));return function(){return r.apply(this,arguments)}}();return u.run=S,u}function cr(e){var r=Q.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(s("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof Q.ReplyError?"".concat(s("REDIS")," ").concat(m("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(m("Error "+e.code)," ").concat(e.toString())}catch(o){r="".concat(s("REDIS")," ").concat(m("Error ")," ").concat(o)}console.error(r)})),o=E(r.get).bind(r),t=E(r.exists).bind(r),n=E(r.set).bind(r),i=E(r.del).bind(r);function a(){return(a=oe((function*(e){return yield o(e)}))).apply(this,arguments)}function l(){return(l=oe((function*(e){return 1==(yield t(e))}))).apply(this,arguments)}function c(){return c=oe((function*(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",o))})),c.apply(this,arguments)}function u(){return(u=oe((function*(e){return(yield i(e))>=1}))).apply(this,arguments)}var d={get:function(e){return a.apply(this,arguments)},exists:function(e){return l.apply(this,arguments)},set:function(e,r){return c.apply(this,arguments)},del:function(e){return u.apply(this,arguments)}};return d}export{lr as miolo,cr as miolo_cacher,le as miolo_emailer,me as miolo_logger};