miolo 0.9.36 → 0.9.37

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.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1742,19 +1742,19 @@ var CUSTOM_BLACKLIST_IPS = ['52.212.247.108',
1742
1742
  function init_rate_limit_middleware(app, config) {
1743
1743
  /* eslint-disable no-unused-vars */
1744
1744
  var miolo = app.context.miolo;
1745
- var _get_ip = function _get_ip(ctx) {
1746
- return ctx.headers["x-real-ip"] || ctx.headers["x-orig-ip"] || ctx.ip || '127.0.0.1';
1747
- };
1745
+
1746
+ //const _get_ip = (ctx) => ctx.headers["x-real-ip"] || ctx.headers["x-orig-ip"] || ctx.ip || '127.0.0.1'
1747
+
1748
1748
  var ipsum_ips = ipsum_read_ips(config == null ? void 0 : config.ipsum_folder, undefined, miolo.logger);
1749
1749
  var _def_whitelist = function _def_whitelist(ctx) {
1750
1750
  var ips = (config == null ? void 0 : config.whitelist_ips) || [];
1751
1751
  if (ips) {
1752
- return ips.indexOf(_get_ip(ctx)) >= 0;
1752
+ return ips.indexOf(ctx.request.ip) >= 0;
1753
1753
  }
1754
1754
  return false;
1755
1755
  };
1756
1756
  var _def_blacklist = function _def_blacklist(ctx) {
1757
- var ip = _get_ip(ctx);
1757
+ var ip = ctx.request.ip;
1758
1758
  var ips = [].concat(ipsum_ips, CUSTOM_BLACKLIST_IPS, (config == null ? void 0 : config.blacklist_ips) || []);
1759
1759
  var doit = ips.indexOf(ip) >= 0;
1760
1760
  if (doit) {
@@ -1766,7 +1766,9 @@ function init_rate_limit_middleware(app, config) {
1766
1766
  var rateLimitConfig = {
1767
1767
  driver: 'memory',
1768
1768
  db: rateLimitDB,
1769
- id: _get_ip,
1769
+ id: function id(ctx) {
1770
+ return ctx.request.ip;
1771
+ },
1770
1772
  headers: {
1771
1773
  remaining: 'Rate-Limit-Remaining',
1772
1774
  reset: 'Rate-Limit-Reset',
@@ -1804,7 +1806,7 @@ var init_static_middleware = function init_static_middleware(app, config) {
1804
1806
  };
1805
1807
 
1806
1808
  var _geoip_reader = undefined;
1807
- var _geoip_local_ips = ['127.0.0.1'];
1809
+ var _geoip_local_ips = ['127.0.0.1', '::1:'];
1808
1810
  function _geoip_init(db, local_ips, logger) {
1809
1811
  if (db === void 0) {
1810
1812
  db = '/var/lib/GeoIP/GeoLite2-City.mmdb';
@@ -1861,6 +1863,21 @@ var geoip_localize_ip = function geoip_localize_ip(ip, config, logger) {
1861
1863
  var REQUEST_COUNTER = {
1862
1864
  total: 0
1863
1865
  };
1866
+ function _validate_ip(ipaddress) {
1867
+ if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {
1868
+ return true;
1869
+ }
1870
+ return false;
1871
+ }
1872
+ var _get_ip = function _get_ip(ctx) {
1873
+ var chances = [ctx.headers["x-real-ip"], ctx.headers["x-orig-ip"], ctx.ip, '127.0.0.1'];
1874
+ for (var _i = 0, _chances = chances; _i < _chances.length; _i++) {
1875
+ var ch = _chances[_i];
1876
+ if (_validate_ip(ch)) {
1877
+ return ch;
1878
+ }
1879
+ }
1880
+ };
1864
1881
 
1865
1882
  /**
1866
1883
  * Middleware for feed and log the request
@@ -1918,7 +1935,7 @@ function init_request_middleware(app, config) {
1918
1935
  while (1) switch (_context3.prev = _context3.next) {
1919
1936
  case 0:
1920
1937
  logger = ctx.miolo.logger;
1921
- ip = ctx.headers["x-real-ip"] || ctx.headers["x-orig-ip"] || ctx.ip || '127.0.0.1';
1938
+ ip = _get_ip(ctx);
1922
1939
  started = node_perf_hooks.performance.now(); // Patch for koa-better-body
1923
1940
  ctx.request.body = _extends({}, ctx.request.fields, ctx.request.files);
1924
1941
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
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"koa";import r from"deepmerge";import o from"node:path";import{fileURLToPath as t}from"node:url";import{dropConnections as n,getConnection as i}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import a from"nodemailer";import l,{readFileSync as c}from"node:fs";import{uncolor as u,red as s,gray as d,magenta as f,cyan as v,yellow as p,red_light as m,green as h,cyan_light as g,blue as y,green_bold as b,yellow_bold as _}from"tinguir";import w,{promisify as x}from"node:util";import S,{transports as k,createLogger as E,format as O}from"winston";import{intre_now as j}from"intre";import C from"koa-better-body";import R from"koa-convert";import q from"koa-compress";import{constants as P}from"node:zlib";import I from"koa-ratelimit";import M from"node:https";import L from"koa-mount";import F from"koa-static";import J from"koa-favicon";import{performance as N}from"node:perf_hooks";import{Reader as T}from"@maxmind/geoip2-node";import U from"@koa/router";import A from"jwt-simple";import z from"koa-passport";import B from"passport-local";import D from"koa-session";import G from"koa-redis";import W from"@koa/cors";import H from"koa-proxies";import K from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as V}from"cron";import X from"node:os";import Z from"diskspace";import Q from"node:http";import{createHttpTerminator as $}from"http-terminator";import ee from"redis";function re(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 oe(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?re(Object(o),!0).forEach((function(r){ae(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):re(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function te(e){var r=function(e,r){if("object"!=typeof e||!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)}function ne(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 ie(e){return function(){var r=this,o=arguments;return new Promise((function(t,n){var i=e.apply(r,o);function a(e){ne(i,t,n,a,l,"next",e)}function l(e){ne(i,t,n,a,l,"throw",e)}a(void 0)}))}}function ae(e,r,o){return(r=te(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var le=t(import.meta.url),ce=o.dirname(le),ue={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:o.resolve(ce,"../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/afialapis/%MIOLO%.log",zippedArchive:!0,maxsize:20971520,maxFiles:20},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 se(e){var{options:r,defaults:o,silent:t}=e,n=a.createTransport(r,o);function i(){return(i=ie((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 l={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 l}var{combine:de,timestamp:fe,_label:ve,printf:pe,errors:me}=O,he=function(e,r){var t,n,i,a,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",h={silly:d,debug:f,verbose:v,info:p,warn:m,error:s},g={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},y=r=>{var o,t=h[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(o=e.format)||void 0===o?void 0:o.locale)||"en"),i="[".concat(c,"] ").concat(t(n)," ").concat(t(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 k.Console({humanReadableUnhandledException:!0,level:(null==e||null===(a=e.console)||void 0===a?void 0:a.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(n=e.file)||void 0===n?void 0:n.enabled)){var _,x,O=new k.File({filename:null!=e&&null!==(_=e.file)&&void 0!==_&&_.filename?e.file.filename.replace("%MIOLO%",c):"/var/log/afialapis/miolo.log",level:(null==e||null===(x=e.file)||void 0===x?void 0:x.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0,maxRetries:10});!function(e){process.on("SIGHUP",(function(){var r=o.join(e.dirname,e._getFile(!1));return function(){console.log("[miolo][file-logger] SIGHUP received. Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroy());var o=l.createWriteStream(r,e.options);o.setMaxListeners(1/0),e._size=0,e._stream=o,e.opening=!1,e.emit("open",r),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(t){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(t.toString()))}}()}))}(O),b.push(O);var C=r=>{var t,n,i=o.join(O.dirname,O.filename),a=y({level:"info",message:"[logger][file-rotate] ".concat(r,"\n"),timestamp:j()});try{l.accessSync(i,l.constants.F_OK),l.appendFileSync(i,a)}catch(c){l.writeFileSync(i,a,{encoding:"utf-8"})}!0===(null==e||null===(t=e.console)||void 0===t?void 0:t.enabled)&&(O.levels[(null==e||null===(n=e.console)||void 0===n?void 0:n.level)||(null==e?void 0:e.level)||"error"]>=O.levels.info&&console.log(a))};O.on("finish",(function(e){C("Log done")})),O.on("error",(function(e){C(s("Error: ".concat(e)))}))}if(!0===(null==e||null===(i=e.mail)||void 0===i?void 0:i.enabled)){var R=function(e,r){var o=function(o){S.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 w.inherits(o,S.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=u(i)}catch(d){i="Could not create a title for the error (".concat(d.toString(),")")}try{try{a=u(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),c={from:this.from,to:this.to,subject:l,text:a};r.send(c,(function(){n.emit("logged"),t(null,!0)}))},o}(e.mail,r);k.MailerLogger=R,b.push(new k.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}var q=E({level:(null==e?void 0:e.level)||"silly",format:de(me({stack:!0}),fe(),pe(y)),transports:b});try{q.info("[logger] Inited for ".concat(q.transports.map((e=>"".concat(e.name," (").concat(e.level,")").concat(e.silent?s(" SILENT!"):""))).join(", ")))}catch(P){}return q};class ge{parse_value_str(e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong str value passed: ".concat(e);return r}return e.toString()}parse_field_str(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected str value not passed for ".concat(r);return t}return this.parse_value_str(e[r],o,t)}parse_value_int(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,t=parseInt(e);if(null==t||isNaN(t)){if(r)throw"Wrong int value passed: ".concat(e);return o}return t}parse_field_int(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected int value not passed for ".concat(r);return t}return this.parse_value_int(e[r],o,t)}parse_value_float(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,t=parseFloat(e);if(null==t||isNaN(t)){if(r)throw"Wrong float value passed: ".concat(e);return o}return e}parse_field_float(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected float value not passed for ".concat(r);return t}return this.parse_value_float(e[r],o,t)}parse_value_bool(e){if(null!=e&&null!=e)return!0===e||"true"===e||"True"===e||1===e||"1"===e||!1!==e&&"false"!==e&&"False"!==e&&0!==e&&"0"!==e&&(arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0);if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong bool value passed for ".concat(name)}parse_field_bool(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected bool value not passed for ".concat(r);return t}return this.parse_value_bool(e[r],o,t)}parse_value_obj(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(r)throw"Wrong obj value passed: ".concat(e);return o}if(0==Object.keys(e).length){if(r)throw"Empty obj value passed: ".concat(e);return o}if("object"!=typeof e)throw"Wrong obj value passed: ".concat(e);return e}parse_field_obj(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected obj value not passed for ".concat(r);return t}return this.parse_value_obj(e[r],o,t)}}var ye=()=>new ge,be=(e,r)=>{var o=se(r.mail),t=he(r.log,o,null==r?void 0:r.name),a=ye(),l=e=>{var o=oe(oe(oe({},r.db.options),e||{}),{},{log:t});return i(r.db.config,o)},c={initConnection:()=>l({reset:!0}),flyConnection:()=>l({nocache:!0}),getConnection:l,getModel:(e,o)=>{var n=oe(oe(oe({},r.db.options),o||{}),{},{log:t});return i(r.db.config,n).getModel(e)},dropConnections:n},u={config:oe({},r),emailer:o,logger:t,db:c,parser:a};function s(){return(s=ie((function*(e,r){e.miolo=u,yield r()}))).apply(this,arguments)}e.use((function(e,r){return s.apply(this,arguments)})),e.context.miolo=u},_e=[401,403];var we="/var/ipsum",xe="ipsum.txt",Se="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",ke=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)>=ke&&t.push(r)})),t}catch(n){return o("[cron][".concat(v("IPsum"),"] Error getting IPs from content")),[]}}function Oe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:we,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,n=t?t.error:console.error,i=t?t.debug:console.log;if(l.existsSync(e))try{i("[cron][".concat(v("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Se,o=arguments.length>2?arguments[2]:void 0,t=o?o.error:console.error;M.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("[cron][".concat(v("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((n=>{var a=o.join(e,xe);l.writeFileSync(a,n,{encoding:"utf8",flag:"w"});var c=n.split("\n").length,u=Ee(n,t),s=u.length;i("[cron][".concat(v("IPsum"),"] File downloaded. ").concat(c," ips on the list (").concat(s," appearing in ").concat(ke," or more lists)")),r&&r(u)}))}catch(a){n("[cron][".concat(v("IPsum"),"] Error ").concat(a," updating the file"))}else n("[cron][".concat(v("IPsum"),"] Folder ").concat(e," does not exist"))}function je(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:we,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,n=t?t.debug:console.log,i=t?t.warn:console.log,a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:we,r=arguments.length>1?arguments[1]:void 0,t=r?r.error:console.error;if(!l.existsSync(e))return r&&t("[cron][".concat(v("IPsum"),"] Folder ").concat(e," does not exist")),[];var n=o.join(e,xe);return l.existsSync(n)?Ee(l.readFileSync(n,{encoding:"utf8"}),r):(r&&t("[cron][".concat(v("IPsum"),"] File ").concat(n," does not exist")),[])}(e,t);return a.length>0?(r&&r(a),n("[cron][".concat(v("IPsum"),"] File contains ").concat(a.length," ips")),a):(i("[cron][".concat(v("IPsum"),"] File is empty. Launching update...")),Oe(e,r,t),[])}var Ce=["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","212.128.118.10"];var Re=t(import.meta.url),qe=o.dirname(Re),Pe=o.resolve(qe,"./miolo.ico"),Ie=o.resolve(qe,"../../../.."),Me=void 0,Le=["127.0.0.1"];var Fe=function(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(Le.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!=Me)return Me;Le=[...Le,...r||[]];var t=l.readFileSync(e);return Me=T.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 Ne=t(import.meta.url),Te=o.dirname(Ne),Ue=c(o.resolve(Te,"./robots.txt"),"utf8");var Ae=(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 A.encode(n,t)}(o||{},t)};function i(){return i=ie((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)}))},ze=(e,r)=>{var{auth_user:o,realm:t,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=ie((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))))},Be=new G;var De=(e,r,o)=>r(null,e.id),Ge=(e,r,o)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},We=(e,r,o,t)=>{o(Error("You need to define auth.passport.local_auth_user"),null)},He=(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||De,d=n||Ge,f=i||We,v=a||"/login",p=l||"/logout",m=new B.Strategy(((r,o,t)=>{f(r,o,t,e.context.miolo)}));function h(){return(h=ie((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=oe({store:Be},r.options||{});e.use(D(o,e))}(e,o),z.serializeUser(((r,o)=>{process.nextTick((function(){s(r,o,e.context.miolo)}))})),z.deserializeUser(((r,o)=>{process.nextTick((function(){d(r,o,e.context.miolo)}))})),z.use(m),e.use(z.initialize()),e.use(z.session()),e.use((function(e,r){return h.apply(this,arguments)}));var g=function(){var e=ie((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)=>z.authenticate("local",function(){var r=ie((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(p,g),y.post(p,g),e.use(y.routes())},Ke=(e,r,o)=>{try{var t=e[r];if(null!=t&&0!=t)return o(t)}catch(n){}},Ye=(e,r)=>{var o=e.context.miolo.logger;Ke(r,"cors",(r=>{if("simple"==r)o.debug("Setting CORS the simple way"),e.use(function(){var e=ie((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(W(t))}})),Ke(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(H(t,n))}))},Ve=function(){var e=ie((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Xe=function(){var e=ie((function*(e,r){return r}));return function(r,o){return e.apply(this,arguments)}}(),Ze={require:!1,action:"redirect",redirect_url:"/",error_code:401},Qe={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},$e=e=>{var o=(null==e?void 0:e.crud)||[];if(!o)return[];if(!Array.isArray(o))return[];var t=[];return o.map((o=>{var n=null==o?void 0:o.routes;if(n&&Array.isArray(n)){var i=(null==o?void 0:o.bodyField)||(null==e?void 0:e.bodyField),a=(null==o?void 0:o.before)||(null==e?void 0:e.before)||Ve,l=(null==o?void 0:o.after)||(null==e?void 0:e.after)||Xe,c=r(Ze,(null==e?void 0:e.auth)||{},(null==o?void 0:o.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:r(Qe,(null==d?void 0:d.useUserFields)||{}),auth:r(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==o?void 0:o.prefix)||"",routes:u})}})),t};function er(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?K.parse(r):{}}function rr(e,r){function o(e){return t.apply(this,arguments)}function t(){return(t=ie((function*(r){r.miolo.logger.info("[router] ".concat(e.name,"()"));var o=r.request.fields;try{r.miolo.logger.debug("[router] ".concat(e.name,"() Calling with params ").concat(JSON.stringify(o)))}catch(n){}var t=yield e(r.miolo,o);try{r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result ").concat(JSON.stringify(t)))}catch(n){}r.body=t}))).apply(this,arguments)}return Object.defineProperty(o,"name",{value:e.name,writable:!1}),o}function or(e,r,o){r.map((r=>{var t=r.prefix;r.routes.map((r=>{for(var n=function(){var e=ie((function*(e,o){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&&"w"===o)||(n||("error"==i.action?(e.miolo.logger.error("[miolo-router] Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(e.miolo.logger.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(e.miolo.logger.error("[miolo-router] Crud path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r,o){return e.apply(this,arguments)}}(),i=function(){var e=ie((function*(e,o,t){var i=e.miolo.db.getModel(r.name);if(!i)throw e.miolo.logger.error("[miolo-router] Could not get model for ".concat(r.name)),new Error("[miolo-router] Could not get model for ".concat(r.name));var a,l={};try{var c;if(!(yield n(e,o)))return void(e.body={});var u=!0;if(null!=r&&r.before&&(u=yield r.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===r.useUserFields.use&&(d=r.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield t(i,f),null!=r&&r.after&&(l=yield r.after(e,l))}catch(v){e.miolo.logger.error("[miolo-router] Unexpected error on CRUD ".concat(r.name,"-").concat(o)),e.miolo.logger.error(v)}a=l,l=null==r.bodyField?a:{[r.bodyField]:a},e.body=l}));return function(r,o,t){return e.apply(this,arguments)}}(),a=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=er(e.request.url),n={transaction:void 0};return yield r.read(t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=er(e.request.url),n={transaction:void 0};return yield r.keyList(t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=er(e.request.url),n={transaction:void 0};return yield r.find(t.id,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=er(e.request.url),n={transaction:void 0};return yield r.distinct(t.distinct_field,t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=ie((function*(e){yield i(e,"w",function(){var r=ie((function*(r,o){var t,n=e.request.fields;null!=o&&null!==(t=o.fieldNames)&&void 0!==t&&t.created_by&&(n[o.fieldNames.created_by]=o.uid);var i={transaction:void 0};return yield r.insert(n,i)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=ie((function*(e){yield i(e,"w",function(){var r=ie((function*(r,o){var t,n=e.request.fields;null!=o&&null!==(t=o.fieldNames)&&void 0!==t&&t.last_update_by&&(n[o.fieldNames.last_update_by]=o.uid);var i={transaction:void 0};return yield r.update(n,{id:n.id},i)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=ie((function*(e){yield i(e,"w",function(){var r=ie((function*(r,o){var t=e.request.fields,n={transaction:void 0};return yield r.delete({id:t.id},n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=t?"/".concat(t,"/").concat(r.url):"/".concat(r.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(r.name," to ").concat(v));var p=r.mode.indexOf("r")>=0,m=r.mode.indexOf("w")>=0,h=r.mode.indexOf("u")>=0||m;p&&(e.get("".concat(v,"/find"),(e=>c(e))),e.get("".concat(v,"/read"),(e=>a(e))),e.get("".concat(v,"/distinct"),(e=>u(e))),e.get("".concat(v,"/key_list"),(e=>l(e)))),h&&(e.post("".concat(v,"/save"),(e=>s(e))),e.post("".concat(v,"/update"),(e=>d(e)))),m&&e.post("".concat(v,"/delete"),(e=>f(e)))}))}))}var tr=e=>{var o=(null==e?void 0:e.queries)||[];if(!o)return[];if(!Array.isArray(o))return[];var t=[];return o.map((o=>{var n=null==o?void 0:o.routes;if(n&&Array.isArray(n)){var i=(null==o?void 0:o.before)||(null==e?void 0:e.before)||Ve,a=(null==o?void 0:o.after)||(null==e?void 0:e.after)||Xe,l=r(Ze,(null==o?void 0:o.auth)||{},(null==e?void 0:e.auth)||{}),c=[];for(var u of n)if(u.url){var s=void 0;if(u.callback||u.callback_fn){s=u.callback||rr(u.callback_fn);var d={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:s,auth:r(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(d)}}t.push({prefix:(null==o?void 0:o.prefix)||"",routes:c})}})),t};function nr(e,r){var o=e.context.miolo.logger,t=new U;try{var n=$e(r),i=tr(r),a=n.length>0,l=i.length>0;if(!a&&!l)throw"[miolo-router] Could not get any route from the passed <routes> param";a&&or(t,n,o),l&&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,"/");var a=r.auth,l=!0===a.require||"read-only"===a.require&&"POST"===r.method;o.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i).concat(l?" (auth)":""));var c=function(){var e=ie((function*(e){var o,t=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return!l||(t||("error"==a.action?(e.miolo.logger.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(e.miolo.logger.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(e.miolo.logger.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),t)}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ie((function*(e){var o={};try{try{var t;if("GET"==r.method&&(null===(t=e.request)||void 0===t||!t.fields)&&e.request.url.indexOf("?")>0){var n=er(e.request.url);n&&(e.request.fields=n)}}catch(a){e.miolo.logger.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield c(e)))return;var i=!0;if(null!=r&&r.before&&(i=yield r.before(e)),!i)return;o=yield r.callback(e),null!=r&&r.after&&(o=yield r.after(e,o))}catch(l){e.miolo.logger.error("[miolo-router] Unexpected error on Query ".concat(r.name)),e.miolo.logger.error(l)}return o}));return function(r){return e.apply(this,arguments)}}(),s=r.method.toLowerCase();e[s](i,(e=>u(e,r)))}))}))}(t,i,o)}catch(c){o.error("[miolo-router] Error initing the router."),o.error("[miolo-router] routes:"),o.error(r),o.error(c)}e.use(t.routes())}var ir=t(import.meta.url),ar=o.dirname(ir),lr=c(o.resolve(ar,"fallback_index.html"),"utf8");function cr(e){return e?e/1e6:0}function ur(e){return e?e/1e6:0}function sr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var o,t,n,i;o=e.logger,t=Math.round(cr(X.freemem()),2),n=Math.round(cr(X.totalmem()),2),(i=Math.round(100*t/n,2))>80?o.error("[cron][".concat(v("SysCheck"),"] RAM ").concat(p(t)," MB used of ").concat(h(n)," MB (").concat(p(i)," %)")):o.info("[cron][".concat(v("SysCheck"),"] RAM ").concat(p(t)," MB used of ").concat(h(n)," MB (").concat(p(i)," %)")),Z.check("/",(function(e,r){var t=Math.round(ur(r.used),2),n=Math.round(ur(r.total),2),i=Math.round(ur(r.free),2);i<1?o.error("[cron][".concat(v("SysCheck"),"] DISK ").concat(p(t)," GB used of ").concat(h(n)," GB (").concat(p(i)," GB free)")):o.info("[cron][".concat(v("SysCheck"),"] DISK ").concat(p(t)," GB used of ").concat(h(n)," GB (").concat(p(i)," GB free)"))}))},start:!0}}function dr(e,r){var o=e.context.miolo,t=o.logger,n=[sr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Oe(e.config.http.ratelimit.ipsum_folder||we,(r=>{e.logger.info("[cron][".concat(v("IPsum"),"] File downloaded. ").concat(h(r.length)," ips will be ").concat(p("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 V((null==r?void 0:r.cronTime)||"*/5 * * * *",(o=>{try{t.silly("[cron][Custom Job ".concat(v(i),"] ").concat(b("ticks!"))),r.onTick(e,o)}catch(n){t.error("[cron][Custom Job ".concat(v(i),"] Error at onTick()")),t.error(n)}}),(()=>{if(t.silly("[cron][Custom Job ".concat(v(i),"] ").concat(b("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(o){t.error("[cron][Custom Job ".concat(v(i),"] Error at onComplete()")),t.error(o)}}),!1,(null==r?void 0:r.timezone)||"Europe/Madrid")}(o,e);i.push({name:r,job:t,running:!1})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||t.error("[cron] Job ".concat(v(e)," Not Found")),r},l=e=>{try{return e.job.start(),e.running=!0,t.debug("[cron][Job ".concat(v(e.name),"] ").concat(b("started!"))),1}catch(r){return t.error("[cron][Job ".concat(v(e.name),"] Error starting it")),t.error(r),0}},c=e=>{try{return e.job.stop(),e.running=!1,t.debug("[cron][Job ".concat(v(e.name),"] ").concat(_("stopped!"))),1}catch(r){return t.error("[cron][Job ".concat(v(e.name),"] Error stopping it")),t.error(r),0}};return e.cron={jobs:i,start_one:e=>{var r=a(e);return r?[l(r),r.name]:[0,""]},start:()=>{try{var e=[],r=[];i.map((o=>{1==l(o)?e.push(o.name):r.push(o.name)})),e.length>0&&t.info("[cron] Started ".concat(e.length," jobs: ").concat(e)),r.length>0&&t.warn("[cron] Could not start ".concat(r.length," jobs: ").concat(r))}catch(o){t.error("[cron] start() error: ".concat(o))}},stop_one:e=>{var r=a(e);return r?[c(r),r.name]:[0,""]},stop:()=>{try{var e=[],r=[];i.map((o=>{1==c(o)?e.push(o.name):r.push(o.name)})),e.length>0&&t.info("[cron] Stopped ".concat(e.length," jobs: ").concat(e)),r.length>0&&t.warn("[cron] Could not stop ".concat(r.length," jobs: ").concat(r))}catch(o){t.error("[cron] stop() error: ".concat(o))}}},e}var fr=(e,r,o)=>new Promise(((t,n)=>{e.listen(r,o,(e=>{e?n(e):t()}))}));function vr(o,t){var n,i,a,l=new e,c=function(e){var o,t=r(ue,e);return t.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),t.use_catcher=!(null==t||null===(o=t.http)||void 0===o||!o.catcher_url),t}(o);be(l,c),Ye(l,c.http),(e=>{e.use(q({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:P.Z_SYNC_FLUSH},deflate:{flush:P.Z_SYNC_FLUSH},br:!1})),e.use(R(C({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(l),function(e){var r=e.context.miolo.logger;function o(){return(o=ie((function*(e){if(e){var o=this.headers["x-real-ip"]||this.headers["x-orig-ip"]||this.ip||"127.0.0.1",t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),_e.indexOf(t)>=0?r.warn("[".concat(o,"] ").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 o.apply(this,arguments)}}(l),function(e,r){var o=e.context.miolo,t=e=>e.headers["x-real-ip"]||e.headers["x-orig-ip"]||e.ip||"127.0.0.1",n=je(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,...Ce,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(o)>=0;return i&&e.miolo.logger.info("Rejecting ".concat(p("blacklisted")," ").concat(f(o))),i})};e.use(I(i))}(l,null===(n=c.http)||void 0===n?void 0:n.ratelimit),((e,r)=>{var{favicon:o,folders:t}=r,n=o||Pe;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(Ie,""))),e.use(J(n)),Object.entries(t)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(Ie,""))),e.use(L(i,F(a,{index:!1})))})(l,null===(i=c.http)||void 0===i?void 0:i.static),function(e,r){var o=function(){var e=ie((function*(e,r){return{}}));return function(r,o){return e.apply(this,arguments)}}(),t=function(){var e=ie((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=ie((function*(e,r){var o,t,i,a,l,c,u=e.miolo.logger,d=e.headers["x-real-ip"]||e.headers["x-orig-ip"]||e.ip||"127.0.0.1",m=N.now();e.request.body=oe(oe({},e.request.fields),e.request.files),Je.total+=1,Je[d]=(Je[d]||0)+1,e.requestId=Je.total,e.request.ip=d;var y=!0===(null==n||null===(o=n.geoip)||void 0===o?void 0:o.enabled),b={};y&&(b=Fe(d,n.geoip,u)),e.request.geoip=b;var _=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,w=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(f(d)).concat(w," ").concat(v(e.request.method)," ").concat(v(_)," [").concat(g(Je[d]),"/").concat(g(e.requestId),"]"),S=null!=e.request.body?JSON.stringify(e.request.body):"";u.info("".concat(x," - START")),u.debug("".concat(x," - Body: ").concat(S));var k=yield n.onStart(e,{started:m,description:"pending"});yield r();var E=null==e||null===(c=e.session)||void 0===c?void 0:c.user,O="";null!=E&&(null!=E&&E.id?O=" - uid ".concat(null==E?void 0:E.id):null!=E&&E.token&&(O=" - token ".concat(null==E?void 0:E.token)));var j,C=e.response.status,R=C;200==C?j=h:C>200&&C<=299?(j=p,e.response.redirected&&e.response.url&&(R+=" -> ".concat(e.response.url))):j=s;var q="[".concat(j(R),"]"),P=parseFloat((N.now()-m)/1e3).toFixed(2),I=P<n.lazy?h:P<n.slow?p:s,M=P<n.lazy?"Ok":P<n.slow?"lazy":"slow",L=null!=e.session?JSON.stringify(e.session):"";u.debug("".concat(x," - Session: ").concat(L));var F=null!=e.body?JSON.stringify(e.body):"";u.debug("".concat(x," - Response: ").concat(F)),yield n.onDone(e,k,{started:m,elapsed:P,description:M}),u.info("".concat(x," - DONE ").concat(q).concat(O," (").concat(I(M),": ").concat(I(P),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(l,null==c||null===(a=c.http)||void 0===a?void 0:a.request),function(e){function r(){return(r=ie((function*(e){e.body=Ue}))).apply(this,arguments)}var o=new U;o.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(o.routes())}(l),c.use_catcher&&function(e,r){function o(){return o=ie((function*(e){var{error:r,warning:o,path:t,agent:n}=e.request.body,i=e.miolo.logger;if(o){var a="".concat(p("[JS Warning]")," on ").concat(y(t),": ").concat(JSON.stringify(o.msg),"\n")+"".concat(p("[JS Warning]")," File => ").concat(o.file,"\n")+"".concat(p("[JS Warning]")," Line => ").concat(o.line,"\n")+"".concat(p("[JS Warning]")," Col => ").concat(o.col,"\n")+"".concat(p("[JS Warning]")," Error => ").concat(JSON.stringify(o.error),"\n")+"".concat(p("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(s("[JS Error]")," on ").concat(y(t),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(s("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(s("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(s("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(s("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(s("[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())}(l,c.http.catcher_url),"guest"==c.auth_type&&Ae(l,c.auth.guest,null==c?void 0:c.session),"basic"==c.auth_type&&ze(l,c.auth.basic),"credentials"==c.auth_type&&He(l,c.auth.credentials,null==c?void 0:c.session),"custom"==c.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,"'"))}})(l,c.auth.custom);var u=null==c?void 0:c.middlewares;return u&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(l,u),null!=c&&c.routes&&nr(l,c.routes),null!=(null==t?void 0:t.middleware)?l.use(t.middleware):function(e,r,o,t){var n=(null==r?void 0:r.html)||lr;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=ie((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=ie((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)}))}(l,t,c.http,null==c?void 0:c.auth),dr(l,null==c?void 0:c.cron),function(e,r){var o,t=e.context.miolo.logger,n=function(){var o=ie((function*(){try{var o,n,i;if(null!=(null===(o=e.http)||void 0===o?void 0:o.server))return void t.warn("[http][start] Server already running on ".concat(null==e||null===(n=e.http)||void 0===n?void 0:n.hostname,":").concat(null==e||null===(i=e.http)||void 0===i?void 0:i.port));var a=Q.createServer(e.callback()),l=$({server:a}),c=function(){var o=ie((function*(){try{yield l.terminate(),delete e.http.server,t.info("[http][stop] miolo has been shutdowned from ".concat(r.hostname,":").concat(r.port))}catch(o){t.error("[http][stop] error: ".concat(o))}}));return function(){return o.apply(this,arguments)}}();e.http.server=a,e.http.stop=c,yield fr(a,r.port,r.hostname),t.info("[http][start] miolo is listening on ".concat(r.hostname,":").concat(r.port))}catch(u){t.error("[http][start] error: ".concat(u))}}));return function(){return o.apply(this,arguments)}}();e.http={server:void 0,start:n,stop:(o=ie((function*(){t.warn("[http] stop() stop() function still not attached. Is server running?")})),function(){return o.apply(this,arguments)}),hostname:r.hostname,port:r.port}}(l,null==c?void 0:c.http),l.start=ie((function*(){l.context.miolo.db.initConnection(),yield l.http.start(),l.cron.start()})),l.stop=ie((function*(){l.context.miolo.db.dropConnections(),yield l.http.stop(),l.cron.stop()})),l.restart=ie((function*(){yield l.stop(),yield l.start()})),l}function pr(e){var r=ee.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(f("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof ee.ReplyError?"".concat(f("REDIS")," ").concat(s("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(f("REDIS")," ").concat(s("Error "+e.code)," ").concat(e.toString())}catch(o){r="".concat(f("REDIS")," ").concat(s("Error ")," ").concat(o)}console.error(r)})),o=x(r.get).bind(r),t=x(r.exists).bind(r),n=x(r.set).bind(r),i=x(r.del).bind(r);function a(){return(a=ie((function*(e){return yield o(e)}))).apply(this,arguments)}function l(){return(l=ie((function*(e){return 1==(yield t(e))}))).apply(this,arguments)}function c(){return c=ie((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=ie((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{vr as miolo,pr as miolo_cacher,se as miolo_emailer,he as miolo_logger,ye as miolo_parser};
11
+ import e from"koa";import r from"deepmerge";import o from"node:path";import{fileURLToPath as t}from"node:url";import{dropConnections as n,getConnection as i}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import a from"nodemailer";import l,{readFileSync as c}from"node:fs";import{uncolor as u,red as s,gray as d,magenta as f,cyan as v,yellow as p,red_light as m,green as h,cyan_light as g,blue as y,green_bold as b,yellow_bold as _}from"tinguir";import w,{promisify as x}from"node:util";import S,{transports as k,createLogger as E,format as O}from"winston";import{intre_now as j}from"intre";import C from"koa-better-body";import q from"koa-convert";import R from"koa-compress";import{constants as P}from"node:zlib";import I from"koa-ratelimit";import M from"node:https";import L from"koa-mount";import F from"koa-static";import J from"koa-favicon";import{performance as N}from"node:perf_hooks";import{Reader as T}from"@maxmind/geoip2-node";import U from"@koa/router";import A from"jwt-simple";import z from"koa-passport";import B from"passport-local";import D from"koa-session";import G from"koa-redis";import W from"@koa/cors";import H from"koa-proxies";import K from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as V}from"cron";import X from"node:os";import Z from"diskspace";import Q from"node:http";import{createHttpTerminator as $}from"http-terminator";import ee from"redis";function re(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 oe(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?re(Object(o),!0).forEach((function(r){ae(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):re(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function te(e){var r=function(e,r){if("object"!=typeof e||!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)}function ne(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 ie(e){return function(){var r=this,o=arguments;return new Promise((function(t,n){var i=e.apply(r,o);function a(e){ne(i,t,n,a,l,"next",e)}function l(e){ne(i,t,n,a,l,"throw",e)}a(void 0)}))}}function ae(e,r,o){return(r=te(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var le=t(import.meta.url),ce=o.dirname(le),ue={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:o.resolve(ce,"../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/afialapis/%MIOLO%.log",zippedArchive:!0,maxsize:20971520,maxFiles:20},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 se(e){var{options:r,defaults:o,silent:t}=e,n=a.createTransport(r,o);function i(){return(i=ie((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 l={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 l}var{combine:de,timestamp:fe,_label:ve,printf:pe,errors:me}=O,he=function(e,r){var t,n,i,a,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",h={silly:d,debug:f,verbose:v,info:p,warn:m,error:s},g={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},y=r=>{var o,t=h[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(o=e.format)||void 0===o?void 0:o.locale)||"en"),i="[".concat(c,"] ").concat(t(n)," ").concat(t(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 k.Console({humanReadableUnhandledException:!0,level:(null==e||null===(a=e.console)||void 0===a?void 0:a.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(n=e.file)||void 0===n?void 0:n.enabled)){var _,x,O=new k.File({filename:null!=e&&null!==(_=e.file)&&void 0!==_&&_.filename?e.file.filename.replace("%MIOLO%",c):"/var/log/afialapis/miolo.log",level:(null==e||null===(x=e.file)||void 0===x?void 0:x.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0,maxRetries:10});!function(e){process.on("SIGHUP",(function(){var r=o.join(e.dirname,e._getFile(!1));return function(){console.log("[miolo][file-logger] SIGHUP received. Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroy());var o=l.createWriteStream(r,e.options);o.setMaxListeners(1/0),e._size=0,e._stream=o,e.opening=!1,e.emit("open",r),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(t){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(t.toString()))}}()}))}(O),b.push(O);var C=r=>{var t,n,i=o.join(O.dirname,O.filename),a=y({level:"info",message:"[logger][file-rotate] ".concat(r,"\n"),timestamp:j()});try{l.accessSync(i,l.constants.F_OK),l.appendFileSync(i,a)}catch(c){l.writeFileSync(i,a,{encoding:"utf-8"})}!0===(null==e||null===(t=e.console)||void 0===t?void 0:t.enabled)&&(O.levels[(null==e||null===(n=e.console)||void 0===n?void 0:n.level)||(null==e?void 0:e.level)||"error"]>=O.levels.info&&console.log(a))};O.on("finish",(function(e){C("Log done")})),O.on("error",(function(e){C(s("Error: ".concat(e)))}))}if(!0===(null==e||null===(i=e.mail)||void 0===i?void 0:i.enabled)){var q=function(e,r){var o=function(o){S.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 w.inherits(o,S.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=u(i)}catch(d){i="Could not create a title for the error (".concat(d.toString(),")")}try{try{a=u(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),c={from:this.from,to:this.to,subject:l,text:a};r.send(c,(function(){n.emit("logged"),t(null,!0)}))},o}(e.mail,r);k.MailerLogger=q,b.push(new k.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}var R=E({level:(null==e?void 0:e.level)||"silly",format:de(me({stack:!0}),fe(),pe(y)),transports:b});try{R.info("[logger] Inited for ".concat(R.transports.map((e=>"".concat(e.name," (").concat(e.level,")").concat(e.silent?s(" SILENT!"):""))).join(", ")))}catch(P){}return R};class ge{parse_value_str(e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong str value passed: ".concat(e);return r}return e.toString()}parse_field_str(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected str value not passed for ".concat(r);return t}return this.parse_value_str(e[r],o,t)}parse_value_int(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,t=parseInt(e);if(null==t||isNaN(t)){if(r)throw"Wrong int value passed: ".concat(e);return o}return t}parse_field_int(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected int value not passed for ".concat(r);return t}return this.parse_value_int(e[r],o,t)}parse_value_float(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,t=parseFloat(e);if(null==t||isNaN(t)){if(r)throw"Wrong float value passed: ".concat(e);return o}return e}parse_field_float(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected float value not passed for ".concat(r);return t}return this.parse_value_float(e[r],o,t)}parse_value_bool(e){if(null!=e&&null!=e)return!0===e||"true"===e||"True"===e||1===e||"1"===e||!1!==e&&"false"!==e&&"False"!==e&&0!==e&&"0"!==e&&(arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0);if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong bool value passed for ".concat(name)}parse_field_bool(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected bool value not passed for ".concat(r);return t}return this.parse_value_bool(e[r],o,t)}parse_value_obj(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(r)throw"Wrong obj value passed: ".concat(e);return o}if(0==Object.keys(e).length){if(r)throw"Empty obj value passed: ".concat(e);return o}if("object"!=typeof e)throw"Wrong obj value passed: ".concat(e);return e}parse_field_obj(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected obj value not passed for ".concat(r);return t}return this.parse_value_obj(e[r],o,t)}}var ye=()=>new ge,be=(e,r)=>{var o=se(r.mail),t=he(r.log,o,null==r?void 0:r.name),a=ye(),l=e=>{var o=oe(oe(oe({},r.db.options),e||{}),{},{log:t});return i(r.db.config,o)},c={initConnection:()=>l({reset:!0}),flyConnection:()=>l({nocache:!0}),getConnection:l,getModel:(e,o)=>{var n=oe(oe(oe({},r.db.options),o||{}),{},{log:t});return i(r.db.config,n).getModel(e)},dropConnections:n},u={config:oe({},r),emailer:o,logger:t,db:c,parser:a};function s(){return(s=ie((function*(e,r){e.miolo=u,yield r()}))).apply(this,arguments)}e.use((function(e,r){return s.apply(this,arguments)})),e.context.miolo=u},_e=[401,403];var we="/var/ipsum",xe="ipsum.txt",Se="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",ke=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)>=ke&&t.push(r)})),t}catch(n){return o("[cron][".concat(v("IPsum"),"] Error getting IPs from content")),[]}}function Oe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:we,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,n=t?t.error:console.error,i=t?t.debug:console.log;if(l.existsSync(e))try{i("[cron][".concat(v("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Se,o=arguments.length>2?arguments[2]:void 0,t=o?o.error:console.error;M.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("[cron][".concat(v("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((n=>{var a=o.join(e,xe);l.writeFileSync(a,n,{encoding:"utf8",flag:"w"});var c=n.split("\n").length,u=Ee(n,t),s=u.length;i("[cron][".concat(v("IPsum"),"] File downloaded. ").concat(c," ips on the list (").concat(s," appearing in ").concat(ke," or more lists)")),r&&r(u)}))}catch(a){n("[cron][".concat(v("IPsum"),"] Error ").concat(a," updating the file"))}else n("[cron][".concat(v("IPsum"),"] Folder ").concat(e," does not exist"))}function je(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:we,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,n=t?t.debug:console.log,i=t?t.warn:console.log,a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:we,r=arguments.length>1?arguments[1]:void 0,t=r?r.error:console.error;if(!l.existsSync(e))return r&&t("[cron][".concat(v("IPsum"),"] Folder ").concat(e," does not exist")),[];var n=o.join(e,xe);return l.existsSync(n)?Ee(l.readFileSync(n,{encoding:"utf8"}),r):(r&&t("[cron][".concat(v("IPsum"),"] File ").concat(n," does not exist")),[])}(e,t);return a.length>0?(r&&r(a),n("[cron][".concat(v("IPsum"),"] File contains ").concat(a.length," ips")),a):(i("[cron][".concat(v("IPsum"),"] File is empty. Launching update...")),Oe(e,r,t),[])}var Ce=["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","212.128.118.10"];var qe=t(import.meta.url),Re=o.dirname(qe),Pe=o.resolve(Re,"./miolo.ico"),Ie=o.resolve(Re,"../../../.."),Me=void 0,Le=["127.0.0.1","::1:"];var Fe=function(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(Le.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!=Me)return Me;Le=[...Le,...r||[]];var t=l.readFileSync(e);return Me=T.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 Ne=e=>{var r=[e.headers["x-real-ip"],e.headers["x-orig-ip"],e.ip,"127.0.0.1"];for(var o of r)if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(o))return o};var Te=t(import.meta.url),Ue=o.dirname(Te),Ae=c(o.resolve(Ue,"./robots.txt"),"utf8");var ze=(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 A.encode(n,t)}(o||{},t)};function i(){return i=ie((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)}))},Be=(e,r)=>{var{auth_user:o,realm:t,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=ie((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))))},De=new G;var Ge=(e,r,o)=>r(null,e.id),We=(e,r,o)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},He=(e,r,o,t)=>{o(Error("You need to define auth.passport.local_auth_user"),null)},Ke=(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||Ge,d=n||We,f=i||He,v=a||"/login",p=l||"/logout",m=new B.Strategy(((r,o,t)=>{f(r,o,t,e.context.miolo)}));function h(){return(h=ie((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=oe({store:De},r.options||{});e.use(D(o,e))}(e,o),z.serializeUser(((r,o)=>{process.nextTick((function(){s(r,o,e.context.miolo)}))})),z.deserializeUser(((r,o)=>{process.nextTick((function(){d(r,o,e.context.miolo)}))})),z.use(m),e.use(z.initialize()),e.use(z.session()),e.use((function(e,r){return h.apply(this,arguments)}));var g=function(){var e=ie((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)=>z.authenticate("local",function(){var r=ie((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(p,g),y.post(p,g),e.use(y.routes())},Ye=(e,r,o)=>{try{var t=e[r];if(null!=t&&0!=t)return o(t)}catch(n){}},Ve=(e,r)=>{var o=e.context.miolo.logger;Ye(r,"cors",(r=>{if("simple"==r)o.debug("Setting CORS the simple way"),e.use(function(){var e=ie((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(W(t))}})),Ye(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(H(t,n))}))},Xe=function(){var e=ie((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Ze=function(){var e=ie((function*(e,r){return r}));return function(r,o){return e.apply(this,arguments)}}(),Qe={require:!1,action:"redirect",redirect_url:"/",error_code:401},$e={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},er=e=>{var o=(null==e?void 0:e.crud)||[];if(!o)return[];if(!Array.isArray(o))return[];var t=[];return o.map((o=>{var n=null==o?void 0:o.routes;if(n&&Array.isArray(n)){var i=(null==o?void 0:o.bodyField)||(null==e?void 0:e.bodyField),a=(null==o?void 0:o.before)||(null==e?void 0:e.before)||Xe,l=(null==o?void 0:o.after)||(null==e?void 0:e.after)||Ze,c=r(Qe,(null==e?void 0:e.auth)||{},(null==o?void 0:o.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:r($e,(null==d?void 0:d.useUserFields)||{}),auth:r(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==o?void 0:o.prefix)||"",routes:u})}})),t};function rr(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?K.parse(r):{}}function or(e,r){function o(e){return t.apply(this,arguments)}function t(){return(t=ie((function*(r){r.miolo.logger.info("[router] ".concat(e.name,"()"));var o=r.request.fields;try{r.miolo.logger.debug("[router] ".concat(e.name,"() Calling with params ").concat(JSON.stringify(o)))}catch(n){}var t=yield e(r.miolo,o);try{r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result ").concat(JSON.stringify(t)))}catch(n){}r.body=t}))).apply(this,arguments)}return Object.defineProperty(o,"name",{value:e.name,writable:!1}),o}function tr(e,r,o){r.map((r=>{var t=r.prefix;r.routes.map((r=>{for(var n=function(){var e=ie((function*(e,o){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&&"w"===o)||(n||("error"==i.action?(e.miolo.logger.error("[miolo-router] Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(e.miolo.logger.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(e.miolo.logger.error("[miolo-router] Crud path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r,o){return e.apply(this,arguments)}}(),i=function(){var e=ie((function*(e,o,t){var i=e.miolo.db.getModel(r.name);if(!i)throw e.miolo.logger.error("[miolo-router] Could not get model for ".concat(r.name)),new Error("[miolo-router] Could not get model for ".concat(r.name));var a,l={};try{var c;if(!(yield n(e,o)))return void(e.body={});var u=!0;if(null!=r&&r.before&&(u=yield r.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===r.useUserFields.use&&(d=r.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield t(i,f),null!=r&&r.after&&(l=yield r.after(e,l))}catch(v){e.miolo.logger.error("[miolo-router] Unexpected error on CRUD ".concat(r.name,"-").concat(o)),e.miolo.logger.error(v)}a=l,l=null==r.bodyField?a:{[r.bodyField]:a},e.body=l}));return function(r,o,t){return e.apply(this,arguments)}}(),a=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=rr(e.request.url),n={transaction:void 0};return yield r.read(t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=rr(e.request.url),n={transaction:void 0};return yield r.keyList(t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=rr(e.request.url),n={transaction:void 0};return yield r.find(t.id,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ie((function*(e){yield i(e,"r",function(){var r=ie((function*(r,o){var t=rr(e.request.url),n={transaction:void 0};return yield r.distinct(t.distinct_field,t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=ie((function*(e){yield i(e,"w",function(){var r=ie((function*(r,o){var t,n=e.request.fields;null!=o&&null!==(t=o.fieldNames)&&void 0!==t&&t.created_by&&(n[o.fieldNames.created_by]=o.uid);var i={transaction:void 0};return yield r.insert(n,i)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=ie((function*(e){yield i(e,"w",function(){var r=ie((function*(r,o){var t,n=e.request.fields;null!=o&&null!==(t=o.fieldNames)&&void 0!==t&&t.last_update_by&&(n[o.fieldNames.last_update_by]=o.uid);var i={transaction:void 0};return yield r.update(n,{id:n.id},i)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=ie((function*(e){yield i(e,"w",function(){var r=ie((function*(r,o){var t=e.request.fields,n={transaction:void 0};return yield r.delete({id:t.id},n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=t?"/".concat(t,"/").concat(r.url):"/".concat(r.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(r.name," to ").concat(v));var p=r.mode.indexOf("r")>=0,m=r.mode.indexOf("w")>=0,h=r.mode.indexOf("u")>=0||m;p&&(e.get("".concat(v,"/find"),(e=>c(e))),e.get("".concat(v,"/read"),(e=>a(e))),e.get("".concat(v,"/distinct"),(e=>u(e))),e.get("".concat(v,"/key_list"),(e=>l(e)))),h&&(e.post("".concat(v,"/save"),(e=>s(e))),e.post("".concat(v,"/update"),(e=>d(e)))),m&&e.post("".concat(v,"/delete"),(e=>f(e)))}))}))}var nr=e=>{var o=(null==e?void 0:e.queries)||[];if(!o)return[];if(!Array.isArray(o))return[];var t=[];return o.map((o=>{var n=null==o?void 0:o.routes;if(n&&Array.isArray(n)){var i=(null==o?void 0:o.before)||(null==e?void 0:e.before)||Xe,a=(null==o?void 0:o.after)||(null==e?void 0:e.after)||Ze,l=r(Qe,(null==o?void 0:o.auth)||{},(null==e?void 0:e.auth)||{}),c=[];for(var u of n)if(u.url){var s=void 0;if(u.callback||u.callback_fn){s=u.callback||or(u.callback_fn);var d={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:s,auth:r(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(d)}}t.push({prefix:(null==o?void 0:o.prefix)||"",routes:c})}})),t};function ir(e,r){var o=e.context.miolo.logger,t=new U;try{var n=er(r),i=nr(r),a=n.length>0,l=i.length>0;if(!a&&!l)throw"[miolo-router] Could not get any route from the passed <routes> param";a&&tr(t,n,o),l&&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,"/");var a=r.auth,l=!0===a.require||"read-only"===a.require&&"POST"===r.method;o.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i).concat(l?" (auth)":""));var c=function(){var e=ie((function*(e){var o,t=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return!l||(t||("error"==a.action?(e.miolo.logger.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(e.miolo.logger.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(e.miolo.logger.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),t)}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ie((function*(e){var o={};try{try{var t;if("GET"==r.method&&(null===(t=e.request)||void 0===t||!t.fields)&&e.request.url.indexOf("?")>0){var n=rr(e.request.url);n&&(e.request.fields=n)}}catch(a){e.miolo.logger.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield c(e)))return;var i=!0;if(null!=r&&r.before&&(i=yield r.before(e)),!i)return;o=yield r.callback(e),null!=r&&r.after&&(o=yield r.after(e,o))}catch(l){e.miolo.logger.error("[miolo-router] Unexpected error on Query ".concat(r.name)),e.miolo.logger.error(l)}return o}));return function(r){return e.apply(this,arguments)}}(),s=r.method.toLowerCase();e[s](i,(e=>u(e,r)))}))}))}(t,i,o)}catch(c){o.error("[miolo-router] Error initing the router."),o.error("[miolo-router] routes:"),o.error(r),o.error(c)}e.use(t.routes())}var ar=t(import.meta.url),lr=o.dirname(ar),cr=c(o.resolve(lr,"fallback_index.html"),"utf8");function ur(e){return e?e/1e6:0}function sr(e){return e?e/1e6:0}function dr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var o,t,n,i;o=e.logger,t=Math.round(ur(X.freemem()),2),n=Math.round(ur(X.totalmem()),2),(i=Math.round(100*t/n,2))>80?o.error("[cron][".concat(v("SysCheck"),"] RAM ").concat(p(t)," MB used of ").concat(h(n)," MB (").concat(p(i)," %)")):o.info("[cron][".concat(v("SysCheck"),"] RAM ").concat(p(t)," MB used of ").concat(h(n)," MB (").concat(p(i)," %)")),Z.check("/",(function(e,r){var t=Math.round(sr(r.used),2),n=Math.round(sr(r.total),2),i=Math.round(sr(r.free),2);i<1?o.error("[cron][".concat(v("SysCheck"),"] DISK ").concat(p(t)," GB used of ").concat(h(n)," GB (").concat(p(i)," GB free)")):o.info("[cron][".concat(v("SysCheck"),"] DISK ").concat(p(t)," GB used of ").concat(h(n)," GB (").concat(p(i)," GB free)"))}))},start:!0}}function fr(e,r){var o=e.context.miolo,t=o.logger,n=[dr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Oe(e.config.http.ratelimit.ipsum_folder||we,(r=>{e.logger.info("[cron][".concat(v("IPsum"),"] File downloaded. ").concat(h(r.length)," ips will be ").concat(p("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 V((null==r?void 0:r.cronTime)||"*/5 * * * *",(o=>{try{t.silly("[cron][Custom Job ".concat(v(i),"] ").concat(b("ticks!"))),r.onTick(e,o)}catch(n){t.error("[cron][Custom Job ".concat(v(i),"] Error at onTick()")),t.error(n)}}),(()=>{if(t.silly("[cron][Custom Job ".concat(v(i),"] ").concat(b("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(o){t.error("[cron][Custom Job ".concat(v(i),"] Error at onComplete()")),t.error(o)}}),!1,(null==r?void 0:r.timezone)||"Europe/Madrid")}(o,e);i.push({name:r,job:t,running:!1})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||t.error("[cron] Job ".concat(v(e)," Not Found")),r},l=e=>{try{return e.job.start(),e.running=!0,t.debug("[cron][Job ".concat(v(e.name),"] ").concat(b("started!"))),1}catch(r){return t.error("[cron][Job ".concat(v(e.name),"] Error starting it")),t.error(r),0}},c=e=>{try{return e.job.stop(),e.running=!1,t.debug("[cron][Job ".concat(v(e.name),"] ").concat(_("stopped!"))),1}catch(r){return t.error("[cron][Job ".concat(v(e.name),"] Error stopping it")),t.error(r),0}};return e.cron={jobs:i,start_one:e=>{var r=a(e);return r?[l(r),r.name]:[0,""]},start:()=>{try{var e=[],r=[];i.map((o=>{1==l(o)?e.push(o.name):r.push(o.name)})),e.length>0&&t.info("[cron] Started ".concat(e.length," jobs: ").concat(e)),r.length>0&&t.warn("[cron] Could not start ".concat(r.length," jobs: ").concat(r))}catch(o){t.error("[cron] start() error: ".concat(o))}},stop_one:e=>{var r=a(e);return r?[c(r),r.name]:[0,""]},stop:()=>{try{var e=[],r=[];i.map((o=>{1==c(o)?e.push(o.name):r.push(o.name)})),e.length>0&&t.info("[cron] Stopped ".concat(e.length," jobs: ").concat(e)),r.length>0&&t.warn("[cron] Could not stop ".concat(r.length," jobs: ").concat(r))}catch(o){t.error("[cron] stop() error: ".concat(o))}}},e}var vr=(e,r,o)=>new Promise(((t,n)=>{e.listen(r,o,(e=>{e?n(e):t()}))}));function pr(o,t){var n,i,a,l=new e,c=function(e){var o,t=r(ue,e);return t.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),t.use_catcher=!(null==t||null===(o=t.http)||void 0===o||!o.catcher_url),t}(o);be(l,c),Ve(l,c.http),(e=>{e.use(R({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:P.Z_SYNC_FLUSH},deflate:{flush:P.Z_SYNC_FLUSH},br:!1})),e.use(q(C({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(l),function(e){var r=e.context.miolo.logger;function o(){return(o=ie((function*(e){if(e){var o=this.headers["x-real-ip"]||this.headers["x-orig-ip"]||this.ip||"127.0.0.1",t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),_e.indexOf(t)>=0?r.warn("[".concat(o,"] ").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 o.apply(this,arguments)}}(l),function(e,r){var o=e.context.miolo,t=je(null==r?void 0:r.ipsum_folder,void 0,o.logger),n={driver:"memory",db:new Map,id:e=>e.request.ip,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(e.request.ip)>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var o=e.request.ip,n=[...t,...Ce,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(o)>=0;return n&&e.miolo.logger.info("Rejecting ".concat(p("blacklisted")," ").concat(f(o))),n})};e.use(I(n))}(l,null===(n=c.http)||void 0===n?void 0:n.ratelimit),((e,r)=>{var{favicon:o,folders:t}=r,n=o||Pe;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(Ie,""))),e.use(J(n)),Object.entries(t)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(Ie,""))),e.use(L(i,F(a,{index:!1})))})(l,null===(i=c.http)||void 0===i?void 0:i.static),function(e,r){var o=function(){var e=ie((function*(e,r){return{}}));return function(r,o){return e.apply(this,arguments)}}(),t=function(){var e=ie((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=ie((function*(e,r){var o,t,i,a,l,c,u=e.miolo.logger,d=Ne(e),m=N.now();e.request.body=oe(oe({},e.request.fields),e.request.files),Je.total+=1,Je[d]=(Je[d]||0)+1,e.requestId=Je.total,e.request.ip=d;var y=!0===(null==n||null===(o=n.geoip)||void 0===o?void 0:o.enabled),b={};y&&(b=Fe(d,n.geoip,u)),e.request.geoip=b;var _=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,w=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(f(d)).concat(w," ").concat(v(e.request.method)," ").concat(v(_)," [").concat(g(Je[d]),"/").concat(g(e.requestId),"]"),S=null!=e.request.body?JSON.stringify(e.request.body):"";u.info("".concat(x," - START")),u.debug("".concat(x," - Body: ").concat(S));var k=yield n.onStart(e,{started:m,description:"pending"});yield r();var E=null==e||null===(c=e.session)||void 0===c?void 0:c.user,O="";null!=E&&(null!=E&&E.id?O=" - uid ".concat(null==E?void 0:E.id):null!=E&&E.token&&(O=" - token ".concat(null==E?void 0:E.token)));var j,C=e.response.status,q=C;200==C?j=h:C>200&&C<=299?(j=p,e.response.redirected&&e.response.url&&(q+=" -> ".concat(e.response.url))):j=s;var R="[".concat(j(q),"]"),P=parseFloat((N.now()-m)/1e3).toFixed(2),I=P<n.lazy?h:P<n.slow?p:s,M=P<n.lazy?"Ok":P<n.slow?"lazy":"slow",L=null!=e.session?JSON.stringify(e.session):"";u.debug("".concat(x," - Session: ").concat(L));var F=null!=e.body?JSON.stringify(e.body):"";u.debug("".concat(x," - Response: ").concat(F)),yield n.onDone(e,k,{started:m,elapsed:P,description:M}),u.info("".concat(x," - DONE ").concat(R).concat(O," (").concat(I(M),": ").concat(I(P),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(l,null==c||null===(a=c.http)||void 0===a?void 0:a.request),function(e){function r(){return(r=ie((function*(e){e.body=Ae}))).apply(this,arguments)}var o=new U;o.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(o.routes())}(l),c.use_catcher&&function(e,r){function o(){return o=ie((function*(e){var{error:r,warning:o,path:t,agent:n}=e.request.body,i=e.miolo.logger;if(o){var a="".concat(p("[JS Warning]")," on ").concat(y(t),": ").concat(JSON.stringify(o.msg),"\n")+"".concat(p("[JS Warning]")," File => ").concat(o.file,"\n")+"".concat(p("[JS Warning]")," Line => ").concat(o.line,"\n")+"".concat(p("[JS Warning]")," Col => ").concat(o.col,"\n")+"".concat(p("[JS Warning]")," Error => ").concat(JSON.stringify(o.error),"\n")+"".concat(p("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(s("[JS Error]")," on ").concat(y(t),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(s("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(s("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(s("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(s("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(s("[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())}(l,c.http.catcher_url),"guest"==c.auth_type&&ze(l,c.auth.guest,null==c?void 0:c.session),"basic"==c.auth_type&&Be(l,c.auth.basic),"credentials"==c.auth_type&&Ke(l,c.auth.credentials,null==c?void 0:c.session),"custom"==c.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,"'"))}})(l,c.auth.custom);var u=null==c?void 0:c.middlewares;return u&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(l,u),null!=c&&c.routes&&ir(l,c.routes),null!=(null==t?void 0:t.middleware)?l.use(t.middleware):function(e,r,o,t){var n=(null==r?void 0:r.html)||cr;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=ie((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=ie((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)}))}(l,t,c.http,null==c?void 0:c.auth),fr(l,null==c?void 0:c.cron),function(e,r){var o,t=e.context.miolo.logger,n=function(){var o=ie((function*(){try{var o,n,i;if(null!=(null===(o=e.http)||void 0===o?void 0:o.server))return void t.warn("[http][start] Server already running on ".concat(null==e||null===(n=e.http)||void 0===n?void 0:n.hostname,":").concat(null==e||null===(i=e.http)||void 0===i?void 0:i.port));var a=Q.createServer(e.callback()),l=$({server:a}),c=function(){var o=ie((function*(){try{yield l.terminate(),delete e.http.server,t.info("[http][stop] miolo has been shutdowned from ".concat(r.hostname,":").concat(r.port))}catch(o){t.error("[http][stop] error: ".concat(o))}}));return function(){return o.apply(this,arguments)}}();e.http.server=a,e.http.stop=c,yield vr(a,r.port,r.hostname),t.info("[http][start] miolo is listening on ".concat(r.hostname,":").concat(r.port))}catch(u){t.error("[http][start] error: ".concat(u))}}));return function(){return o.apply(this,arguments)}}();e.http={server:void 0,start:n,stop:(o=ie((function*(){t.warn("[http] stop() stop() function still not attached. Is server running?")})),function(){return o.apply(this,arguments)}),hostname:r.hostname,port:r.port}}(l,null==c?void 0:c.http),l.start=ie((function*(){l.context.miolo.db.initConnection(),yield l.http.start(),l.cron.start()})),l.stop=ie((function*(){l.context.miolo.db.dropConnections(),yield l.http.stop(),l.cron.stop()})),l.restart=ie((function*(){yield l.stop(),yield l.start()})),l}function mr(e){var r=ee.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(f("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof ee.ReplyError?"".concat(f("REDIS")," ").concat(s("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(f("REDIS")," ").concat(s("Error "+e.code)," ").concat(e.toString())}catch(o){r="".concat(f("REDIS")," ").concat(s("Error ")," ").concat(o)}console.error(r)})),o=x(r.get).bind(r),t=x(r.exists).bind(r),n=x(r.set).bind(r),i=x(r.del).bind(r);function a(){return(a=ie((function*(e){return yield o(e)}))).apply(this,arguments)}function l(){return(l=ie((function*(e){return 1==(yield t(e))}))).apply(this,arguments)}function c(){return c=ie((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=ie((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{pr as miolo,mr as miolo_cacher,se as miolo_emailer,he as miolo_logger,ye as miolo_parser};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.36
2
+ * miolo v0.9.37
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1360,17 +1360,19 @@ var CUSTOM_BLACKLIST_IPS = ['52.212.247.108',
1360
1360
  function init_rate_limit_middleware(app, config) {
1361
1361
  /* eslint-disable no-unused-vars */
1362
1362
  var miolo = app.context.miolo;
1363
- var _get_ip = ctx => ctx.headers["x-real-ip"] || ctx.headers["x-orig-ip"] || ctx.ip || '127.0.0.1';
1363
+
1364
+ //const _get_ip = (ctx) => ctx.headers["x-real-ip"] || ctx.headers["x-orig-ip"] || ctx.ip || '127.0.0.1'
1365
+
1364
1366
  var ipsum_ips = ipsum_read_ips(config === null || config === void 0 ? void 0 : config.ipsum_folder, undefined, miolo.logger);
1365
1367
  var _def_whitelist = ctx => {
1366
1368
  var ips = (config === null || config === void 0 ? void 0 : config.whitelist_ips) || [];
1367
1369
  if (ips) {
1368
- return ips.indexOf(_get_ip(ctx)) >= 0;
1370
+ return ips.indexOf(ctx.request.ip) >= 0;
1369
1371
  }
1370
1372
  return false;
1371
1373
  };
1372
1374
  var _def_blacklist = ctx => {
1373
- var ip = _get_ip(ctx);
1375
+ var ip = ctx.request.ip;
1374
1376
  var ips = [...ipsum_ips, ...CUSTOM_BLACKLIST_IPS, ...((config === null || config === void 0 ? void 0 : config.blacklist_ips) || [])];
1375
1377
  var doit = ips.indexOf(ip) >= 0;
1376
1378
  if (doit) {
@@ -1382,7 +1384,7 @@ function init_rate_limit_middleware(app, config) {
1382
1384
  var rateLimitConfig = {
1383
1385
  driver: 'memory',
1384
1386
  db: rateLimitDB,
1385
- id: _get_ip,
1387
+ id: ctx => ctx.request.ip,
1386
1388
  headers: {
1387
1389
  remaining: 'Rate-Limit-Remaining',
1388
1390
  reset: 'Rate-Limit-Reset',
@@ -1419,7 +1421,7 @@ var init_static_middleware = (app, config) => {
1419
1421
  };
1420
1422
 
1421
1423
  var _geoip_reader = undefined;
1422
- var _geoip_local_ips = ['127.0.0.1'];
1424
+ var _geoip_local_ips = ['127.0.0.1', '::1:'];
1423
1425
  function _geoip_init() {
1424
1426
  var db = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '/var/lib/GeoIP/GeoLite2-City.mmdb';
1425
1427
  var local_ips = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['127.0.0.1'];
@@ -1468,6 +1470,20 @@ var geoip_localize_ip = function geoip_localize_ip(ip, config) {
1468
1470
  var REQUEST_COUNTER = {
1469
1471
  total: 0
1470
1472
  };
1473
+ function _validate_ip(ipaddress) {
1474
+ if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {
1475
+ return true;
1476
+ }
1477
+ return false;
1478
+ }
1479
+ var _get_ip = ctx => {
1480
+ var chances = [ctx.headers["x-real-ip"], ctx.headers["x-orig-ip"], ctx.ip, '127.0.0.1'];
1481
+ for (var ch of chances) {
1482
+ if (_validate_ip(ch)) {
1483
+ return ch;
1484
+ }
1485
+ }
1486
+ };
1471
1487
 
1472
1488
  /**
1473
1489
  * Middleware for feed and log the request
@@ -1505,7 +1521,7 @@ function init_request_middleware(app, config) {
1505
1521
  _request_middleware = _asyncToGenerator(function* (ctx, next) {
1506
1522
  var _reqConfig$geoip, _geo_info, _geo_info2, _geo_info3, _geo_info4, _ctx$session;
1507
1523
  var logger = ctx.miolo.logger;
1508
- var ip = ctx.headers["x-real-ip"] || ctx.headers["x-orig-ip"] || ctx.ip || '127.0.0.1';
1524
+ var ip = _get_ip(ctx);
1509
1525
  var started = performance.now();
1510
1526
 
1511
1527
  // Patch for koa-better-body