@andrewcaires/api 5.2.1 → 5.2.2

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.
package/dist/index.cjs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/api v5.2.1
2
+ * @andrewcaires/api v5.2.2
3
3
  * Simple api for small applications using express, jsonwebtoken, sequelize and websocket
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- "use strict";var e,t=require("@andrewcaires/express"),r=require("@andrewcaires/node"),o=require("@andrewcaires/utils.js"),s=require("ws"),i=require("@andrewcaires/sequelize"),n=require("dotenv"),d=require("express-session"),l=require("@andrewcaires/decorator"),a=require("jsonwebtoken"),u=require("@node-rs/argon2"),p=require("fs"),c=require("path");function g(e,t,r,o){var s,i=arguments.length,n=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(s=e[d])&&(n=(i<3?s(n):i>3?s(t,r,n):s(t,r))||n);return i>3&&n&&Object.defineProperty(t,r,n),n}function v(e,t){return function(r,o){t(r,o,e)}}function h(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function y(e,t,r,o){return new(r||(r=Promise))(function(s,i){function n(e){try{l(o.next(e))}catch(e){i(e)}}function d(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,d)}l((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,n.config({quiet:!0});class Env extends r.Env{}e=Env,Env.BASE_NAME=e.getString("BASE_NAME",""),Env.CONSOLE_ERROR=e.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=e.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=e.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=e.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=e.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=e.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=e.getString("HTTP_CROSS",""),Env.HTTP_TLS_CA=e.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=e.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=e.getFile("HTTP_TLS_KEY"),Env.MODEL_LIMIT=e.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=e.getInt("MODEL_LIMIT_MAX",100),Env.PASSWORD_ALGORITHM=e.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=e.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=e.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=e.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=e.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=e.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=e.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=e.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=e.getFile("TOKEN_CRT"),Env.TOKEN_KEY=e.getFile("TOKEN_KEY"),Env.TOKEN_TTL=e.getMs("TOKEN_TTL","1d"),Env.TOKEN_TYPE=e.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=e.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=e.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=e.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=e.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=e.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=e.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_HYBRID=e.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=e.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=e.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=e.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=e.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=e.getString("API_KEY_HEADER","x-api-key"),Env.API_SESSION_NAME=e.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=e.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=e.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=e.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=e.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=e.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=e.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_RENEW=e.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=e.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=e.getBool("API_WEBSOCKET_START",!1);const x=new i.Sequelize({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>r.Log.console(r.LogColor.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var m,C,E;exports.AuditTypes=void 0,(m=exports.AuditTypes||(exports.AuditTypes={})).CREATE="CREATE",m.DELETE="DELETE",m.UPDATE="UPDATE",exports.Loglevels=void 0,(C=exports.Loglevels||(exports.Loglevels={})).INFO="info",C.WARN="warn",C.ERROR="error",exports.UserStatus=void 0,(E=exports.UserStatus||(exports.UserStatus={})).ACTIVE="active",E.PENDING="pending",E.DISABLED="disabled",E.LOCKED="locked",E.ARCHIVED="archived";const A=e=>r=>(s,i,n)=>{t.Use(s=>y(void 0,void 0,void 0,function*(){var i;o.isUndefined(r)&&(r=o.isFunction(s.controller.name)?s.controller.name():null===(i=s.controller.constructor)||void 0===i?void 0:i.name);const{permissions:n=[]}=s.req;if(n.includes(`${r}.${e}`))return s.next();s.error(new t.UnauthorizedError("Access Denied"))}))(s,i,n)},S=A("create"),_=A("delete"),f=A("read"),M=A("update"),P=()=>(e,r,o)=>{t.Use(e=>y(void 0,void 0,void 0,function*(){yield(e=>y(void 0,void 0,void 0,function*(){var r,o,s,i;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:n,[Env.API_TOKEN_HEADER]:d,"user-agent":l}=e.getHeaders(),a=e.getQuery(Env.API_KEY_HEADER),u=(null===(r=n||a)||void 0===r?void 0:r.toString())||"";let p=e.getCookie(Env.API_TOKEN_COOKIE);p=`${Env.TOKEN_TYPE} ${p}`;const[c,g]=null!==(s=null===(o=d||p)||void 0===o?void 0:o.split(" "))&&void 0!==s?s:["",""];if(!(u||g&&c.toLowerCase()==Env.TOKEN_TYPE))return e.error(new t.UnauthorizedError("Invalid token"));const{authService:v,userService:h}=e.app,{auth:y,user:x}=null!==(i=yield(u?v.key(u.toString()):v.user(g)).catch(t=>{e.error(t)}))&&void 0!==i?i:{};if(!y||!x)return;if(!u&&y.user_agent&&y.user_agent!=l)return e.error(new t.UnauthorizedError("Invalid token"));e.req.auth=y,e.req.user=x;const{groups:m,permissions:C}=yield h.getGroupsPermissions(x.id);e.req.groups=m,e.req.permissions=C,e.next()}))(e)}))(e,r,o)},O=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),T=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.groups)&&void 0!==o?o:[]).includes(t)}),I=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==r?r:[]}),w=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.permissions)&&void 0!==o?o:[]).includes(t)}),U=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==r?r:[]}),b=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),R=(e,r,o)=>{var s,i,n,d,l,a,u,p,c,g,v;const h=o.ctx instanceof t.Context?o.ctx:null,y=null!==(s=null==h?void 0:h.id)&&void 0!==s?s:null,x=null!==(l=null!==(d=null===(n=null===(i=null==h?void 0:h.req)||void 0===i?void 0:i.user)||void 0===n?void 0:n.id)&&void 0!==d?d:o.user_id)&&void 0!==l?l:null,m={type:e,model:null!==(a=null==r?void 0:r.getTableName())&&void 0!==a?a:null,source:null!==(u=Env.BASE_NAME)&&void 0!==u?u:"",request_id:y,user_id:x};return h?Object.assign(Object.assign({},m),{full_url:null!==(p=h.getUrl())&&void 0!==p?p:"",ip_address:null!==(c=h.getIp())&&void 0!==c?c:"",user_agent:null!==(v=null===(g=h.req)||void 0===g?void 0:g.headers["user-agent"])&&void 0!==v?v:""}):m},D=e=>{const t=o.getConstructor(e),r=t.primaryKeyAttribute;return{model:t,record_id:r?e.getDataValue(r):null}},L={afterCreate:(e,t)=>y(void 0,void 0,void 0,function*(){const{model:o,record_id:s}=D(e);yield exports.AuditModel.create(Object.assign(Object.assign({},R(exports.AuditTypes.CREATE,o,t)),{record:s,currently:e.toJSON()})).catch(r.Log.catch)}),afterUpdate:(e,t)=>y(void 0,void 0,void 0,function*(){const{model:o,record_id:s}=D(e),i={},n={},d=e.changed();d&&d.length&&d.forEach(t=>{i[t]=e.getDataValue(t),n[t]=e.previous(t)}),yield exports.AuditModel.create(Object.assign(Object.assign({},R(exports.AuditTypes.UPDATE,o,t)),{record:s,currently:i,previously:n})).catch(r.Log.catch)}),afterDestroy:(e,t)=>y(void 0,void 0,void 0,function*(){const{model:o,record_id:s}=D(e);yield exports.AuditModel.create(Object.assign(Object.assign({},R(exports.AuditTypes.DELETE,o,t)),{record:s,currently:e.toJSON()})).catch(r.Log.catch)})},N=e=>(o.isUndefined(e)&&(e=Env.DATABASE_AUDIT),i.Hooks(e?L:{}));exports.RegisterModel=class RegisterModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.RegisterModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.RegisterModel.prototype,"secret",void 0),g([i.Column.FullDate(),h("design:type",Number)],exports.RegisterModel.prototype,"expired_at",void 0),g([i.Column.Boolean(),h("design:type",Boolean)],exports.RegisterModel.prototype,"active",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.RegisterModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.RegisterModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.RegisterModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.RegisterModel.prototype,"user_id",void 0),exports.RegisterModel=g([i.Database(x),i.ModelName("register"),i.Version("5.2.0")],exports.RegisterModel),exports.UserAuthModel=class UserAuthModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.UserAuthModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.UserAuthModel.prototype,"secret",void 0),g([i.Column.String(),h("design:type",String)],exports.UserAuthModel.prototype,"ip_address",void 0),g([i.Column.String(),h("design:type",String)],exports.UserAuthModel.prototype,"user_agent",void 0),g([i.Column.FullDate(),h("design:type",Object)],exports.UserAuthModel.prototype,"revoked_at",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.UserAuthModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.UserAuthModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.UserAuthModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.UserAuthModel.prototype,"user_id",void 0),exports.UserAuthModel=g([i.Database(x),i.ModelName("users_auth"),i.Version("5.2.0")],exports.UserAuthModel),exports.PermissionModel=class PermissionModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.PermissionModel.prototype,"id",void 0),g([i.Column.String(),i.Index(),h("design:type",String)],exports.PermissionModel.prototype,"name",void 0),g([i.Column.Text(),h("design:type",String)],exports.PermissionModel.prototype,"description",void 0),g([i.Column.Boolean(),h("design:type",Boolean)],exports.PermissionModel.prototype,"active",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.PermissionModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.PermissionModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.PermissionModel.prototype,"deleted_at",void 0),g([i.Association.HasMany(()=>exports.GroupPermissionModel),h("design:type",Array)],exports.PermissionModel.prototype,"groups_permissions",void 0),exports.PermissionModel=g([i.Database(x),i.ModelName("permission"),N(),i.Version("5.2.1")],exports.PermissionModel),exports.GroupPermissionModel=class GroupPermissionModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.GroupPermissionModel.prototype,"id",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.GroupPermissionModel.prototype,"created_at",void 0),g([i.Association.BelongsTo(()=>exports.GroupModel),h("design:type",String)],exports.GroupPermissionModel.prototype,"group_id",void 0),g([i.Association.BelongsTo(()=>exports.PermissionModel),h("design:type",String)],exports.GroupPermissionModel.prototype,"permission_id",void 0),exports.GroupPermissionModel=g([i.Database(x),i.ModelName("groups_permissions"),N(),i.Version("5.2.0")],exports.GroupPermissionModel),exports.GroupModel=class GroupModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.GroupModel.prototype,"id",void 0),g([i.Column.String(),i.Index(),h("design:type",String)],exports.GroupModel.prototype,"name",void 0),g([i.Column.Text(),h("design:type",String)],exports.GroupModel.prototype,"description",void 0),g([i.Column.Boolean(),h("design:type",Boolean)],exports.GroupModel.prototype,"active",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.GroupModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.GroupModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.GroupModel.prototype,"deleted_at",void 0),g([i.Association.HasMany(()=>exports.UserGroupModel),h("design:type",Array)],exports.GroupModel.prototype,"users_groups",void 0),g([i.Association.HasMany(()=>exports.GroupPermissionModel),h("design:type",Array)],exports.GroupModel.prototype,"groups_Permission",void 0),exports.GroupModel=g([i.Database(x),i.ModelName("group"),N(),i.Version("5.2.1")],exports.GroupModel),exports.UserGroupModel=class UserGroupModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.UserGroupModel.prototype,"id",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.UserGroupModel.prototype,"created_at",void 0),g([i.Association.BelongsTo(()=>exports.GroupModel),h("design:type",String)],exports.UserGroupModel.prototype,"group_id",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.UserGroupModel.prototype,"user_id",void 0),exports.UserGroupModel=g([i.Database(x),i.ModelName("users_groups"),N(),i.Version("5.2.0")],exports.UserGroupModel),exports.UserPasswordModel=class UserPasswordModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.UserPasswordModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.UserPasswordModel.prototype,"hash",void 0),g([i.Column.FullDate(),h("design:type",Object)],exports.UserPasswordModel.prototype,"revoked_at",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.UserPasswordModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.UserPasswordModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.UserPasswordModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.UserPasswordModel.prototype,"user_id",void 0),exports.UserPasswordModel=g([i.Database(x),i.ModelName("users_password"),N(),i.Version("5.2.0")],exports.UserPasswordModel),exports.UserModel=class UserModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.UserModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.UserModel.prototype,"name",void 0),g([i.Column.String(),h("design:type",String)],exports.UserModel.prototype,"username",void 0),g([i.Column.String(),h("design:type",String)],exports.UserModel.prototype,"email",void 0),g([i.Column.Text(),h("design:type",String)],exports.UserModel.prototype,"notes",void 0),g([i.Column.Enum(exports.UserStatus),i.DefaultValue(exports.UserStatus.ACTIVE),h("design:type",String)],exports.UserModel.prototype,"status",void 0),g([i.Column.Json(),i.DefaultValue(()=>({})),h("design:type",Object)],exports.UserModel.prototype,"metadata",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.UserModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.UserModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.UserModel.prototype,"deleted_at",void 0),g([i.Association.HasMany(()=>exports.AuditModel),h("design:type",Array)],exports.UserModel.prototype,"audits",void 0),g([i.Association.HasMany(()=>exports.UserAuthModel),h("design:type",Array)],exports.UserModel.prototype,"users_auths",void 0),g([i.Association.HasMany(()=>exports.RegisterModel),h("design:type",Array)],exports.UserModel.prototype,"registers",void 0),g([i.Association.HasMany(()=>exports.UserGroupModel),h("design:type",Array)],exports.UserModel.prototype,"users_groups",void 0),g([i.Association.HasMany(()=>exports.UserPasswordModel),h("design:type",Array)],exports.UserModel.prototype,"users_passwords",void 0),exports.UserModel=g([i.Database(x),i.ModelName("user"),N(),i.Version("5.2.0")],exports.UserModel),exports.AuditModel=class AuditModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.AuditModel.prototype,"id",void 0),g([i.Column.Enum(exports.AuditTypes),h("design:type",String)],exports.AuditModel.prototype,"type",void 0),g([i.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"model",void 0),g([i.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"record",void 0),g([i.Column.Json(),h("design:type",Object)],exports.AuditModel.prototype,"currently",void 0),g([i.Column.Json(),h("design:type",Object)],exports.AuditModel.prototype,"previously",void 0),g([i.Column.String(36),h("design:type",String)],exports.AuditModel.prototype,"request_id",void 0),g([i.Column.Text(),h("design:type",String)],exports.AuditModel.prototype,"full_url",void 0),g([i.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"ip_address",void 0),g([i.Column.Text(),h("design:type",String)],exports.AuditModel.prototype,"user_agent",void 0),g([i.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"source",void 0),g([i.Column.FullDate(),h("design:type",Object)],exports.AuditModel.prototype,"reverted_at",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.AuditModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.AuditModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.AuditModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.AuditModel.prototype,"user_id",void 0),exports.AuditModel=g([i.Database(x),i.ModelName("audit"),i.Version("5.2.0")],exports.AuditModel),exports.ConfigModel=class ConfigModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.ConfigModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.ConfigModel.prototype,"key",void 0),g([i.Column.Text(),h("design:type",String)],exports.ConfigModel.prototype,"value",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.ConfigModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.ConfigModel.prototype,"updated_at",void 0),exports.ConfigModel=g([i.Database(x),i.ModelName("configs"),i.Version("5.2.0")],exports.ConfigModel),exports.ForgotModel=class ForgotModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.ForgotModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.ForgotModel.prototype,"secret",void 0),g([i.Column.FullDate(),h("design:type",Number)],exports.ForgotModel.prototype,"expired_at",void 0),g([i.Column.Boolean(),h("design:type",Boolean)],exports.ForgotModel.prototype,"active",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.ForgotModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.ForgotModel.prototype,"updated_at",void 0),g([i.Column.DeletedAt(),h("design:type",Object)],exports.ForgotModel.prototype,"deleted_at",void 0),g([i.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.ForgotModel.prototype,"user_id",void 0),exports.ForgotModel=g([i.Database(x),i.ModelName("forgot"),i.Version("5.2.0")],exports.ForgotModel),exports.LogModel=class LogModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.LogModel.prototype,"id",void 0),g([i.Column.Enum(exports.Loglevels),i.DefaultValue(exports.Loglevels.INFO),h("design:type",String)],exports.LogModel.prototype,"level",void 0),g([i.Column.Text(),h("design:type",String)],exports.LogModel.prototype,"message",void 0),g([i.Column.String(),h("design:type",String)],exports.LogModel.prototype,"source",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.LogModel.prototype,"created_at",void 0),exports.LogModel=g([i.Database(x),i.ModelName("log"),i.Version("5.2.0")],exports.LogModel),exports.MigrationModel=class MigrationModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.MigrationModel.prototype,"id",void 0),g([i.Column.String(),h("design:type",String)],exports.MigrationModel.prototype,"model",void 0),g([i.Column.String(),h("design:type",String)],exports.MigrationModel.prototype,"version",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.MigrationModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.MigrationModel.prototype,"updated_at",void 0),exports.MigrationModel=g([i.Database(x),i.ModelName("migration"),i.Version("5.2.0")],exports.MigrationModel),exports.SessionModel=class SessionModel extends i.Model{},g([i.Column.Id(7),h("design:type",String)],exports.SessionModel.prototype,"id",void 0),g([i.Column.Json(),h("design:type",Object)],exports.SessionModel.prototype,"data",void 0),g([i.Column.FullDate(),h("design:type",Date)],exports.SessionModel.prototype,"expired_at",void 0),g([i.Column.CreatedAt(),h("design:type",Date)],exports.SessionModel.prototype,"created_at",void 0),g([i.Column.UpdatedAt(),h("design:type",Date)],exports.SessionModel.prototype,"updated_at",void 0),exports.SessionModel=g([i.Database(x),i.ModelName("session"),i.Version("5.2.0")],exports.SessionModel);class Log{static error(e,t,r){return y(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,r)})}static info(e,t,r){return y(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,r)})}static warn(e,t,r){return y(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,r)})}static writeRaw(e,t,o,s){return y(this,void 0,void 0,function*(){var i;s&&r.Log.console(null!==(i=this.colors[e])&&void 0!==i?i:r.LogColor.White,e,t),x&&(yield exports.LogModel.create({level:e,message:t,source:null!=o?o:""}).catch(r.Log.catch))})}}Log.colors={error:r.LogColor.Red,info:r.LogColor.Cyan,warn:r.LogColor.Yellow};class Loggable{get log(){return e=>Loggable.logInfo(this,e)}static get log(){return e=>this.logInfo(this,e)}get error(){return e=>Loggable.logError(this,e)}static get error(){return e=>this.logError(this,e)}static logError(e,t){var r,o;Log.error(null!==(o=null!==(r=null==t?void 0:t.message)&&void 0!==r?r:t)&&void 0!==o?o:"",this.source(e),Env.CONSOLE_ERROR)}static logInfo(e,t){Log.info(null!=t?t:"",this.source(e),Env.CONSOLE_ERROR)}static source(e){var t,r,o;const s=null!==(o=null!==(r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==r?r:null==e?void 0:e.name)&&void 0!==o?o:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${s}`:s}}class SessionStore extends d.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,function*(){e=e||o.noop;const t=yield exports.SessionModel.findAll({attributes:["id","expired_at"],where:{expired_at:{[i.Op.gte]:new Date}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.id)),e()}),this.clear=e=>y(this,void 0,void 0,function*(){yield exports.SessionModel.destroy().catch(r.Log.catch),e&&e()}),this.destroy=(e,t)=>y(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{id:e}}).catch(r.Log.catch),t&&t()}),this.expired=()=>y(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{expired_at:{[i.Op.lt]:new Date}}}).catch(r.Log.catch)}),this.get=(e,t)=>y(this,void 0,void 0,function*(){t=t||o.noop;const s=yield exports.SessionModel.findOne({where:{id:e,expired_at:{[i.Op.gte]:new Date}}}).catch(e=>(t(e),null));if(s){if(s.data.cookie){if(new Date(s.data.cookie.expires).getTime()<=Date.now())return yield s.destroy().catch(r.Log.catch),void t(null)}t(null,s.data)}else t(null)}),this.length=e=>y(this,void 0,void 0,function*(){e&&e(null,(yield exports.SessionModel.count().catch(r.Log.catch))||0)}),this.set=(e,t,s)=>y(this,void 0,void 0,function*(){s=s||o.noop;const i=new Date;i.setTime(i.getTime()+Env.API_SESSION_LIFETIME);const[n,d]=(yield exports.SessionModel.findOrCreate({where:{id:e},defaults:{id:e,data:t,expired_at:i}}).catch(r.Log.catch))||[];n?(d||(n.data=t,n.expired_at=i,yield n.save().catch(r.Log.catch)),s()):s()}),setInterval(this.expired,6e4)}}exports.Service=class Service{},exports.Service=g([l.Trait(Loggable)],exports.Service),exports.AuthService=class AuthService extends exports.Service{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return y(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{id:r}=e,s=o.uuidv7(),i=yield exports.UserAuthModel.create({secret:s,user_id:r}).catch(this.error);if(!i)throw new t.InternalServerError;return{auth:i,token:a.sign({id:r,secret:s},Env.TOKEN_KEY,this.options())}})}destroy(e){return y(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return y(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{decode:r}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:s,secret:i}=r;if(s&&i){const e=yield exports.UserModel.findOne({where:{id:s,status:exports.UserStatus.ACTIVE}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:i,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=o.uuidv7(),yield t.save().catch(this.error);return{auth:t,token:a.sign({id:s,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t.UnauthorizedError("Invalid token")})}user(e){return y(this,void 0,void 0,function*(){const{decode:r}=yield this.verify(e);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:o,secret:s}=r;if(o&&s){const e=yield exports.UserModel.findOne({attributes:this.userAttributes,where:{id:o,status:exports.UserStatus.ACTIVE}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t.UnauthorizedError("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,r){return y(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new t.NotFoundError("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t.UnauthorizedError("Invalid token");try{return{decode:a.verify(e,Env.TOKEN_CRT,{clockTolerance:r})}}catch(e){throw new t.UnauthorizedError("Invalid token")}})}key(e){return y(this,void 0,void 0,function*(){if(!e)throw new t.UnauthorizedError("Invalid token");const r=yield exports.UserModel.findOne({attributes:this.userAttributes,where:{token:e,status:exports.UserStatus.ACTIVE}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[o]=(yield exports.UserAuthModel.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(o)return o.revoked_at&&(o.revoked_at=null,yield o.save().catch(this.error)),{auth:o,user:r}}throw new t.UnauthorizedError("Invalid token")})}},exports.AuthService=g([l.Singleton()],exports.AuthService);class ModelService extends exports.Service{constructor(e,t){var r,o;super(),this.attributes=[],this.permissions=[],this.search=[],this.model=e,(null==t?void 0:t.permissions)&&(this.permissions=t.permissions);const s=Object.keys(e.getAttributes());this.attributes=this.filterAttributes(s,null!==(r=null==t?void 0:t.attributes)&&void 0!==r?r:[]),this.search=this.filterAttributes(s,null!==(o=null==t?void 0:t.search)&&void 0!==o?o:this.attributes)}applySelect(e,t,r){if(!t)return;const s=null==e?void 0:e.getQuery(r?`${r}_select`:"select"),i=t.attributes,n=e=>i.includes(e);t.attributes=[],o.isString(s)&&s.length&&t.attributes.push(...s.split(/\s*,\s*/g).filter(n)),t.attributes.length||(t.attributes=i)}applyOrders(e,t){if(!t)return;const r=null==e?void 0:e.getQuery("asc"),s=null==e?void 0:e.getQuery("desc"),i=[],n=t.attributes,d=e=>n.includes(e);o.isString(r)&&r.length&&i.push(...r.split(/\s*,\s*/g).filter(d).map(e=>[e,"ASC"])),o.isString(s)&&s.length&&i.push(...s.split(/\s*,\s*/g).filter(d).map(e=>[e,"DESC"])),i.length&&(t.order=i)}applyPagination(e,t){if(!t)return;const r=null==e?void 0:e.getQuery("limit"),s=null==e?void 0:e.getQuery("offset");o.isUndefined(t.limit)&&(t.limit=Env.MODEL_LIMIT,o.isString(r)&&(t.limit=parseInt(r)||0),t.limit=o.clamp(t.limit,-1,Env.MODEL_LIMIT_MAX)),t.limit<0&&(t.limit=void 0),o.isString(s)&&(t.offset=parseInt(s)||0,t.offset<0&&(t.offset=void 0))}applySearch(e,t){var r;if(!t)return;const s=null==e?void 0:e.getQuery("search");s&&o.isString(s)&&(t.where=Object.assign(Object.assign({},null!==(r=t.where)&&void 0!==r?r:{}),{[i.Op.or]:this.search.map(e=>({[e]:{[i.Op.substring]:s}}))}))}applyWhere(e,r,s){var n,d;if(!r)return null;const l=null==e?void 0:e.getQuery(s?`${s}_where`:"where");if(!o.isString(l))return null;const a=r.attributes,u=i.Where.parse(a,l);return o.isUndefined(u.error)?(r.where=Object.assign(Object.assign({},null!==(n=r.where)&&void 0!==n?n:{}),null!==(d=u.value)&&void 0!==d?d:{}),null):new t.ValidationError(u.error.join(", "))}countAll(e){return y(this,void 0,void 0,function*(){var r,s;const{ctx:i,options:n={}}=e,d=o.merge({},n);d.attributes=this.getAttributes(null!==(r=null==d?void 0:d.attributes)&&void 0!==r?r:[]),this.applySearch(i,d);const l=this.applyWhere(i,d);if(l)return null==i||i.error(l),0;this.applySelect(i,d);const a=null!==(s=yield this.model.count(Object.assign(Object.assign({},d),{distinct:!!d.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==s?s:0;return null==i||i.prepare(t.StatusCodes.OK,{count:a}),a})}create(e){return y(this,void 0,void 0,function*(){var r,s;const{body:i={},ctx:n,options:d={}}=e,l=o.merge({},d),a=yield this.model.create(Object.assign({},o.merge({},null!==(s=null===(r=null==n?void 0:n.req)||void 0===r?void 0:r.body)&&void 0!==s?s:{},i)),Object.assign(Object.assign({},l),{ctx:n})).catch(this.error);if(!a)return null==n||n.error(new t.InternalServerError),null;const{primaryKeyAttribute:u}=this.model;return null==n||n.prepare(t.StatusCodes.OK,{[u]:a.getDataValue(u)}),a})}delete(e){return y(this,void 0,void 0,function*(){var r,s;const{ctx:i,id:n,options:d={}}=e,{primaryKeyAttribute:l}=this.model,a=null!==(r=null==i?void 0:i.getParam(l))&&void 0!==r?r:n;if(o.isUndefined(a))return null==i||i.error(new t.BadRequestError),0;const u=o.merge({},d),p=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},u),{where:Object.assign(Object.assign({},null!==(s=u.where)&&void 0!==s?s:{}),{[l]:a}),individualHooks:!0}),{ctx:i})).catch(this.error);return p?(null==i||i.success("OK"),p):(null==i||i.error(new t.NotFoundError),0)})}filterAttributes(e,t){if(o.isArray(t))return t.length?t.filter(t=>o.isString(t)&&e.includes(t)):e;const{exclude:r,include:s}=t,i=o.isUndefined(s)?e:s.filter(t=>o.isString(t)&&e.includes(t)),n=null!=r?r:[];return n.length?i.filter(e=>!n.includes(e)):i}findAll(e){return y(this,void 0,void 0,function*(){var r,s;const{ctx:i,callback:n,options:d={},query:l=!0}=e,a=o.merge({},d);if(a.attributes=this.getAttributes(null!==(r=null==a?void 0:a.attributes)&&void 0!==r?r:[]),l&&this.applySelect(i,a),this.applyOrders(i,a),this.applyPagination(i,a),(null!==(s=null==a?void 0:a.limit)&&void 0!==s?s:0)>Env.MODEL_LIMIT_MAX&&(a.limit=Env.MODEL_LIMIT_MAX),this.applySearch(i,a),l){const e=this.applyWhere(i,a);if(e)return null==i||i.error(e),{count:0,records:[]}}const[u,p]=yield Promise.all([this.model.count(Object.assign(Object.assign({},a),{distinct:!!a.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error).then(e=>null!=e?e:0),this.model.findAll(a).catch(this.error).then(e=>null!=e?e:[])]),c={count:u,records:n?yield n(p):p};return null==i||i.prepare(t.StatusCodes.OK,c),c})}findOne(e){return y(this,void 0,void 0,function*(){var r,s,i;const{callback:n,ctx:d,id:l,options:a={},query:u=!0}=e,{primaryKeyAttribute:p}=this.model,c=null!==(r=null==d?void 0:d.getParam(p))&&void 0!==r?r:l;if(o.isUndefined(c))return null==d||d.error(new t.BadRequestError),null;const g=o.merge({},a);g.attributes=this.getAttributes(null!==(s=null==g?void 0:g.attributes)&&void 0!==s?s:[]),u&&this.applySelect(d,g);const v=yield this.model.findOne(Object.assign(Object.assign({},g),{where:Object.assign(Object.assign({},null!==(i=null==g?void 0:g.where)&&void 0!==i?i:{}),{[p]:c})})).catch(this.error);return v?(null==d||d.prepare(t.StatusCodes.OK,n?yield n(v):v.toJSON()),v):(null==d||d.error(new t.NotFoundError),null)})}getAttributes(e){return this.filterAttributes(this.attributes,e)}include(e,t){var r;const s=o.clone(t),{ctx:i}=null!=t?t:{};s.attributes=this.filterAttributes(Object.keys(e.getAttributes()),null!==(r=s.attributes)&&void 0!==r?r:[]),this.applySearch(i,s);const n=this.applyWhere(i,s,t.name);return n?(null==i||i.error(n),null):(this.applySelect(i,s,t.name),Object.assign({model:e},s))}name(){return this.model.tableName}sync(){return y(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",active:!0};yield o.forEachAsync(this.permissions,r=>y(this,void 0,void 0,function*(){const s=`${e}.${r}`,i=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:s},defaults:Object.assign({name:`${i} ${o.upperCamelCase(r," ")}`,key:s,tags:i},t)})}))})}update(e){return y(this,void 0,void 0,function*(){var r,s,i,n,d;const{ctx:l,body:a,id:u,options:p={}}=e,{primaryKeyAttribute:c}=this.model,g=null!==(r=null==l?void 0:l.getParam(c))&&void 0!==r?r:u;if(o.isUndefined(g))return null==l||l.error(new t.BadRequestError),!1;const v=o.merge({},p),[h]=null!==(d=yield this.model.update(Object.assign({},o.merge({},null!==(i=null===(s=null==l?void 0:l.req)||void 0===s?void 0:s.body)&&void 0!==i?i:{},null!=a?a:{})),Object.assign(Object.assign(Object.assign({},v),{where:Object.assign(Object.assign({},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{}),{[c]:g}),individualHooks:!0}),{ctx:l})).catch(this.error))&&void 0!==d?d:[];return h?(null==l||l.success("OK"),!0):(null==l||l.success("Record not changed"),!1)})}}exports.UserService=class UserService extends exports.Service{constructor(){super(...arguments),this.hashOptions={algorithm:Env.PASSWORD_ALGORITHM,memoryCost:Env.PASSWORD_MEMORY_COST,parallelism:Env.PASSWORD_PARALLELISM,timeCost:Env.PASSWORD_TIME_COST}}createPassword(e,t,r){return y(this,void 0,void 0,function*(){yield exports.UserPasswordModel.update({revoked_at:new Date},{where:{revoked_at:null,user_id:e}}).catch(this.error);const o=u.hashSync(t+Env.PASSWORD_PEPPER,this.hashOptions);yield exports.UserPasswordModel.create({hash:o,user_id:e},Object.assign({},{ctx:r})).catch(this.error)})}findAllPermission(e){return y(this,void 0,void 0,function*(){var t;return null!==(t=yield exports.PermissionModel.findAll({attributes:["name"],where:{active:!0},include:[{association:"groups_permissions",required:!0,include:[{association:"group",required:!0,attributes:["id","name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]})}getGroups(e){return y(this,void 0,void 0,function*(){var t;return(null!==(t=yield exports.GroupModel.findAll({attributes:["name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.name)})}getGroupsPermissions(e){return y(this,void 0,void 0,function*(){const t=[],r=[];return(yield this.findAllPermission(e)).forEach(e=>{r.push(e.name),e.groups_permissions.forEach(e=>t.push(e.group.name))}),{groups:o.uniqueArray(t),permissions:o.uniqueArray(r)}})}getPermissions(e){return y(this,void 0,void 0,function*(){return(yield this.findAllPermission(e)).map(e=>e.name)})}},exports.UserService=g([l.Singleton()],exports.UserService);class Application extends t.Application{constructor(e,t){super(e,o.merge({},{cross:!!Env.HTTP_CROSS&&("*"===Env.HTTP_CROSS||{origin:Env.HTTP_CROSS.split(",")}),hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new SessionStore,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:o.uuidv7},tls:{ca:Env.HTTP_TLS_CA,cert:Env.HTTP_TLS_CRT,key:Env.HTTP_TLS_KEY}},null!=t?t:{})),this.hash=new r.Hash(Env.API_KEY_HASH)}error(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.error(e.message,t,Env.CONSOLE_ERROR)}log(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,function*(){yield x.sync(),yield this.migrations(x),yield o.forEachSeries(this.controllers,e=>y(this,void 0,void 0,function*(){o.isFunction(e.sync)&&(yield e.sync(this))})),this.authService=new exports.AuthService,this.userService=new exports.UserService,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new s.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>y(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield o.sleep(2e3)})))})}migrations(e){return y(this,void 0,void 0,function*(){const t=[];yield o.forEachSeries(Object.keys(e.models),r=>y(this,void 0,void 0,function*(){var o;const s=e.models[r],i=s.version();if(!i)return;const[n,d]=null!==(o=yield exports.MigrationModel.findOrCreate({where:{model:s.tableName},defaults:{model:s.tableName,version:""}}).catch(this.error))&&void 0!==o?o:[];n&&(d||n.version!=i)&&(n.version=i,yield n.save().catch(this.error),t.push(s))})),yield o.forEachSeries(t,e=>y(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}exports.BaseController=class BaseController extends o.EventEmitter{constructor(){super(...arguments),this.permissions=[]}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}session(e,t,r){return y(this,void 0,void 0,function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(o.noop):(r.user_agent=t,r.save(o.noop))),e.next()})}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," ");yield o.forEachSeries(this.permissions,r=>y(this,void 0,void 0,function*(){const s=`${e}.${r}`;yield exports.PermissionModel.findOrCreate({where:{name:s},defaults:{name:s,description:`${t} ${o.upperCamelCase(r," ")}`,active:!0}})}))})}},g([v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Session()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Object]),h("design:returntype",Promise)],exports.BaseController.prototype,"session",null),exports.BaseController=g([l.Trait(Loggable)],exports.BaseController),exports.ModelController=class ModelController extends exports.BaseController{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return y(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return y(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return y(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return y(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return y(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," ");yield o.forEachSeries(this.permissions,r=>y(this,void 0,void 0,function*(){const s=`${e}.${r}`;yield exports.PermissionModel.findOrCreate({where:{name:s},defaults:{name:s,description:`${t} ${o.upperCamelCase(r," ")}`,active:!0}})})),this.service=new ModelService(this.model,{attributes:this.attributes.length?this.attributes:void 0,search:this.search.length?this.search:void 0})})}update(e){return y(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}},exports.ModelController=g([t.Extends(exports.BaseController)],exports.ModelController),exports.AuditsController=class AuditsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.AuditModel,this.permissions=["read"]}all(e,t,r){return y(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["currently","previously"]},where:o,order:[["created_at","DESC"]]}})})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},g([t.Get(),P(),f(),v(0,t.Ctx()),v(1,t.Query("type")),v(2,t.Query("table")),h("design:type",Function),h("design:paramtypes",[t.Context,String,String]),h("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),g([t.Get("/:id"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=g([t.Controller("/audits"),t.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class AuthController extends exports.BaseController{constructor(){super(...arguments),this.authService=new exports.AuthService}login(e,r,s,n,d,l){return y(this,void 0,void 0,function*(){var a;yield o.sleep(Env.SLEEP_AUTH);const p=yield exports.UserModel.findOne({where:{[i.Op.or]:[{email:s},{username:s}]}}).catch(this.error);if(!p)return e.error(new t.UnauthorizedError("Invalid credentials")),l.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const c=yield exports.UserPasswordModel.findOne({where:{revoked_at:null,user_id:p.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!c||!(yield u.verify(c.hash,n).catch(o.noop)))return e.error(new t.UnauthorizedError("Invalid credentials")),l.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const g=yield exports.RegisterModel.findOne({where:{active:!0,user_id:p.id}}).catch(this.error);if(g)return e.error(new t.UnauthorizedError("Activation Required")),l.emit("auth.activation",{ctx:e,register:g,user:p}),void this.emit("auth.activation",{ctx:e,register:g,user:p});if(p.status!=exports.UserStatus.ACTIVE)return e.error(new t.UnauthorizedError("Invalid credentials")),l.emit("auth.failure",{ctx:e,user:p}),void this.emit("auth.failure",{ctx:e,user:p});const{auth:v,token:h}=null!==(a=yield this.authService.create(p).catch(t=>{e.error(t),l.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==a?a:{};v&&h&&(v.user_agent=r,v.ip_address=e.getIp(),yield v.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.setCookie(Env.API_TOKEN_COOKIE,h,{maxAge:d?Env.TOKEN_TTL:void 0}),e.json({token:h}),l.emit("auth.login",{ctx:e,auth:v,user:p}),this.emit("auth.login",{ctx:e,auth:v,user:p}))})}logout(e,r,o,s){return y(this,void 0,void 0,function*(){if(yield this.authService.destroy(r))return Env.API_TOKEN_COOKIE_SET&&e.clearCookie(Env.API_TOKEN_COOKIE),e.success("OK"),s.emit("auth.logout",{auth:r,ctx:e,user:o}),void this.emit("auth.logout",{auth:r,ctx:e,user:o});e.error(new t.UnauthorizedError("Access Denied"))})}renew(e,t,r,o){return y(this,void 0,void 0,function*(){var s;const{auth:i,token:n}=null!==(s=yield this.authService.renew(r).catch(t=>{e.error(t)}))&&void 0!==s?s:{};i&&n&&(i.user_agent=t,yield i.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:i,ctx:e}),this.emit("auth.renew",{auth:i,ctx:e}))})}user(e,r){return y(this,void 0,void 0,function*(){const{groups:o,permissions:s,profile:i}=e.req;if(!o||!s)return e.error(new t.InternalServerError);e.json(Object.assign(Object.assign({},r.toJSON()),{groups:o,permissions:s,profile:i}))})}},g([t.Post("/login"),t.Validate(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("username")),v(3,t.Body("password")),v(4,t.Body("remember")),v(5,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,String,String,Boolean,Application]),h("design:returntype",Promise)],exports.AuthController.prototype,"login",null),g([t.Get("/logout"),P(),v(0,t.Ctx()),v(1,O()),v(2,b()),v(3,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,exports.UserAuthModel,exports.UserModel,Application]),h("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),g([t.Post("/renew"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("token")),v(3,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,String,Application]),h("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),g([t.Get(),t.Get("/me"),P(),v(0,t.Ctx()),v(1,b()),h("design:type",Function),h("design:paramtypes",[t.Context,exports.UserModel]),h("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=g([t.Controller("/auth"),t.Extends(exports.BaseController)],exports.AuthController),exports.CrudController=class CrudController extends exports.ModelController{constructor(){super(...arguments),this._crud={}}CrudArgumentsCountAll(e){return{ctx:e}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidateCreate(){return this._crud}CrudValidateUpdate(){return this._crud}add(e){return y(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return y(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return y(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return y(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return y(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,r){return y(this,void 0,void 0,function*(){var s,i;const n=o.Validation.object(r).parse(),{error:d,message:l,value:a}=yield n.validateAsync(null!==(i=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==i?i:{});if(d)return e.error(new t.ValidationError(null!=l?l:d));e.req.body=a,e.next()})}validateCreate(e){return y(this,void 0,void 0,function*(){const r=this.CrudValidateCreate();if(r==this._crud)return e.error(new t.InternalServerError);yield this.validate(e,r)})}validateUpdate(e){return y(this,void 0,void 0,function*(){const r=this.CrudValidateUpdate();if(r==this._crud)return e.error(new t.InternalServerError);yield this.validate(e,r)})}},g([t.Post(),P(),S(),t.Middleware("validateCreate"),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"add",null),g([t.Get(),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"all",null),g([t.Get("/count"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"rows",null),g([t.Delete("/:id"),P(),_(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"del",null),g([t.Get("/:id"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"get",null),g([t.Put("/:id"),P(),M(),t.Middleware("validateUpdate"),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"set",null),g([v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"validateCreate",null),g([v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"validateUpdate",null),exports.CrudController=g([t.Extends(exports.ModelController)],exports.CrudController),exports.FilesController=class FilesController extends exports.BaseController{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return y(this,void 0,void 0,function*(){let{path:r}=e.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const s=c.join(this.directory,r);if(!p.existsSync(s)||!p.statSync(s).isDirectory())return e.error(new t.NotFoundError);let i;return i=p.readdirSync(s),i=i.map(e=>this.info(c.join(s,e))),i=i.filter(o.isDef),Object.assign(Object.assign({},this.info(s)),{files:i})})}info(e){if(!p.existsSync(e))return null;const t=p.statSync(e),r=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," ");yield o.forEachSeries(this.permissions,r=>y(this,void 0,void 0,function*(){const s=`${e}.${r}`;yield exports.PermissionModel.findOrCreate({where:{name:s},defaults:{name:s,description:`${t} ${o.upperCamelCase(r," ")}`,active:!0}})}))})}},g([t.Get("/path"),t.Get("/path/*path"),P(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.FilesController.prototype,"files",null),exports.FilesController=g([t.Controller("/files"),t.Extends(exports.BaseController)],exports.FilesController),exports.ForgotController=class ForgotController extends exports.BaseController{check(e,r){return y(this,void 0,void 0,function*(){const s=yield this.find(r);if(!s||!s.user)return e.error(new t.NotFoundError);s.secret=o.uniqueID(),yield s.save(),e.json({token:s.secret})})}forgot(e,r,s){return y(this,void 0,void 0,function*(){yield o.sleep(Env.SLEEP_FORGOT);const n=r,d=yield exports.UserModel.findOne({where:{[i.Op.or]:[{email:n},{username:r}]}}).catch(this.error);if(!d)return e.error(new t.NotFoundError);const l=o.uniqueID(),a=Date.now()+6e4*Env.API_TOKEN_FORGOT,u=yield exports.ForgotModel.create({token:l,timestamp:a,active:!0,user_id:d.id});e.success("OK"),s.emit("forgot.send",{ctx:e,forgot:u,user:d}),this.emit("forgot.send",{ctx:e,forgot:u,user:d})})}reset(e,r,o,s){return y(this,void 0,void 0,function*(){const o=yield this.find(r);if(!o)return e.error(new t.NotFoundError);o.active=!1,yield o.save().catch(this.error),yield o.user.save().catch(this.error),e.success("OK"),s.emit("forgot.reset",{ctx:e,user:o.user}),this.emit("forgot.reset",{ctx:e,user:o.user})})}find(e){return y(this,void 0,void 0,function*(){return yield exports.ForgotModel.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}},g([t.Get("/check"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),h("design:type",Function),h("design:paramtypes",[t.Context,String]),h("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),g([t.Post(),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Application]),h("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),g([t.Post("/reset"),t.Validate(e=>({token:e.string().required(),password:e.string().min(5).required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.Body("password")),v(3,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,String,Application]),h("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=g([t.Controller("/forgot"),t.Extends(exports.BaseController)],exports.ForgotController),exports.GroupsController=class GroupsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.GroupModel,this.schemaCreate={name:o.Validation.string().required(),description:o.Validation.string().empty(""),active:o.Validation.boolean().parse().required()},this.schemaUpdate={description:o.Validation.string().empty(),active:o.Validation.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}},exports.GroupsController=g([t.Controller("/groups"),t.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class GroupsPermissionsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.GroupPermissionModel,this.permissions=[]}all(e,t){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{association:"permission"}]},callback:e=>e.map(e=>e.permission),query:!1})})}set(e,r,s){return y(this,void 0,void 0,function*(){const n=yield exports.GroupModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=[];yield o.forEachSeries(o.uniqueArray(s),t=>y(this,void 0,void 0,function*(){var r;if(!(yield exports.PermissionModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.GroupPermissionModel.findOrCreate(Object.assign({where:{group_id:d,permission_id:t},defaults:{group_id:d,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.GroupPermissionModel.destroy(Object.assign({where:{group_id:d,permission_id:{[i.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/permissions"),P(),f("groups"),v(0,t.Ctx()),v(1,t.Params("id")),h("design:type",Function),h("design:paramtypes",[t.Context,String]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),g([t.Put("/:id/permissions"),P(),M("groups"),t.Validate(e=>({permissions:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("permissions")),h("design:type",Function),h("design:paramtypes",[t.Context,String,Array]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=g([t.Controller("/groups"),t.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.HealthController=class HealthController{ping(e){return y(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}},g([t.All("/"),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.HealthController.prototype,"ping",null),exports.HealthController=g([t.Controller("/health")],exports.HealthController),exports.LogsController=class LogsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.LogModel,this.permissions=["read"]}all(e){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]}})})}},g([t.Get(),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=g([t.Controller("/logs"),t.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class PermissionsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.PermissionModel,this.schemaCreate={name:o.Validation.string().required(),description:o.Validation.string().empty(""),active:o.Validation.boolean().parse().required()},this.schemaUpdate={description:o.Validation.string().empty(),active:o.Validation.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}},exports.PermissionsController=g([t.Controller("/permissions"),t.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class RegisterController extends exports.BaseController{register(e,s,n){return y(this,void 0,void 0,function*(){yield o.sleep(Env.SLEEP_REGISTRY);const{name:d,date:l,email:a,username:u,password:p,confirm:c}=s,g=u||a,v=r.sha256(p);if(yield exports.UserModel.count({where:{[i.Op.or]:[{email:a},{username:g}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(v!=r.sha256(c))return e.error("INVALID PASSWORD");const h=yield exports.UserModel.create({name:d,email:a,username:g,password:v,avatar:"",date:l,description:"",status:exports.UserStatus.PENDING}).catch(this.error);if(!h)return e.error(new t.InternalServerError);const y=yield exports.RegisterModel.create({token:yield this.getId(),active:!0,user_id:h.id}).catch(this.error);if(!y)return yield h.destroy().catch(this.error),e.error(new t.InternalServerError);e.success("OK"),n.emit("register.user",{ctx:e,register:y,user:h}),this.emit("register.user",{ctx:e,register:y,user:h})})}confirm(e,r,o){return y(this,void 0,void 0,function*(){const s=yield exports.RegisterModel.findOne({where:{token:r,active:!0},include:[{association:"users",required:!0}]}).catch(this.error);if(!s)return e.error(new t.NotFoundError);s.active=!1,yield s.save().catch(this.error),s.user.status=exports.UserStatus.ACTIVE,yield s.user.save().catch(this.error),e.success("OK"),o.emit("register.confirm",{ctx:e,register:s,user:s.user}),this.emit("register.confirm",{ctx:e,register:s,user:s.user})})}send(e,r,o){return y(this,void 0,void 0,function*(){const s=r,n=yield exports.RegisterModel.findOne({where:{active:!0},include:[{model:exports.UserModel,required:!0,where:{[i.Op.or]:[{email:s},{username:r}]}}]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);e.success("OK"),o.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return y(this,void 0,void 0,function*(){const e=o.uuidv7();return(yield exports.RegisterModel.count({where:{token:e}}))?this.getId():e})}},g([t.Post(),t.Validate(e=>({name:e.string().required(),date:e.date().required(),email:e.string().email().required(),username:e.string().min(4).empty(),password:e.string().min(5).required(),confirm:e.string().min(5).required()})),v(0,t.Ctx()),v(1,t.Body()),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,Object,Application]),h("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),g([t.Post("/confirm"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Application]),h("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),g([t.Post("/send"),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Application]),h("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=g([t.Controller("/register"),t.Extends(exports.BaseController)],exports.RegisterController),exports.SetupController=class SetupController extends exports.BaseController{constructor(){super(...arguments),this.userService=new exports.UserService}setup(e){return y(this,void 0,void 0,function*(){var r;if(yield exports.UserModel.count())return e.error(new t.NotFoundError("Endpoint Not Found"));const s=yield exports.UserModel.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:exports.UserStatus.ACTIVE},Object.assign({},{ctx:e})).catch(this.error);if(!s)return e.error(new t.InternalServerError);yield this.userService.createPassword(s.id,"admin",e);const i=yield exports.GroupModel.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield exports.UserGroupModel.create({user_id:s.id,group_id:i.id},Object.assign({},{ctx:e})),yield exports.GroupModel.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield exports.GroupModel.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const n=null!==(r=yield exports.PermissionModel.findAll({where:{active:!0}}).catch(this.error))&&void 0!==r?r:[];yield o.forEachSeries(n,t=>y(this,void 0,void 0,function*(){yield exports.GroupPermissionModel.create({group_id:i.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}},g([t.Get(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=g([t.Controller("/setup"),t.Extends(exports.BaseController)],exports.SetupController),exports.UsersController=class UsersController extends exports.ModelController{constructor(){super(),this.model=exports.UserModel,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&p.existsSync(Env.API_HTTP_PUBLIC)&&!p.existsSync(this.path)&&p.mkdirSync(this.path)}avatar(e,r){return y(this,void 0,void 0,function*(){var o;const s=e.getFiles();if(s.file&&s.file.length){const{filename:i,path:n}=null!==(o=s.file[0])&&void 0!==o?o:{};if(i){const o=yield exports.UserModel.findOne({where:{user_id:r.id}}).catch(this.error);if(!o)return p.lstatSync(n).isFile()&&p.rmSync(n),e.error(new t.InternalServerError);const s=this.path+"/"+o.metadata.avatar_url;if(p.existsSync(s)&&p.lstatSync(s).isFile()&&p.rmSync(s),o.changed("metadata",!0),o.metadata.avatar_url=i,yield o.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return y(this,void 0,void 0,function*(){var e;const t=o.uuidv7();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return y(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return y(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,r,o){return y(this,void 0,void 0,function*(){if(o.id==r)return e.error(new t.NotFoundError);yield this.delete({ctx:e})})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return y(this,void 0,void 0,function*(){yield this.update({ctx:e})})}},g([t.Post("/avatar"),P(),t.Upload({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),v(0,t.Ctx()),v(1,b()),h("design:type",Function),h("design:paramtypes",[t.Context,exports.UserModel]),h("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),g([t.Post(),P(),S(),t.Validate(e=>({name:e.string().required(),email:e.string().email().required(),username:e.string().min(3).required(),description:e.string().empty(""),state:e.boolean().parse().empty(!0)})),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"add",null),g([t.Get(),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"all",null),g([t.Get("/count"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"rows",null),g([t.Delete("/:id"),P(),_(),v(0,t.Ctx()),v(1,t.Params("id")),v(2,b()),h("design:type",Function),h("design:paramtypes",[t.Context,String,exports.UserModel]),h("design:returntype",Promise)],exports.UsersController.prototype,"del",null),g([t.Get("/:id"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"get",null),g([t.Put("/:id"),P(),M(),t.Validate(e=>({name:e.string().empty(),email:e.string().email().empty(),username:e.string().min(3).empty(),description:e.string().empty(),state:e.boolean().parse().empty()})),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=g([t.Controller("/users"),t.Extends(exports.ModelController),h("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class UsersGroupsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.UserGroupModel,this.permissions=[]}all(e,r){return y(this,void 0,void 0,function*(){if(!(yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error)))return e.error(new t.NotFoundError("User Not Found"));yield this.findAll({ctx:e,options:{where:{user_id:r},include:[{association:"group"}]},callback:e=>e.map(e=>e.group),query:!1})})}set(e,r,s){return y(this,void 0,void 0,function*(){const n=yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError("User Not Found"));const d=n.id,l=[];yield o.forEachSeries(o.uniqueArray(s),t=>y(this,void 0,void 0,function*(){var r;if(!(yield exports.GroupModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.UserGroupModel.findOrCreate(Object.assign({where:{user_id:d,group_id:t},defaults:{user_id:d,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.UserGroupModel.destroy(Object.assign({where:{user_id:d,group_id:{[i.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/groups"),P(),f("users"),v(0,t.Ctx()),v(1,t.Params("id")),h("design:type",Function),h("design:paramtypes",[t.Context,String]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),g([t.Put("/:id/groups"),P(),M("users"),t.Validate(e=>({groups:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("groups")),h("design:type",Function),h("design:paramtypes",[t.Context,String,Array]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=g([t.Controller("/users"),t.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=Application,exports.Audit=N,exports.CanCreate=S,exports.CanDelete=_,exports.CanRead=f,exports.CanUpdate=M,exports.Config=class Config extends Loggable{static all(e){return y(this,void 0,void 0,function*(){var t;const r=null!==(t=yield exports.ConfigModel.findAll({where:(null==e?void 0:e.length)?{key:{[i.Op.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(r.map(e=>[e.key,e.value]))})}static del(e){return y(this,void 0,void 0,function*(){return((yield exports.ConfigModel.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return y(this,arguments,void 0,function*(e,t=""){const[r]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t){return y(this,void 0,void 0,function*(){const[r,o]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];r&&!o&&(r.value=t,yield r.save().catch(this.error))})}},exports.Env=Env,exports.HasGroups=(...e)=>(r,s,i)=>{t.Use(r=>y(void 0,void 0,void 0,function*(){const{groups:s=[]}=r.req;if(o.includesArray(e,s))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,s,i)},exports.HasPermissions=(...e)=>(r,s,i)=>{t.Use(r=>y(void 0,void 0,void 0,function*(){const{permissions:s}=r.req;if(o.includesArray(e,null!=s?s:[]))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,s,i)},exports.IsAuthenticated=P,exports.Log=Log,exports.Loggable=Loggable,exports.ModelService=ModelService,exports.ReqAuth=O,exports.ReqGroup=T,exports.ReqGroups=I,exports.ReqPermission=w,exports.ReqPermissions=U,exports.ReqUser=b,exports.SessionStore=SessionStore,exports.canFactory=A,exports.sequelize=x;
7
+ "use strict";var e,t=require("@andrewcaires/express"),r=require("@andrewcaires/node"),o=require("@andrewcaires/utils.js"),i=require("ws"),s=require("@andrewcaires/sequelize"),n=require("dotenv"),d=require("express-session"),l=require("@andrewcaires/decorator"),a=require("jsonwebtoken"),u=require("@node-rs/argon2"),p=require("fs"),c=require("path");function g(e,t,r,o){var i,s=arguments.length,n=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function v(e,t){return function(r,o){t(r,o,e)}}function h(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function y(e,t,r,o){return new(r||(r=Promise))(function(i,s){function n(e){try{l(o.next(e))}catch(e){s(e)}}function d(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,d)}l((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,n.config({quiet:!0});class Env extends r.Env{}e=Env,Env.BASE_NAME=e.getString("BASE_NAME",""),Env.CONSOLE_ERROR=e.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=e.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=e.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=e.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=e.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=e.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=e.getString("HTTP_CROSS",""),Env.HTTP_TLS_CA=e.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=e.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=e.getFile("HTTP_TLS_KEY"),Env.MODEL_LIMIT=e.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=e.getInt("MODEL_LIMIT_MAX",100),Env.PASSWORD_ALGORITHM=e.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=e.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=e.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=e.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=e.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=e.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=e.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=e.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=e.getFile("TOKEN_CRT"),Env.TOKEN_KEY=e.getFile("TOKEN_KEY"),Env.TOKEN_TTL=e.getMs("TOKEN_TTL","1d"),Env.TOKEN_TYPE=e.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=e.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=e.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=e.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=e.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=e.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=e.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_HYBRID=e.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=e.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=e.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=e.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=e.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=e.getString("API_KEY_HEADER","x-api-key"),Env.API_SESSION_NAME=e.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=e.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=e.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=e.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=e.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=e.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=e.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_RENEW=e.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=e.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=e.getBool("API_WEBSOCKET_START",!1);const x=new s.Sequelize({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>r.Log.console(r.LogColor.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var m,C,E;exports.AuditTypes=void 0,(m=exports.AuditTypes||(exports.AuditTypes={})).CREATE="CREATE",m.DELETE="DELETE",m.UPDATE="UPDATE",exports.Loglevels=void 0,(C=exports.Loglevels||(exports.Loglevels={})).INFO="info",C.WARN="warn",C.ERROR="error",exports.UserStatus=void 0,(E=exports.UserStatus||(exports.UserStatus={})).ACTIVE="active",E.PENDING="pending",E.DISABLED="disabled",E.LOCKED="locked",E.ARCHIVED="archived";const A=e=>r=>(i,s,n)=>{t.Use(i=>y(void 0,void 0,void 0,function*(){var s;o.isUndefined(r)&&(r=o.isFunction(i.controller.name)?i.controller.name():null===(s=i.controller.constructor)||void 0===s?void 0:s.name);const{permissions:n=[]}=i.req;if(n.includes(`${r}.${e}`))return i.next();i.error(new t.UnauthorizedError("Access Denied"))}))(i,s,n)},S=A("create"),_=A("delete"),f=A("read"),M=A("update"),P=()=>(e,r,o)=>{t.Use(e=>y(void 0,void 0,void 0,function*(){yield(e=>y(void 0,void 0,void 0,function*(){var r,o,i,s;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:n,[Env.API_TOKEN_HEADER]:d,"user-agent":l}=e.getHeaders(),a=e.getQuery(Env.API_KEY_HEADER),u=(null===(r=n||a)||void 0===r?void 0:r.toString())||"";let p=e.getCookie(Env.API_TOKEN_COOKIE);p=`${Env.TOKEN_TYPE} ${p}`;const[c,g]=null!==(i=null===(o=d||p)||void 0===o?void 0:o.split(" "))&&void 0!==i?i:["",""];if(!(u||g&&c.toLowerCase()==Env.TOKEN_TYPE))return e.error(new t.UnauthorizedError("Invalid token"));const{authService:v,userService:h}=e.app,{auth:y,user:x}=null!==(s=yield(u?v.key(u.toString()):v.user(g)).catch(t=>{e.error(t)}))&&void 0!==s?s:{};if(!y||!x)return;if(!u&&y.user_agent&&y.user_agent!=l)return e.error(new t.UnauthorizedError("Invalid token"));e.req.auth=y,e.req.user=x;const{groups:m,permissions:C}=yield h.getGroupsPermissions(x.id);e.req.groups=m,e.req.permissions=C,e.next()}))(e)}))(e,r,o)},O=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),T=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.groups)&&void 0!==o?o:[]).includes(t)}),I=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==r?r:[]}),w=t.parameterFactory(({ctx:e,key:t})=>{var r,o;return(null!==(o=null===(r=e.req)||void 0===r?void 0:r.permissions)&&void 0!==o?o:[]).includes(t)}),U=t.parameterFactory(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==r?r:[]}),b=t.parameterFactory(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),R=(e,r,o)=>{var i,s,n,d,l,a,u,p,c,g,v;const h=o.ctx instanceof t.Context?o.ctx:null,y=null!==(i=null==h?void 0:h.id)&&void 0!==i?i:null,x=null!==(l=null!==(d=null===(n=null===(s=null==h?void 0:h.req)||void 0===s?void 0:s.user)||void 0===n?void 0:n.id)&&void 0!==d?d:o.user_id)&&void 0!==l?l:null,m={type:e,model:null!==(a=null==r?void 0:r.getTableName())&&void 0!==a?a:null,source:null!==(u=Env.BASE_NAME)&&void 0!==u?u:"",request_id:y,user_id:x};return h?Object.assign(Object.assign({},m),{full_url:null!==(p=h.getUrl())&&void 0!==p?p:"",ip_address:null!==(c=h.getIp())&&void 0!==c?c:"",user_agent:null!==(v=null===(g=h.req)||void 0===g?void 0:g.headers["user-agent"])&&void 0!==v?v:""}):m},D=e=>{const t=o.getConstructor(e),r=t.primaryKeyAttribute;return{model:t,record_id:r?e.getDataValue(r):null}},L={afterCreate:(e,t)=>y(void 0,void 0,void 0,function*(){const{model:o,record_id:i}=D(e);yield exports.AuditModel.create(Object.assign(Object.assign({},R(exports.AuditTypes.CREATE,o,t)),{record:i,currently:e.toJSON()})).catch(r.Log.catch)}),afterUpdate:(e,t)=>y(void 0,void 0,void 0,function*(){const{model:o,record_id:i}=D(e),s={},n={},d=e.changed();d&&d.length&&d.forEach(t=>{s[t]=e.getDataValue(t),n[t]=e.previous(t)}),yield exports.AuditModel.create(Object.assign(Object.assign({},R(exports.AuditTypes.UPDATE,o,t)),{record:i,currently:s,previously:n})).catch(r.Log.catch)}),afterDestroy:(e,t)=>y(void 0,void 0,void 0,function*(){const{model:o,record_id:i}=D(e);yield exports.AuditModel.create(Object.assign(Object.assign({},R(exports.AuditTypes.DELETE,o,t)),{record:i,currently:e.toJSON()})).catch(r.Log.catch)})},N=e=>(o.isUndefined(e)&&(e=Env.DATABASE_AUDIT),s.Hooks(e?L:{}));exports.RegisterModel=class RegisterModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.RegisterModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.RegisterModel.prototype,"secret",void 0),g([s.Column.FullDate(),h("design:type",Number)],exports.RegisterModel.prototype,"expired_at",void 0),g([s.Column.Boolean(),h("design:type",Boolean)],exports.RegisterModel.prototype,"active",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.RegisterModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.RegisterModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.RegisterModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.RegisterModel.prototype,"user_id",void 0),exports.RegisterModel=g([s.Database(x),s.ModelName("register"),s.Version("5.2.0")],exports.RegisterModel),exports.UserAuthModel=class UserAuthModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.UserAuthModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.UserAuthModel.prototype,"secret",void 0),g([s.Column.String(),h("design:type",String)],exports.UserAuthModel.prototype,"ip_address",void 0),g([s.Column.String(),h("design:type",String)],exports.UserAuthModel.prototype,"user_agent",void 0),g([s.Column.FullDate(),h("design:type",Object)],exports.UserAuthModel.prototype,"revoked_at",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.UserAuthModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.UserAuthModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.UserAuthModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.UserAuthModel.prototype,"user_id",void 0),exports.UserAuthModel=g([s.Database(x),s.ModelName("users_auth"),s.Version("5.2.0")],exports.UserAuthModel),exports.PermissionModel=class PermissionModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.PermissionModel.prototype,"id",void 0),g([s.Column.String(),s.Index(),h("design:type",String)],exports.PermissionModel.prototype,"name",void 0),g([s.Column.Text(),h("design:type",String)],exports.PermissionModel.prototype,"description",void 0),g([s.Column.Boolean(),h("design:type",Boolean)],exports.PermissionModel.prototype,"active",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.PermissionModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.PermissionModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.PermissionModel.prototype,"deleted_at",void 0),g([s.Association.HasMany(()=>exports.GroupPermissionModel),h("design:type",Array)],exports.PermissionModel.prototype,"groups_permissions",void 0),exports.PermissionModel=g([s.Database(x),s.ModelName("permission"),N(),s.Version("5.2.1")],exports.PermissionModel),exports.GroupPermissionModel=class GroupPermissionModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.GroupPermissionModel.prototype,"id",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.GroupPermissionModel.prototype,"created_at",void 0),g([s.Association.BelongsTo(()=>exports.GroupModel),h("design:type",String)],exports.GroupPermissionModel.prototype,"group_id",void 0),g([s.Association.BelongsTo(()=>exports.PermissionModel),h("design:type",String)],exports.GroupPermissionModel.prototype,"permission_id",void 0),exports.GroupPermissionModel=g([s.Database(x),s.ModelName("groups_permissions"),N(),s.Version("5.2.0")],exports.GroupPermissionModel),exports.GroupModel=class GroupModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.GroupModel.prototype,"id",void 0),g([s.Column.String(),s.Index(),h("design:type",String)],exports.GroupModel.prototype,"name",void 0),g([s.Column.Text(),h("design:type",String)],exports.GroupModel.prototype,"description",void 0),g([s.Column.Boolean(),h("design:type",Boolean)],exports.GroupModel.prototype,"active",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.GroupModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.GroupModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.GroupModel.prototype,"deleted_at",void 0),g([s.Association.HasMany(()=>exports.UserGroupModel),h("design:type",Array)],exports.GroupModel.prototype,"users_groups",void 0),g([s.Association.HasMany(()=>exports.GroupPermissionModel),h("design:type",Array)],exports.GroupModel.prototype,"groups_Permission",void 0),exports.GroupModel=g([s.Database(x),s.ModelName("group"),N(),s.Version("5.2.1")],exports.GroupModel),exports.UserGroupModel=class UserGroupModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.UserGroupModel.prototype,"id",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.UserGroupModel.prototype,"created_at",void 0),g([s.Association.BelongsTo(()=>exports.GroupModel),h("design:type",String)],exports.UserGroupModel.prototype,"group_id",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.UserGroupModel.prototype,"user_id",void 0),exports.UserGroupModel=g([s.Database(x),s.ModelName("users_groups"),N(),s.Version("5.2.0")],exports.UserGroupModel),exports.UserPasswordModel=class UserPasswordModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.UserPasswordModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.UserPasswordModel.prototype,"hash",void 0),g([s.Column.FullDate(),h("design:type",Object)],exports.UserPasswordModel.prototype,"revoked_at",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.UserPasswordModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.UserPasswordModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.UserPasswordModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.UserPasswordModel.prototype,"user_id",void 0),exports.UserPasswordModel=g([s.Database(x),s.ModelName("users_password"),N(),s.Version("5.2.0")],exports.UserPasswordModel),exports.UserModel=class UserModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.UserModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.UserModel.prototype,"name",void 0),g([s.Column.String(),h("design:type",String)],exports.UserModel.prototype,"username",void 0),g([s.Column.String(),h("design:type",String)],exports.UserModel.prototype,"email",void 0),g([s.Column.Text(),h("design:type",String)],exports.UserModel.prototype,"notes",void 0),g([s.Column.Enum(exports.UserStatus),s.DefaultValue(exports.UserStatus.ACTIVE),h("design:type",String)],exports.UserModel.prototype,"status",void 0),g([s.Column.Json(),s.DefaultValue(()=>({})),h("design:type",Object)],exports.UserModel.prototype,"metadata",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.UserModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.UserModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.UserModel.prototype,"deleted_at",void 0),g([s.Association.HasMany(()=>exports.AuditModel),h("design:type",Array)],exports.UserModel.prototype,"audits",void 0),g([s.Association.HasMany(()=>exports.UserAuthModel),h("design:type",Array)],exports.UserModel.prototype,"users_auths",void 0),g([s.Association.HasMany(()=>exports.RegisterModel),h("design:type",Array)],exports.UserModel.prototype,"registers",void 0),g([s.Association.HasMany(()=>exports.UserGroupModel),h("design:type",Array)],exports.UserModel.prototype,"users_groups",void 0),g([s.Association.HasMany(()=>exports.UserPasswordModel),h("design:type",Array)],exports.UserModel.prototype,"users_passwords",void 0),exports.UserModel=g([s.Database(x),s.ModelName("user"),N(),s.Version("5.2.0")],exports.UserModel),exports.AuditModel=class AuditModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.AuditModel.prototype,"id",void 0),g([s.Column.Enum(exports.AuditTypes),h("design:type",String)],exports.AuditModel.prototype,"type",void 0),g([s.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"model",void 0),g([s.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"record",void 0),g([s.Column.Json(),h("design:type",Object)],exports.AuditModel.prototype,"currently",void 0),g([s.Column.Json(),h("design:type",Object)],exports.AuditModel.prototype,"previously",void 0),g([s.Column.String(36),h("design:type",String)],exports.AuditModel.prototype,"request_id",void 0),g([s.Column.Text(),h("design:type",String)],exports.AuditModel.prototype,"full_url",void 0),g([s.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"ip_address",void 0),g([s.Column.Text(),h("design:type",String)],exports.AuditModel.prototype,"user_agent",void 0),g([s.Column.String(),h("design:type",String)],exports.AuditModel.prototype,"source",void 0),g([s.Column.FullDate(),h("design:type",Object)],exports.AuditModel.prototype,"reverted_at",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.AuditModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.AuditModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.AuditModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.AuditModel.prototype,"user_id",void 0),exports.AuditModel=g([s.Database(x),s.ModelName("audit"),s.Version("5.2.0")],exports.AuditModel),exports.ConfigModel=class ConfigModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.ConfigModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.ConfigModel.prototype,"key",void 0),g([s.Column.Text(),h("design:type",String)],exports.ConfigModel.prototype,"value",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.ConfigModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.ConfigModel.prototype,"updated_at",void 0),exports.ConfigModel=g([s.Database(x),s.ModelName("configs"),s.Version("5.2.0")],exports.ConfigModel),exports.ForgotModel=class ForgotModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.ForgotModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.ForgotModel.prototype,"secret",void 0),g([s.Column.FullDate(),h("design:type",Number)],exports.ForgotModel.prototype,"expired_at",void 0),g([s.Column.Boolean(),h("design:type",Boolean)],exports.ForgotModel.prototype,"active",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.ForgotModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.ForgotModel.prototype,"updated_at",void 0),g([s.Column.DeletedAt(),h("design:type",Object)],exports.ForgotModel.prototype,"deleted_at",void 0),g([s.Association.BelongsTo(()=>exports.UserModel),h("design:type",String)],exports.ForgotModel.prototype,"user_id",void 0),exports.ForgotModel=g([s.Database(x),s.ModelName("forgot"),s.Version("5.2.0")],exports.ForgotModel),exports.LogModel=class LogModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.LogModel.prototype,"id",void 0),g([s.Column.Enum(exports.Loglevels),s.DefaultValue(exports.Loglevels.INFO),h("design:type",String)],exports.LogModel.prototype,"level",void 0),g([s.Column.Text(),h("design:type",String)],exports.LogModel.prototype,"message",void 0),g([s.Column.String(),h("design:type",String)],exports.LogModel.prototype,"source",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.LogModel.prototype,"created_at",void 0),exports.LogModel=g([s.Database(x),s.ModelName("log"),s.Version("5.2.0")],exports.LogModel),exports.MigrationModel=class MigrationModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.MigrationModel.prototype,"id",void 0),g([s.Column.String(),h("design:type",String)],exports.MigrationModel.prototype,"model",void 0),g([s.Column.String(),h("design:type",String)],exports.MigrationModel.prototype,"version",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.MigrationModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.MigrationModel.prototype,"updated_at",void 0),exports.MigrationModel=g([s.Database(x),s.ModelName("migration"),s.Version("5.2.0")],exports.MigrationModel),exports.SessionModel=class SessionModel extends s.Model{},g([s.Column.Id(7),h("design:type",String)],exports.SessionModel.prototype,"id",void 0),g([s.Column.Json(),h("design:type",Object)],exports.SessionModel.prototype,"data",void 0),g([s.Column.FullDate(),h("design:type",Date)],exports.SessionModel.prototype,"expired_at",void 0),g([s.Column.CreatedAt(),h("design:type",Date)],exports.SessionModel.prototype,"created_at",void 0),g([s.Column.UpdatedAt(),h("design:type",Date)],exports.SessionModel.prototype,"updated_at",void 0),exports.SessionModel=g([s.Database(x),s.ModelName("session"),s.Version("5.2.0")],exports.SessionModel);class Log{static error(e,t,r){return y(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,r)})}static info(e,t,r){return y(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,r)})}static warn(e,t,r){return y(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,r)})}static writeRaw(e,t,o,i){return y(this,void 0,void 0,function*(){var s;i&&r.Log.console(null!==(s=this.colors[e])&&void 0!==s?s:r.LogColor.White,e,t),x&&(yield exports.LogModel.create({level:e,message:t,source:null!=o?o:""}).catch(r.Log.catch))})}}Log.colors={error:r.LogColor.Red,info:r.LogColor.Cyan,warn:r.LogColor.Yellow};class Loggable{get log(){return e=>Loggable.logInfo(this,e)}static get log(){return e=>this.logInfo(this,e)}get error(){return e=>Loggable.logError(this,e)}static get error(){return e=>this.logError(this,e)}static logError(e,t){var r,o;Log.error(null!==(o=null!==(r=null==t?void 0:t.message)&&void 0!==r?r:t)&&void 0!==o?o:"",this.source(e),Env.CONSOLE_ERROR)}static logInfo(e,t){Log.info(null!=t?t:"",this.source(e),Env.CONSOLE_ERROR)}static source(e){var t,r,o;const i=null!==(o=null!==(r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==r?r:null==e?void 0:e.name)&&void 0!==o?o:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${i}`:i}}class SessionStore extends d.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,function*(){e=e||o.noop;const t=yield exports.SessionModel.findAll({attributes:["id","expired_at"],where:{expired_at:{[s.Op.gte]:new Date}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.id)),e()}),this.clear=e=>y(this,void 0,void 0,function*(){yield exports.SessionModel.destroy().catch(r.Log.catch),e&&e()}),this.destroy=(e,t)=>y(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{id:e}}).catch(r.Log.catch),t&&t()}),this.expired=()=>y(this,void 0,void 0,function*(){yield exports.SessionModel.destroy({where:{expired_at:{[s.Op.lt]:new Date}}}).catch(r.Log.catch)}),this.get=(e,t)=>y(this,void 0,void 0,function*(){t=t||o.noop;const i=yield exports.SessionModel.findOne({where:{id:e,expired_at:{[s.Op.gte]:new Date}}}).catch(e=>(t(e),null));if(i){if(i.data.cookie){if(new Date(i.data.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(r.Log.catch),void t(null)}t(null,i.data)}else t(null)}),this.length=e=>y(this,void 0,void 0,function*(){e&&e(null,(yield exports.SessionModel.count().catch(r.Log.catch))||0)}),this.set=(e,t,i)=>y(this,void 0,void 0,function*(){i=i||o.noop;const s=new Date;s.setTime(s.getTime()+Env.API_SESSION_LIFETIME);const[n,d]=(yield exports.SessionModel.findOrCreate({where:{id:e},defaults:{id:e,data:t,expired_at:s}}).catch(r.Log.catch))||[];n?(d||(n.data=t,n.expired_at=s,yield n.save().catch(r.Log.catch)),i()):i()}),setInterval(this.expired,6e4)}}exports.Service=class Service{},exports.Service=g([l.Trait(Loggable)],exports.Service),exports.AuthService=class AuthService extends exports.Service{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return y(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{id:r}=e,i=o.uuidv7(),s=yield exports.UserAuthModel.create({secret:i,user_id:r}).catch(this.error);if(!s)throw new t.InternalServerError;return{auth:s,token:a.sign({id:r,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return y(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return y(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new t.NotFoundError("TOKEN_KEY not found");const{decode:r}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:i,secret:s}=r;if(i&&s){const e=yield exports.UserModel.findOne({where:{id:i,status:exports.UserStatus.ACTIVE}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=o.uuidv7(),yield t.save().catch(this.error);return{auth:t,token:a.sign({id:i,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t.UnauthorizedError("Invalid token")})}user(e){return y(this,void 0,void 0,function*(){const{decode:r}=yield this.verify(e);if(!r)throw new t.UnauthorizedError("Invalid token");const{id:o,secret:i}=r;if(o&&i){const e=yield exports.UserModel.findOne({attributes:this.userAttributes,where:{id:o,status:exports.UserStatus.ACTIVE}}).catch(this.error);if(e){const t=yield exports.UserAuthModel.findOne({where:{secret:i,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t.UnauthorizedError("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,r){return y(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new t.NotFoundError("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t.UnauthorizedError("Invalid token");try{return{decode:a.verify(e,Env.TOKEN_CRT,{clockTolerance:r})}}catch(e){throw new t.UnauthorizedError("Invalid token")}})}key(e){return y(this,void 0,void 0,function*(){if(!e)throw new t.UnauthorizedError("Invalid token");const r=yield exports.UserModel.findOne({attributes:this.userAttributes,where:{token:e,status:exports.UserStatus.ACTIVE}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[o]=(yield exports.UserAuthModel.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(o)return o.revoked_at&&(o.revoked_at=null,yield o.save().catch(this.error)),{auth:o,user:r}}throw new t.UnauthorizedError("Invalid token")})}},exports.AuthService=g([l.Singleton()],exports.AuthService);class ModelService extends exports.Service{constructor(e,t){var r,o;super(),this.attributes=[],this.permissions=[],this.search=[],this.model=e,(null==t?void 0:t.permissions)&&(this.permissions=t.permissions);const i=Object.keys(e.getAttributes());this.attributes=this.filterAttributes(i,null!==(r=null==t?void 0:t.attributes)&&void 0!==r?r:[]),this.search=this.filterAttributes(i,null!==(o=null==t?void 0:t.search)&&void 0!==o?o:this.attributes)}applySelect(e,t,r){if(!t)return;const i=null==e?void 0:e.getQuery(r?`${r}_select`:"select"),s=t.attributes,n=e=>s.includes(e);t.attributes=[],o.isString(i)&&i.length&&t.attributes.push(...i.split(/\s*,\s*/g).filter(n)),t.attributes.length||(t.attributes=s)}applyOrders(e,t){if(!t)return;const r=null==e?void 0:e.getQuery("asc"),i=null==e?void 0:e.getQuery("desc"),s=[],n=t.attributes,d=e=>n.includes(e);o.isString(r)&&r.length&&s.push(...r.split(/\s*,\s*/g).filter(d).map(e=>[e,"ASC"])),o.isString(i)&&i.length&&s.push(...i.split(/\s*,\s*/g).filter(d).map(e=>[e,"DESC"])),s.length&&(t.order=s)}applyPagination(e,t){if(!t)return;const r=null==e?void 0:e.getQuery("limit"),i=null==e?void 0:e.getQuery("offset");o.isUndefined(t.limit)&&(t.limit=Env.MODEL_LIMIT,o.isString(r)&&(t.limit=parseInt(r)||0),t.limit=o.clamp(t.limit,-1,Env.MODEL_LIMIT_MAX)),t.limit<0&&(t.limit=void 0),o.isString(i)&&(t.offset=parseInt(i)||0,t.offset<0&&(t.offset=void 0))}applySearch(e,t){var r;if(!t)return;const i=null==e?void 0:e.getQuery("search");i&&o.isString(i)&&(t.where=Object.assign(Object.assign({},null!==(r=t.where)&&void 0!==r?r:{}),{[s.Op.or]:this.search.map(e=>({[e]:{[s.Op.substring]:i}}))}))}applyWhere(e,r,i){var n,d;if(!r)return null;const l=null==e?void 0:e.getQuery(i?`${i}_where`:"where");if(!o.isString(l))return null;const a=r.attributes,u=s.Where.parse(a,l);return o.isUndefined(u.error)?(r.where=Object.assign(Object.assign({},null!==(n=r.where)&&void 0!==n?n:{}),null!==(d=u.value)&&void 0!==d?d:{}),null):new t.ValidationError(u.error.join(", "))}countAll(e){return y(this,void 0,void 0,function*(){var r,i;const{ctx:s,options:n={}}=e,d=o.merge({},n);d.attributes=this.getAttributes(null!==(r=null==d?void 0:d.attributes)&&void 0!==r?r:[]),this.applySearch(s,d);const l=this.applyWhere(s,d);if(l)return null==s||s.error(l),0;this.applySelect(s,d);const a=null!==(i=yield this.model.count(Object.assign(Object.assign({},d),{distinct:!!d.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==i?i:0;return null==s||s.prepare(t.StatusCodes.OK,{count:a}),a})}create(e){return y(this,void 0,void 0,function*(){var r,i;const{body:s={},ctx:n,options:d={}}=e,l=o.merge({},d),a=yield this.model.create(Object.assign({},o.merge({},null!==(i=null===(r=null==n?void 0:n.req)||void 0===r?void 0:r.body)&&void 0!==i?i:{},s)),Object.assign(Object.assign({},l),{ctx:n})).catch(this.error);if(!a)return null==n||n.error(new t.InternalServerError),null;const{primaryKeyAttribute:u}=this.model;return null==n||n.prepare(t.StatusCodes.OK,{[u]:a.getDataValue(u)}),a})}delete(e){return y(this,void 0,void 0,function*(){var r,i;const{ctx:n,id:d,options:l={}}=e,{primaryKeyAttribute:a}=this.model,u=null!==(r=null==n?void 0:n.getParam(a))&&void 0!==r?r:d;if(o.isUndefined(u))return null==n||n.error(new t.BadRequestError),0;const p=o.merge({},l),c=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},p),{where:{[s.Op.and]:Object.assign({[a]:u},null!==(i=null==p?void 0:p.where)&&void 0!==i?i:{})},individualHooks:!0}),{ctx:n})).catch(this.error);return c?(null==n||n.success("OK"),c):(null==n||n.error(new t.NotFoundError),0)})}filterAttributes(e,t){if(o.isArray(t))return t.length?t.filter(t=>o.isString(t)&&e.includes(t)):e;const{exclude:r,include:i}=t,s=o.isUndefined(i)?e:i.filter(t=>o.isString(t)&&e.includes(t)),n=null!=r?r:[];return n.length?s.filter(e=>!n.includes(e)):s}findAll(e){return y(this,void 0,void 0,function*(){var r,i;const{ctx:s,callback:n,options:d={},query:l=!0}=e,a=o.merge({},d);if(a.attributes=this.getAttributes(null!==(r=null==a?void 0:a.attributes)&&void 0!==r?r:[]),l&&this.applySelect(s,a),this.applyOrders(s,a),this.applyPagination(s,a),(null!==(i=null==a?void 0:a.limit)&&void 0!==i?i:0)>Env.MODEL_LIMIT_MAX&&(a.limit=Env.MODEL_LIMIT_MAX),this.applySearch(s,a),l){const e=this.applyWhere(s,a);if(e)return null==s||s.error(e),{count:0,records:[]}}const[u,p]=yield Promise.all([this.model.count(Object.assign(Object.assign({},a),{distinct:!!a.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error).then(e=>null!=e?e:0),this.model.findAll(a).catch(this.error).then(e=>null!=e?e:[])]),c={count:u,records:n?yield n(p):p};return null==s||s.prepare(t.StatusCodes.OK,c),c})}findOne(e){return y(this,void 0,void 0,function*(){var r,i,n;const{callback:d,ctx:l,id:a,options:u={},query:p=!0}=e,{primaryKeyAttribute:c}=this.model,g=null!==(r=null==l?void 0:l.getParam(c))&&void 0!==r?r:a;if(o.isUndefined(g))return null==l||l.error(new t.BadRequestError),null;const v=o.merge({},u);v.attributes=this.getAttributes(null!==(i=null==v?void 0:v.attributes)&&void 0!==i?i:[]),p&&this.applySelect(l,v);const h=yield this.model.findOne(Object.assign(Object.assign({},v),{where:{[s.Op.and]:Object.assign({[c]:g},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{})}})).catch(this.error);return h?(null==l||l.prepare(t.StatusCodes.OK,d?yield d(h):h.toJSON()),h):(null==l||l.error(new t.NotFoundError),null)})}getAttributes(e){return this.filterAttributes(this.attributes,e)}include(e,t){var r;const i=o.clone(t),{ctx:s}=null!=t?t:{};i.attributes=this.filterAttributes(Object.keys(e.getAttributes()),null!==(r=i.attributes)&&void 0!==r?r:[]),this.applySearch(s,i);const n=this.applyWhere(s,i,t.name);return n?(null==s||s.error(n),null):(this.applySelect(s,i,t.name),Object.assign({model:e},i))}name(){return this.model.tableName}sync(){return y(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",active:!0};yield o.forEachAsync(this.permissions,r=>y(this,void 0,void 0,function*(){const i=`${e}.${r}`,s=o.upperCamelCase(e.replace(/_/g," ")," ");yield exports.PermissionModel.findOrCreate({where:{key:i},defaults:Object.assign({name:`${s} ${o.upperCamelCase(r," ")}`,key:i,tags:s},t)})}))})}update(e){return y(this,void 0,void 0,function*(){var r,i,n,d,l;const{ctx:a,body:u,id:p,options:c={}}=e,{primaryKeyAttribute:g}=this.model,v=null!==(r=null==a?void 0:a.getParam(g))&&void 0!==r?r:p;if(o.isUndefined(v))return null==a||a.error(new t.BadRequestError),!1;const h=o.merge({},c),[y]=null!==(l=yield this.model.update(Object.assign({},o.merge({},null!==(n=null===(i=null==a?void 0:a.req)||void 0===i?void 0:i.body)&&void 0!==n?n:{},null!=u?u:{})),Object.assign(Object.assign(Object.assign({},h),{where:{[s.Op.and]:Object.assign({[g]:v},null!==(d=null==h?void 0:h.where)&&void 0!==d?d:{})},individualHooks:!0}),{ctx:a})).catch(this.error))&&void 0!==l?l:[];return y?(null==a||a.success("OK"),!0):(null==a||a.success("Record not changed"),!1)})}}exports.UserService=class UserService extends exports.Service{constructor(){super(...arguments),this.hashOptions={algorithm:Env.PASSWORD_ALGORITHM,memoryCost:Env.PASSWORD_MEMORY_COST,parallelism:Env.PASSWORD_PARALLELISM,timeCost:Env.PASSWORD_TIME_COST}}createPassword(e,t,r){return y(this,void 0,void 0,function*(){yield exports.UserPasswordModel.update({revoked_at:new Date},{where:{revoked_at:null,user_id:e}}).catch(this.error);const o=u.hashSync(t+Env.PASSWORD_PEPPER,this.hashOptions);yield exports.UserPasswordModel.create({hash:o,user_id:e},Object.assign({},{ctx:r})).catch(this.error)})}findAllPermission(e){return y(this,void 0,void 0,function*(){var t;return null!==(t=yield exports.PermissionModel.findAll({attributes:["name"],where:{active:!0},include:[{association:"groups_permissions",required:!0,include:[{association:"group",required:!0,attributes:["id","name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]})}getGroups(e){return y(this,void 0,void 0,function*(){var t;return(null!==(t=yield exports.GroupModel.findAll({attributes:["name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.name)})}getGroupsPermissions(e){return y(this,void 0,void 0,function*(){const t=[],r=[];return(yield this.findAllPermission(e)).forEach(e=>{r.push(e.name),e.groups_permissions.forEach(e=>t.push(e.group.name))}),{groups:o.uniqueArray(t),permissions:o.uniqueArray(r)}})}getPermissions(e){return y(this,void 0,void 0,function*(){return(yield this.findAllPermission(e)).map(e=>e.name)})}},exports.UserService=g([l.Singleton()],exports.UserService);class Application extends t.Application{constructor(e,t){super(e,o.merge({},{cross:!!Env.HTTP_CROSS&&("*"===Env.HTTP_CROSS||{origin:Env.HTTP_CROSS.split(",")}),hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new SessionStore,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:o.uuidv7},tls:{ca:Env.HTTP_TLS_CA,cert:Env.HTTP_TLS_CRT,key:Env.HTTP_TLS_KEY}},null!=t?t:{})),this.hash=new r.Hash(Env.API_KEY_HASH)}error(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.error(e.message,t,Env.CONSOLE_ERROR)}log(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,function*(){yield x.sync(),yield this.migrations(x),yield o.forEachSeries(this.controllers,e=>y(this,void 0,void 0,function*(){o.isFunction(e.sync)&&(yield e.sync(this))})),this.authService=new exports.AuthService,this.userService=new exports.UserService,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new i.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>y(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield o.sleep(2e3)})))})}migrations(e){return y(this,void 0,void 0,function*(){const t=[];yield o.forEachSeries(Object.keys(e.models),r=>y(this,void 0,void 0,function*(){var o;const i=e.models[r],s=i.version();if(!s)return;const[n,d]=null!==(o=yield exports.MigrationModel.findOrCreate({where:{model:i.tableName},defaults:{model:i.tableName,version:""}}).catch(this.error))&&void 0!==o?o:[];n&&(d||n.version!=s)&&(n.version=s,yield n.save().catch(this.error),t.push(i))})),yield o.forEachSeries(t,e=>y(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}exports.BaseController=class BaseController extends o.EventEmitter{constructor(){super(...arguments),this.permissions=[]}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}session(e,t,r){return y(this,void 0,void 0,function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(o.noop):(r.user_agent=t,r.save(o.noop))),e.next()})}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," ");yield o.forEachSeries(this.permissions,r=>y(this,void 0,void 0,function*(){const i=`${e}.${r}`;yield exports.PermissionModel.findOrCreate({where:{name:i},defaults:{name:i,description:`${t} ${o.upperCamelCase(r," ")}`,active:!0}})}))})}},g([v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Session()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Object]),h("design:returntype",Promise)],exports.BaseController.prototype,"session",null),exports.BaseController=g([l.Trait(Loggable)],exports.BaseController),exports.ModelController=class ModelController extends exports.BaseController{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return y(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return y(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return y(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return y(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return y(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," ");yield o.forEachSeries(this.permissions,r=>y(this,void 0,void 0,function*(){const i=`${e}.${r}`;yield exports.PermissionModel.findOrCreate({where:{name:i},defaults:{name:i,description:`${t} ${o.upperCamelCase(r," ")}`,active:!0}})})),this.service=new ModelService(this.model,{attributes:this.attributes.length?this.attributes:void 0,search:this.search.length?this.search:void 0})})}update(e){return y(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}},exports.ModelController=g([t.Extends(exports.BaseController)],exports.ModelController),exports.AuditsController=class AuditsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.AuditModel,this.permissions=["read"]}all(e,t,r){return y(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["currently","previously"]},where:o,order:[["created_at","DESC"]]}})})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},g([t.Get(),P(),f(),v(0,t.Ctx()),v(1,t.Query("type")),v(2,t.Query("table")),h("design:type",Function),h("design:paramtypes",[t.Context,String,String]),h("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),g([t.Get("/:id"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=g([t.Controller("/audits"),t.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class AuthController extends exports.BaseController{constructor(){super(...arguments),this.authService=new exports.AuthService}login(e,r,i,n,d,l){return y(this,void 0,void 0,function*(){var a;yield o.sleep(Env.SLEEP_AUTH);const p=yield exports.UserModel.findOne({where:{[s.Op.or]:[{email:i},{username:i}]}}).catch(this.error);if(!p)return e.error(new t.UnauthorizedError("Invalid credentials")),l.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const c=yield exports.UserPasswordModel.findOne({where:{revoked_at:null,user_id:p.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!c||!(yield u.verify(c.hash,n).catch(o.noop)))return e.error(new t.UnauthorizedError("Invalid credentials")),l.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const g=yield exports.RegisterModel.findOne({where:{active:!0,user_id:p.id}}).catch(this.error);if(g)return e.error(new t.UnauthorizedError("Activation Required")),l.emit("auth.activation",{ctx:e,register:g,user:p}),void this.emit("auth.activation",{ctx:e,register:g,user:p});if(p.status!=exports.UserStatus.ACTIVE)return e.error(new t.UnauthorizedError("Invalid credentials")),l.emit("auth.failure",{ctx:e,user:p}),void this.emit("auth.failure",{ctx:e,user:p});const{auth:v,token:h}=null!==(a=yield this.authService.create(p).catch(t=>{e.error(t),l.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==a?a:{};v&&h&&(v.user_agent=r,v.ip_address=e.getIp(),yield v.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.setCookie(Env.API_TOKEN_COOKIE,h,{maxAge:d?Env.TOKEN_TTL:void 0}),e.json({token:h}),l.emit("auth.login",{ctx:e,auth:v,user:p}),this.emit("auth.login",{ctx:e,auth:v,user:p}))})}logout(e,r,o,i){return y(this,void 0,void 0,function*(){if(yield this.authService.destroy(r))return Env.API_TOKEN_COOKIE_SET&&e.clearCookie(Env.API_TOKEN_COOKIE),e.success("OK"),i.emit("auth.logout",{auth:r,ctx:e,user:o}),void this.emit("auth.logout",{auth:r,ctx:e,user:o});e.error(new t.UnauthorizedError("Access Denied"))})}renew(e,t,r,o){return y(this,void 0,void 0,function*(){var i;const{auth:s,token:n}=null!==(i=yield this.authService.renew(r).catch(t=>{e.error(t)}))&&void 0!==i?i:{};s&&n&&(s.user_agent=t,yield s.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:s,ctx:e}),this.emit("auth.renew",{auth:s,ctx:e}))})}user(e,r){return y(this,void 0,void 0,function*(){const{groups:o,permissions:i,profile:s}=e.req;if(!o||!i)return e.error(new t.InternalServerError);e.json(Object.assign(Object.assign({},r.toJSON()),{groups:o,permissions:i,profile:s}))})}},g([t.Post("/login"),t.Validate(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("username")),v(3,t.Body("password")),v(4,t.Body("remember")),v(5,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,String,String,Boolean,Application]),h("design:returntype",Promise)],exports.AuthController.prototype,"login",null),g([t.Get("/logout"),P(),v(0,t.Ctx()),v(1,O()),v(2,b()),v(3,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,exports.UserAuthModel,exports.UserModel,Application]),h("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),g([t.Post("/renew"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Headers("user-agent")),v(2,t.Body("token")),v(3,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,String,Application]),h("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),g([t.Get(),t.Get("/me"),P(),v(0,t.Ctx()),v(1,b()),h("design:type",Function),h("design:paramtypes",[t.Context,exports.UserModel]),h("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=g([t.Controller("/auth"),t.Extends(exports.BaseController)],exports.AuthController),exports.CrudController=class CrudController extends exports.ModelController{constructor(){super(...arguments),this._crud={}}CrudArgumentsCountAll(e){return{ctx:e}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidateCreate(){return this._crud}CrudValidateUpdate(){return this._crud}add(e){return y(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return y(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return y(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return y(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return y(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,r){return y(this,void 0,void 0,function*(){var i,s;const n=o.Validation.object(r).parse(),{error:d,message:l,value:a}=yield n.validateAsync(null!==(s=null===(i=e.req)||void 0===i?void 0:i.body)&&void 0!==s?s:{});if(d)return e.error(new t.ValidationError(null!=l?l:d));e.req.body=a,e.next()})}validateCreate(e){return y(this,void 0,void 0,function*(){const r=this.CrudValidateCreate();if(r==this._crud)return e.error(new t.InternalServerError);yield this.validate(e,r)})}validateUpdate(e){return y(this,void 0,void 0,function*(){const r=this.CrudValidateUpdate();if(r==this._crud)return e.error(new t.InternalServerError);yield this.validate(e,r)})}},g([t.Post(),P(),S(),t.Middleware("validateCreate"),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"add",null),g([t.Get(),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"all",null),g([t.Get("/count"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"rows",null),g([t.Delete("/:id"),P(),_(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"del",null),g([t.Get("/:id"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"get",null),g([t.Put("/:id"),P(),M(),t.Middleware("validateUpdate"),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"set",null),g([v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"validateCreate",null),g([v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.CrudController.prototype,"validateUpdate",null),exports.CrudController=g([t.Extends(exports.ModelController)],exports.CrudController),exports.FilesController=class FilesController extends exports.BaseController{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return y(this,void 0,void 0,function*(){let{path:r}=e.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=c.join(this.directory,r);if(!p.existsSync(i)||!p.statSync(i).isDirectory())return e.error(new t.NotFoundError);let s;return s=p.readdirSync(i),s=s.map(e=>this.info(c.join(i,e))),s=s.filter(o.isDef),Object.assign(Object.assign({},this.info(i)),{files:s})})}info(e){if(!p.existsSync(e))return null;const t=p.statSync(e),r=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return y(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=o.upperCamelCase(e.replace(/_/g," ")," ");yield o.forEachSeries(this.permissions,r=>y(this,void 0,void 0,function*(){const i=`${e}.${r}`;yield exports.PermissionModel.findOrCreate({where:{name:i},defaults:{name:i,description:`${t} ${o.upperCamelCase(r," ")}`,active:!0}})}))})}},g([t.Get("/path"),t.Get("/path/*path"),P(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.FilesController.prototype,"files",null),exports.FilesController=g([t.Controller("/files"),t.Extends(exports.BaseController)],exports.FilesController),exports.ForgotController=class ForgotController extends exports.BaseController{check(e,r){return y(this,void 0,void 0,function*(){const i=yield this.find(r);if(!i||!i.user)return e.error(new t.NotFoundError);i.secret=o.uniqueID(),yield i.save(),e.json({token:i.secret})})}forgot(e,r,i){return y(this,void 0,void 0,function*(){yield o.sleep(Env.SLEEP_FORGOT);const n=r,d=yield exports.UserModel.findOne({where:{[s.Op.or]:[{email:n},{username:r}]}}).catch(this.error);if(!d)return e.error(new t.NotFoundError);const l=o.uniqueID(),a=Date.now()+6e4*Env.API_TOKEN_FORGOT,u=yield exports.ForgotModel.create({token:l,timestamp:a,active:!0,user_id:d.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:u,user:d}),this.emit("forgot.send",{ctx:e,forgot:u,user:d})})}reset(e,r,o,i){return y(this,void 0,void 0,function*(){const o=yield this.find(r);if(!o)return e.error(new t.NotFoundError);o.active=!1,yield o.save().catch(this.error),yield o.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:o.user}),this.emit("forgot.reset",{ctx:e,user:o.user})})}find(e){return y(this,void 0,void 0,function*(){return yield exports.ForgotModel.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}},g([t.Get("/check"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),h("design:type",Function),h("design:paramtypes",[t.Context,String]),h("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),g([t.Post(),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Application]),h("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),g([t.Post("/reset"),t.Validate(e=>({token:e.string().required(),password:e.string().min(5).required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.Body("password")),v(3,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,String,Application]),h("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=g([t.Controller("/forgot"),t.Extends(exports.BaseController)],exports.ForgotController),exports.GroupsController=class GroupsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.GroupModel,this.schemaCreate={name:o.Validation.string().required(),description:o.Validation.string().empty(""),active:o.Validation.boolean().parse().required()},this.schemaUpdate={description:o.Validation.string().empty(),active:o.Validation.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}},exports.GroupsController=g([t.Controller("/groups"),t.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class GroupsPermissionsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.GroupPermissionModel,this.permissions=[]}all(e,t){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{association:"permission"}]},callback:e=>e.map(e=>e.permission),query:!1})})}set(e,r,i){return y(this,void 0,void 0,function*(){const n=yield exports.GroupModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);const d=n.id,l=[];yield o.forEachSeries(o.uniqueArray(i),t=>y(this,void 0,void 0,function*(){var r;if(!(yield exports.PermissionModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.GroupPermissionModel.findOrCreate(Object.assign({where:{group_id:d,permission_id:t},defaults:{group_id:d,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.GroupPermissionModel.destroy(Object.assign({where:{group_id:d,permission_id:{[s.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/permissions"),P(),f("groups"),v(0,t.Ctx()),v(1,t.Params("id")),h("design:type",Function),h("design:paramtypes",[t.Context,String]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),g([t.Put("/:id/permissions"),P(),M("groups"),t.Validate(e=>({permissions:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("permissions")),h("design:type",Function),h("design:paramtypes",[t.Context,String,Array]),h("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=g([t.Controller("/groups"),t.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.HealthController=class HealthController{ping(e){return y(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}},g([t.All("/"),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.HealthController.prototype,"ping",null),exports.HealthController=g([t.Controller("/health")],exports.HealthController),exports.LogsController=class LogsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.LogModel,this.permissions=["read"]}all(e){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]}})})}},g([t.Get(),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=g([t.Controller("/logs"),t.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class PermissionsController extends exports.CrudController{constructor(){super(...arguments),this.model=exports.PermissionModel,this.schemaCreate={name:o.Validation.string().required(),description:o.Validation.string().empty(""),active:o.Validation.boolean().parse().required()},this.schemaUpdate={description:o.Validation.string().empty(),active:o.Validation.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}},exports.PermissionsController=g([t.Controller("/permissions"),t.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class RegisterController extends exports.BaseController{register(e,i,n){return y(this,void 0,void 0,function*(){yield o.sleep(Env.SLEEP_REGISTRY);const{name:d,date:l,email:a,username:u,password:p,confirm:c}=i,g=u||a,v=r.sha256(p);if(yield exports.UserModel.count({where:{[s.Op.or]:[{email:a},{username:g}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(v!=r.sha256(c))return e.error("INVALID PASSWORD");const h=yield exports.UserModel.create({name:d,email:a,username:g,password:v,avatar:"",date:l,description:"",status:exports.UserStatus.PENDING}).catch(this.error);if(!h)return e.error(new t.InternalServerError);const y=yield exports.RegisterModel.create({token:yield this.getId(),active:!0,user_id:h.id}).catch(this.error);if(!y)return yield h.destroy().catch(this.error),e.error(new t.InternalServerError);e.success("OK"),n.emit("register.user",{ctx:e,register:y,user:h}),this.emit("register.user",{ctx:e,register:y,user:h})})}confirm(e,r,o){return y(this,void 0,void 0,function*(){const i=yield exports.RegisterModel.findOne({where:{token:r,active:!0},include:[{association:"users",required:!0}]}).catch(this.error);if(!i)return e.error(new t.NotFoundError);i.active=!1,yield i.save().catch(this.error),i.user.status=exports.UserStatus.ACTIVE,yield i.user.save().catch(this.error),e.success("OK"),o.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})})}send(e,r,o){return y(this,void 0,void 0,function*(){const i=r,n=yield exports.RegisterModel.findOne({where:{active:!0},include:[{model:exports.UserModel,required:!0,where:{[s.Op.or]:[{email:i},{username:r}]}}]}).catch(this.error);if(!n)return e.error(new t.NotFoundError);e.success("OK"),o.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return y(this,void 0,void 0,function*(){const e=o.uuidv7();return(yield exports.RegisterModel.count({where:{token:e}}))?this.getId():e})}},g([t.Post(),t.Validate(e=>({name:e.string().required(),date:e.date().required(),email:e.string().email().required(),username:e.string().min(4).empty(),password:e.string().min(5).required(),confirm:e.string().min(5).required()})),v(0,t.Ctx()),v(1,t.Body()),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,Object,Application]),h("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),g([t.Post("/confirm"),t.Validate(e=>({token:e.string().required()})),v(0,t.Ctx()),v(1,t.Body("token")),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Application]),h("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),g([t.Post("/send"),t.Validate(e=>({username:e.string().min(4).required()})),v(0,t.Ctx()),v(1,t.Body("username")),v(2,t.App()),h("design:type",Function),h("design:paramtypes",[t.Context,String,Application]),h("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=g([t.Controller("/register"),t.Extends(exports.BaseController)],exports.RegisterController),exports.SetupController=class SetupController extends exports.BaseController{constructor(){super(...arguments),this.userService=new exports.UserService}setup(e){return y(this,void 0,void 0,function*(){var r;if(yield exports.UserModel.count())return e.error(new t.NotFoundError("Endpoint Not Found"));const i=yield exports.UserModel.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:exports.UserStatus.ACTIVE},Object.assign({},{ctx:e})).catch(this.error);if(!i)return e.error(new t.InternalServerError);yield this.userService.createPassword(i.id,"admin",e);const s=yield exports.GroupModel.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield exports.UserGroupModel.create({user_id:i.id,group_id:s.id},Object.assign({},{ctx:e})),yield exports.GroupModel.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield exports.GroupModel.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const n=null!==(r=yield exports.PermissionModel.findAll({where:{active:!0}}).catch(this.error))&&void 0!==r?r:[];yield o.forEachSeries(n,t=>y(this,void 0,void 0,function*(){yield exports.GroupPermissionModel.create({group_id:s.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}},g([t.Get(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=g([t.Controller("/setup"),t.Extends(exports.BaseController)],exports.SetupController),exports.UsersController=class UsersController extends exports.ModelController{constructor(){super(),this.model=exports.UserModel,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&p.existsSync(Env.API_HTTP_PUBLIC)&&!p.existsSync(this.path)&&p.mkdirSync(this.path)}avatar(e,r){return y(this,void 0,void 0,function*(){var o;const i=e.getFiles();if(i.file&&i.file.length){const{filename:s,path:n}=null!==(o=i.file[0])&&void 0!==o?o:{};if(s){const o=yield exports.UserModel.findOne({where:{user_id:r.id}}).catch(this.error);if(!o)return p.lstatSync(n).isFile()&&p.rmSync(n),e.error(new t.InternalServerError);const i=this.path+"/"+o.metadata.avatar_url;if(p.existsSync(i)&&p.lstatSync(i).isFile()&&p.rmSync(i),o.changed("metadata",!0),o.metadata.avatar_url=s,yield o.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return y(this,void 0,void 0,function*(){var e;const t=o.uuidv7();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return y(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return y(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return y(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,r,o){return y(this,void 0,void 0,function*(){if(o.id==r)return e.error(new t.NotFoundError);yield this.delete({ctx:e})})}get(e){return y(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return y(this,void 0,void 0,function*(){yield this.update({ctx:e})})}},g([t.Post("/avatar"),P(),t.Upload({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),v(0,t.Ctx()),v(1,b()),h("design:type",Function),h("design:paramtypes",[t.Context,exports.UserModel]),h("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),g([t.Post(),P(),S(),t.Validate(e=>({name:e.string().required(),email:e.string().email().required(),username:e.string().min(3).required(),description:e.string().empty(""),state:e.boolean().parse().empty(!0)})),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"add",null),g([t.Get(),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"all",null),g([t.Get("/count"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"rows",null),g([t.Delete("/:id"),P(),_(),v(0,t.Ctx()),v(1,t.Params("id")),v(2,b()),h("design:type",Function),h("design:paramtypes",[t.Context,String,exports.UserModel]),h("design:returntype",Promise)],exports.UsersController.prototype,"del",null),g([t.Get("/:id"),P(),f(),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"get",null),g([t.Put("/:id"),P(),M(),t.Validate(e=>({name:e.string().empty(),email:e.string().email().empty(),username:e.string().min(3).empty(),description:e.string().empty(),state:e.boolean().parse().empty()})),v(0,t.Ctx()),h("design:type",Function),h("design:paramtypes",[t.Context]),h("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=g([t.Controller("/users"),t.Extends(exports.ModelController),h("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class UsersGroupsController extends exports.ModelController{constructor(){super(...arguments),this.model=exports.UserGroupModel,this.permissions=[]}all(e,r){return y(this,void 0,void 0,function*(){if(!(yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error)))return e.error(new t.NotFoundError("User Not Found"));yield this.findAll({ctx:e,options:{where:{user_id:r},include:[{association:"group"}]},callback:e=>e.map(e=>e.group),query:!1})})}set(e,r,i){return y(this,void 0,void 0,function*(){const n=yield exports.UserModel.findByPk(r,{attributes:["id"]}).catch(this.error);if(!n)return e.error(new t.NotFoundError("User Not Found"));const d=n.id,l=[];yield o.forEachSeries(o.uniqueArray(i),t=>y(this,void 0,void 0,function*(){var r;if(!(yield exports.GroupModel.count({where:{id:t}})))return;const[o]=null!==(r=yield exports.UserGroupModel.findOrCreate(Object.assign({where:{user_id:d,group_id:t},defaults:{user_id:d,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==r?r:[];o&&l.push(t)})),yield exports.UserGroupModel.destroy(Object.assign({where:{user_id:d,group_id:{[s.Op.notIn]:l}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}},g([t.Get("/:id/groups"),P(),f("users"),v(0,t.Ctx()),v(1,t.Params("id")),h("design:type",Function),h("design:paramtypes",[t.Context,String]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),g([t.Put("/:id/groups"),P(),M("users"),t.Validate(e=>({groups:e.array(e.string())})),v(0,t.Ctx()),v(1,t.Params("id")),v(2,t.Body("groups")),h("design:type",Function),h("design:paramtypes",[t.Context,String,Array]),h("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=g([t.Controller("/users"),t.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=Application,exports.Audit=N,exports.CanCreate=S,exports.CanDelete=_,exports.CanRead=f,exports.CanUpdate=M,exports.Config=class Config extends Loggable{static all(e){return y(this,void 0,void 0,function*(){var t;const r=null!==(t=yield exports.ConfigModel.findAll({where:(null==e?void 0:e.length)?{key:{[s.Op.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(r.map(e=>[e.key,e.value]))})}static del(e){return y(this,void 0,void 0,function*(){return((yield exports.ConfigModel.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return y(this,arguments,void 0,function*(e,t=""){const[r]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t){return y(this,void 0,void 0,function*(){const[r,o]=(yield exports.ConfigModel.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];r&&!o&&(r.value=t,yield r.save().catch(this.error))})}},exports.Env=Env,exports.HasGroups=(...e)=>(r,i,s)=>{t.Use(r=>y(void 0,void 0,void 0,function*(){const{groups:i=[]}=r.req;if(o.includesArray(e,i))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,i,s)},exports.HasPermissions=(...e)=>(r,i,s)=>{t.Use(r=>y(void 0,void 0,void 0,function*(){const{permissions:i}=r.req;if(o.includesArray(e,null!=i?i:[]))return r.next();r.error(new t.UnauthorizedError("Access Denied"))}))(r,i,s)},exports.IsAuthenticated=P,exports.Log=Log,exports.Loggable=Loggable,exports.ModelService=ModelService,exports.ReqAuth=O,exports.ReqGroup=T,exports.ReqGroups=I,exports.ReqPermission=w,exports.ReqPermissions=U,exports.ReqUser=b,exports.SessionStore=SessionStore,exports.canFactory=A,exports.sequelize=x;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @andrewcaires/api v5.2.1
2
+ * @andrewcaires/api v5.2.2
3
3
  * Simple api for small applications using express, jsonwebtoken, sequelize and websocket
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/api v5.2.1
2
+ * @andrewcaires/api v5.2.2
3
3
  * Simple api for small applications using express, jsonwebtoken, sequelize and websocket
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import{Use as e,UnauthorizedError as t,parameterFactory as i,Context as r,NotFoundError as n,InternalServerError as s,ValidationError as o,StatusCodes as d,BadRequestError as a,Application as l,Ctx as u,Headers as c,Session as p,Extends as v,Get as g,Query as y,Controller as h,Post as m,Validate as E,Body as _,App as f,Middleware as A,Delete as S,Put as O,Params as T,All as P,Upload as I}from"@andrewcaires/express";import{Env as w,Log as b,LogColor as C,Hash as R,sha256 as D}from"@andrewcaires/node";import{isUndefined as x,isFunction as L,includesArray as N,getConstructor as M,noop as k,uuidv7 as K,isString as j,clamp as B,merge as F,isArray as H,clone as U,forEachAsync as q,upperCamelCase as Y,uniqueArray as $,forEachSeries as W,sleep as G,EventEmitter as V,Validation as z,isDef as J,uniqueID as Q}from"@andrewcaires/utils.js";import{WebSocketServer as X}from"ws";import{Sequelize as Z,Hooks as ee,Column as te,Association as ie,Database as re,ModelName as ne,Version as se,Model as oe,Index as de,DefaultValue as ae,Op as le,Where as ue}from"@andrewcaires/sequelize";import{config as ce}from"dotenv";import{Store as pe}from"express-session";import{Trait as ve,Singleton as ge}from"@andrewcaires/decorator";import ye from"jsonwebtoken";import{hashSync as he,verify as me}from"@node-rs/argon2";import{existsSync as Ee,statSync as _e,readdirSync as fe,mkdirSync as Ae,lstatSync as Se,rmSync as Oe}from"fs";import{join as Te}from"path";function Pe(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function Ie(e,t){return function(i,r){t(i,r,e)}}function we(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function be(e,t,i,r){return new(i||(i=Promise))(function(n,s){function o(e){try{a(r.next(e))}catch(e){s(e)}}function d(e){try{a(r.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,d)}a((r=r.apply(e,t||[])).next())})}var Ce;"function"==typeof SuppressedError&&SuppressedError,ce({quiet:!0});class Env extends w{}Ce=Env,Env.BASE_NAME=Ce.getString("BASE_NAME",""),Env.CONSOLE_ERROR=Ce.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=Ce.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=Ce.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=Ce.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=Ce.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=Ce.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=Ce.getString("HTTP_CROSS",""),Env.HTTP_TLS_CA=Ce.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=Ce.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=Ce.getFile("HTTP_TLS_KEY"),Env.MODEL_LIMIT=Ce.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=Ce.getInt("MODEL_LIMIT_MAX",100),Env.PASSWORD_ALGORITHM=Ce.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=Ce.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=Ce.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=Ce.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=Ce.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=Ce.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=Ce.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=Ce.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=Ce.getFile("TOKEN_CRT"),Env.TOKEN_KEY=Ce.getFile("TOKEN_KEY"),Env.TOKEN_TTL=Ce.getMs("TOKEN_TTL","1d"),Env.TOKEN_TYPE=Ce.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=Ce.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Ce.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Ce.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Ce.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=Ce.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=Ce.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_HYBRID=Ce.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Ce.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Ce.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Ce.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Ce.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=Ce.getString("API_KEY_HEADER","x-api-key"),Env.API_SESSION_NAME=Ce.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Ce.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Ce.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=Ce.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=Ce.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=Ce.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=Ce.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_RENEW=Ce.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=Ce.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Ce.getBool("API_WEBSOCKET_START",!1);const Re=new Z({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>b.console(C.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var De,xe,Le;!function(e){e.CREATE="CREATE",e.DELETE="DELETE",e.UPDATE="UPDATE"}(De||(De={})),function(e){e.INFO="info",e.WARN="warn",e.ERROR="error"}(xe||(xe={})),function(e){e.ACTIVE="active",e.PENDING="pending",e.DISABLED="disabled",e.LOCKED="locked",e.ARCHIVED="archived"}(Le||(Le={}));const Ne=i=>r=>(n,s,o)=>{e(e=>be(void 0,void 0,void 0,function*(){var n;x(r)&&(r=L(e.controller.name)?e.controller.name():null===(n=e.controller.constructor)||void 0===n?void 0:n.name);const{permissions:s=[]}=e.req;if(s.includes(`${r}.${i}`))return e.next();e.error(new t("Access Denied"))}))(n,s,o)},Me=Ne("create"),ke=Ne("delete"),Ke=Ne("read"),je=Ne("update"),Be=(...i)=>(r,n,s)=>{e(e=>be(void 0,void 0,void 0,function*(){const{groups:r=[]}=e.req;if(N(i,r))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},Fe=(...i)=>(r,n,s)=>{e(e=>be(void 0,void 0,void 0,function*(){const{permissions:r}=e.req;if(N(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},He=()=>(i,r,n)=>{e(e=>be(void 0,void 0,void 0,function*(){yield(e=>be(void 0,void 0,void 0,function*(){var i,r,n,s;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:o,[Env.API_TOKEN_HEADER]:d,"user-agent":a}=e.getHeaders(),l=e.getQuery(Env.API_KEY_HEADER),u=(null===(i=o||l)||void 0===i?void 0:i.toString())||"";let c=e.getCookie(Env.API_TOKEN_COOKIE);c=`${Env.TOKEN_TYPE} ${c}`;const[p,v]=null!==(n=null===(r=d||c)||void 0===r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(u||v&&p.toLowerCase()==Env.TOKEN_TYPE))return e.error(new t("Invalid token"));const{authService:g,userService:y}=e.app,{auth:h,user:m}=null!==(s=yield(u?g.key(u.toString()):g.user(v)).catch(t=>{e.error(t)}))&&void 0!==s?s:{};if(!h||!m)return;if(!u&&h.user_agent&&h.user_agent!=a)return e.error(new t("Invalid token"));e.req.auth=h,e.req.user=m;const{groups:E,permissions:_}=yield y.getGroupsPermissions(m.id);e.req.groups=E,e.req.permissions=_,e.next()}))(e)}))(i,r,n)},Ue=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),qe=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.groups)&&void 0!==r?r:[]).includes(t)}),Ye=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==i?i:[]}),$e=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.permissions)&&void 0!==r?r:[]).includes(t)}),We=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==i?i:[]}),Ge=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),Ve=(e,t,i)=>{var n,s,o,d,a,l,u,c,p,v,g;const y=i.ctx instanceof r?i.ctx:null,h=null!==(n=null==y?void 0:y.id)&&void 0!==n?n:null,m=null!==(a=null!==(d=null===(o=null===(s=null==y?void 0:y.req)||void 0===s?void 0:s.user)||void 0===o?void 0:o.id)&&void 0!==d?d:i.user_id)&&void 0!==a?a:null,E={type:e,model:null!==(l=null==t?void 0:t.getTableName())&&void 0!==l?l:null,source:null!==(u=Env.BASE_NAME)&&void 0!==u?u:"",request_id:h,user_id:m};return y?Object.assign(Object.assign({},E),{full_url:null!==(c=y.getUrl())&&void 0!==c?c:"",ip_address:null!==(p=y.getIp())&&void 0!==p?p:"",user_agent:null!==(g=null===(v=y.req)||void 0===v?void 0:v.headers["user-agent"])&&void 0!==g?g:""}):E},ze=e=>{const t=M(e),i=t.primaryKeyAttribute;return{model:t,record_id:i?e.getDataValue(i):null}},Je={afterCreate:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e);yield ot.create(Object.assign(Object.assign({},Ve(De.CREATE,i,t)),{record:r,currently:e.toJSON()})).catch(b.catch)}),afterUpdate:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e),n={},s={},o=e.changed();o&&o.length&&o.forEach(t=>{n[t]=e.getDataValue(t),s[t]=e.previous(t)}),yield ot.create(Object.assign(Object.assign({},Ve(De.UPDATE,i,t)),{record:r,currently:n,previously:s})).catch(b.catch)}),afterDestroy:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e);yield ot.create(Object.assign(Object.assign({},Ve(De.DELETE,i,t)),{record:r,currently:e.toJSON()})).catch(b.catch)})},Qe=e=>(x(e)&&(e=Env.DATABASE_AUDIT),ee(e?Je:{}));let Xe=class RegisterModel extends oe{};Pe([te.Id(7),we("design:type",String)],Xe.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],Xe.prototype,"secret",void 0),Pe([te.FullDate(),we("design:type",Number)],Xe.prototype,"expired_at",void 0),Pe([te.Boolean(),we("design:type",Boolean)],Xe.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],Xe.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],Xe.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],Xe.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],Xe.prototype,"user_id",void 0),Xe=Pe([re(Re),ne("register"),se("5.2.0")],Xe);let Ze=class UserAuthModel extends oe{};Pe([te.Id(7),we("design:type",String)],Ze.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"secret",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"ip_address",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"user_agent",void 0),Pe([te.FullDate(),we("design:type",Object)],Ze.prototype,"revoked_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],Ze.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],Ze.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],Ze.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],Ze.prototype,"user_id",void 0),Ze=Pe([re(Re),ne("users_auth"),se("5.2.0")],Ze);let et=class PermissionModel extends oe{};Pe([te.Id(7),we("design:type",String)],et.prototype,"id",void 0),Pe([te.String(),de(),we("design:type",String)],et.prototype,"name",void 0),Pe([te.Text(),we("design:type",String)],et.prototype,"description",void 0),Pe([te.Boolean(),we("design:type",Boolean)],et.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],et.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],et.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],et.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>tt),we("design:type",Array)],et.prototype,"groups_permissions",void 0),et=Pe([re(Re),ne("permission"),Qe(),se("5.2.1")],et);let tt=class GroupPermissionModel extends oe{};Pe([te.Id(7),we("design:type",String)],tt.prototype,"id",void 0),Pe([te.CreatedAt(),we("design:type",Date)],tt.prototype,"created_at",void 0),Pe([ie.BelongsTo(()=>it),we("design:type",String)],tt.prototype,"group_id",void 0),Pe([ie.BelongsTo(()=>et),we("design:type",String)],tt.prototype,"permission_id",void 0),tt=Pe([re(Re),ne("groups_permissions"),Qe(),se("5.2.0")],tt);let it=class GroupModel extends oe{};Pe([te.Id(7),we("design:type",String)],it.prototype,"id",void 0),Pe([te.String(),de(),we("design:type",String)],it.prototype,"name",void 0),Pe([te.Text(),we("design:type",String)],it.prototype,"description",void 0),Pe([te.Boolean(),we("design:type",Boolean)],it.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],it.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],it.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],it.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>rt),we("design:type",Array)],it.prototype,"users_groups",void 0),Pe([ie.HasMany(()=>tt),we("design:type",Array)],it.prototype,"groups_Permission",void 0),it=Pe([re(Re),ne("group"),Qe(),se("5.2.1")],it);let rt=class UserGroupModel extends oe{};Pe([te.Id(7),we("design:type",String)],rt.prototype,"id",void 0),Pe([te.CreatedAt(),we("design:type",Date)],rt.prototype,"created_at",void 0),Pe([ie.BelongsTo(()=>it),we("design:type",String)],rt.prototype,"group_id",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],rt.prototype,"user_id",void 0),rt=Pe([re(Re),ne("users_groups"),Qe(),se("5.2.0")],rt);let nt=class UserPasswordModel extends oe{};Pe([te.Id(7),we("design:type",String)],nt.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],nt.prototype,"hash",void 0),Pe([te.FullDate(),we("design:type",Object)],nt.prototype,"revoked_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],nt.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],nt.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],nt.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],nt.prototype,"user_id",void 0),nt=Pe([re(Re),ne("users_password"),Qe(),se("5.2.0")],nt);let st=class UserModel extends oe{};Pe([te.Id(7),we("design:type",String)],st.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"name",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"username",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"email",void 0),Pe([te.Text(),we("design:type",String)],st.prototype,"notes",void 0),Pe([te.Enum(Le),ae(Le.ACTIVE),we("design:type",String)],st.prototype,"status",void 0),Pe([te.Json(),ae(()=>({})),we("design:type",Object)],st.prototype,"metadata",void 0),Pe([te.CreatedAt(),we("design:type",Date)],st.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],st.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],st.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>ot),we("design:type",Array)],st.prototype,"audits",void 0),Pe([ie.HasMany(()=>Ze),we("design:type",Array)],st.prototype,"users_auths",void 0),Pe([ie.HasMany(()=>Xe),we("design:type",Array)],st.prototype,"registers",void 0),Pe([ie.HasMany(()=>rt),we("design:type",Array)],st.prototype,"users_groups",void 0),Pe([ie.HasMany(()=>nt),we("design:type",Array)],st.prototype,"users_passwords",void 0),st=Pe([re(Re),ne("user"),Qe(),se("5.2.0")],st);let ot=class AuditModel extends oe{};Pe([te.Id(7),we("design:type",String)],ot.prototype,"id",void 0),Pe([te.Enum(De),we("design:type",String)],ot.prototype,"type",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"model",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"record",void 0),Pe([te.Json(),we("design:type",Object)],ot.prototype,"currently",void 0),Pe([te.Json(),we("design:type",Object)],ot.prototype,"previously",void 0),Pe([te.String(36),we("design:type",String)],ot.prototype,"request_id",void 0),Pe([te.Text(),we("design:type",String)],ot.prototype,"full_url",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"ip_address",void 0),Pe([te.Text(),we("design:type",String)],ot.prototype,"user_agent",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"source",void 0),Pe([te.FullDate(),we("design:type",Object)],ot.prototype,"reverted_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ot.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ot.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],ot.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],ot.prototype,"user_id",void 0),ot=Pe([re(Re),ne("audit"),se("5.2.0")],ot);let dt=class ConfigModel extends oe{};Pe([te.Id(7),we("design:type",String)],dt.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],dt.prototype,"key",void 0),Pe([te.Text(),we("design:type",String)],dt.prototype,"value",void 0),Pe([te.CreatedAt(),we("design:type",Date)],dt.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],dt.prototype,"updated_at",void 0),dt=Pe([re(Re),ne("configs"),se("5.2.0")],dt);let at=class ForgotModel extends oe{};Pe([te.Id(7),we("design:type",String)],at.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],at.prototype,"secret",void 0),Pe([te.FullDate(),we("design:type",Number)],at.prototype,"expired_at",void 0),Pe([te.Boolean(),we("design:type",Boolean)],at.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],at.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],at.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],at.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],at.prototype,"user_id",void 0),at=Pe([re(Re),ne("forgot"),se("5.2.0")],at);let lt=class LogModel extends oe{};Pe([te.Id(7),we("design:type",String)],lt.prototype,"id",void 0),Pe([te.Enum(xe),ae(xe.INFO),we("design:type",String)],lt.prototype,"level",void 0),Pe([te.Text(),we("design:type",String)],lt.prototype,"message",void 0),Pe([te.String(),we("design:type",String)],lt.prototype,"source",void 0),Pe([te.CreatedAt(),we("design:type",Date)],lt.prototype,"created_at",void 0),lt=Pe([re(Re),ne("log"),se("5.2.0")],lt);let ut=class MigrationModel extends oe{};Pe([te.Id(7),we("design:type",String)],ut.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],ut.prototype,"model",void 0),Pe([te.String(),we("design:type",String)],ut.prototype,"version",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ut.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ut.prototype,"updated_at",void 0),ut=Pe([re(Re),ne("migration"),se("5.2.0")],ut);let ct=class SessionModel extends oe{};Pe([te.Id(7),we("design:type",String)],ct.prototype,"id",void 0),Pe([te.Json(),we("design:type",Object)],ct.prototype,"data",void 0),Pe([te.FullDate(),we("design:type",Date)],ct.prototype,"expired_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ct.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ct.prototype,"updated_at",void 0),ct=Pe([re(Re),ne("session"),se("5.2.0")],ct);class Log{static error(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return be(this,void 0,void 0,function*(){var n;r&&b.console(null!==(n=this.colors[e])&&void 0!==n?n:C.White,e,t),Re&&(yield lt.create({level:e,message:t,source:null!=i?i:""}).catch(b.catch))})}}Log.colors={error:C.Red,info:C.Cyan,warn:C.Yellow};class Loggable{get log(){return e=>Loggable.logInfo(this,e)}static get log(){return e=>this.logInfo(this,e)}get error(){return e=>Loggable.logError(this,e)}static get error(){return e=>this.logError(this,e)}static logError(e,t){var i,r;Log.error(null!==(r=null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t)&&void 0!==r?r:"",this.source(e),Env.CONSOLE_ERROR)}static logInfo(e,t){Log.info(null!=t?t:"",this.source(e),Env.CONSOLE_ERROR)}static source(e){var t,i,r;const n=null!==(r=null!==(i=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==i?i:null==e?void 0:e.name)&&void 0!==r?r:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${n}`:n}}class Config extends Loggable{static all(e){return be(this,void 0,void 0,function*(){var t;const i=null!==(t=yield dt.findAll({where:(null==e?void 0:e.length)?{key:{[le.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(i.map(e=>[e.key,e.value]))})}static del(e){return be(this,void 0,void 0,function*(){return((yield dt.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return be(this,arguments,void 0,function*(e,t=""){const[i]=(yield dt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t){return be(this,void 0,void 0,function*(){const[i,r]=(yield dt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];i&&!r&&(i.value=t,yield i.save().catch(this.error))})}}class SessionStore extends pe{constructor(){super(),this.all=e=>be(this,void 0,void 0,function*(){e=e||k;const t=yield ct.findAll({attributes:["id","expired_at"],where:{expired_at:{[le.gte]:new Date}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.id)),e()}),this.clear=e=>be(this,void 0,void 0,function*(){yield ct.destroy().catch(b.catch),e&&e()}),this.destroy=(e,t)=>be(this,void 0,void 0,function*(){yield ct.destroy({where:{id:e}}).catch(b.catch),t&&t()}),this.expired=()=>be(this,void 0,void 0,function*(){yield ct.destroy({where:{expired_at:{[le.lt]:new Date}}}).catch(b.catch)}),this.get=(e,t)=>be(this,void 0,void 0,function*(){t=t||k;const i=yield ct.findOne({where:{id:e,expired_at:{[le.gte]:new Date}}}).catch(e=>(t(e),null));if(i){if(i.data.cookie){if(new Date(i.data.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(b.catch),void t(null)}t(null,i.data)}else t(null)}),this.length=e=>be(this,void 0,void 0,function*(){e&&e(null,(yield ct.count().catch(b.catch))||0)}),this.set=(e,t,i)=>be(this,void 0,void 0,function*(){i=i||k;const r=new Date;r.setTime(r.getTime()+Env.API_SESSION_LIFETIME);const[n,s]=(yield ct.findOrCreate({where:{id:e},defaults:{id:e,data:t,expired_at:r}}).catch(b.catch))||[];n?(s||(n.data=t,n.expired_at=r,yield n.save().catch(b.catch)),i()):i()}),setInterval(this.expired,6e4)}}let pt=class Service{};pt=Pe([ve(Loggable)],pt);let vt=class AuthService extends pt{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{id:t}=e,i=K(),r=yield Ze.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new s;return{auth:r,token:ye.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return be(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{decode:i}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!i)throw new t("Invalid token");const{id:r,secret:s}=i;if(r&&s){const e=yield st.findOne({where:{id:r,status:Le.ACTIVE}}).catch(this.error);if(e){const t=yield Ze.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=K(),yield t.save().catch(this.error);return{auth:t,token:ye.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return be(this,void 0,void 0,function*(){const{decode:i}=yield this.verify(e);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield st.findOne({attributes:this.userAttributes,where:{id:r,status:Le.ACTIVE}}).catch(this.error);if(e){const t=yield Ze.findOne({where:{secret:n,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,i){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new n("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t("Invalid token");try{return{decode:ye.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return be(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield st.findOne({attributes:this.userAttributes,where:{token:e,status:Le.ACTIVE}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Ze.findOrCreate({where:{secret:t,user_id:i.id},defaults:{secret:t,user_id:i.id}}).catch(this.error))||[];if(r)return r.revoked_at&&(r.revoked_at=null,yield r.save().catch(this.error)),{auth:r,user:i}}throw new t("Invalid token")})}};vt=Pe([ge()],vt);class ModelService extends pt{constructor(e,t){var i,r;super(),this.attributes=[],this.permissions=[],this.search=[],this.model=e,(null==t?void 0:t.permissions)&&(this.permissions=t.permissions);const n=Object.keys(e.getAttributes());this.attributes=this.filterAttributes(n,null!==(i=null==t?void 0:t.attributes)&&void 0!==i?i:[]),this.search=this.filterAttributes(n,null!==(r=null==t?void 0:t.search)&&void 0!==r?r:this.attributes)}applySelect(e,t,i){if(!t)return;const r=null==e?void 0:e.getQuery(i?`${i}_select`:"select"),n=t.attributes,s=e=>n.includes(e);t.attributes=[],j(r)&&r.length&&t.attributes.push(...r.split(/\s*,\s*/g).filter(s)),t.attributes.length||(t.attributes=n)}applyOrders(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("asc"),r=null==e?void 0:e.getQuery("desc"),n=[],s=t.attributes,o=e=>s.includes(e);j(i)&&i.length&&n.push(...i.split(/\s*,\s*/g).filter(o).map(e=>[e,"ASC"])),j(r)&&r.length&&n.push(...r.split(/\s*,\s*/g).filter(o).map(e=>[e,"DESC"])),n.length&&(t.order=n)}applyPagination(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("limit"),r=null==e?void 0:e.getQuery("offset");x(t.limit)&&(t.limit=Env.MODEL_LIMIT,j(i)&&(t.limit=parseInt(i)||0),t.limit=B(t.limit,-1,Env.MODEL_LIMIT_MAX)),t.limit<0&&(t.limit=void 0),j(r)&&(t.offset=parseInt(r)||0,t.offset<0&&(t.offset=void 0))}applySearch(e,t){var i;if(!t)return;const r=null==e?void 0:e.getQuery("search");r&&j(r)&&(t.where=Object.assign(Object.assign({},null!==(i=t.where)&&void 0!==i?i:{}),{[le.or]:this.search.map(e=>({[e]:{[le.substring]:r}}))}))}applyWhere(e,t,i){var r,n;if(!t)return null;const s=null==e?void 0:e.getQuery(i?`${i}_where`:"where");if(!j(s))return null;const d=t.attributes,a=ue.parse(d,s);return x(a.error)?(t.where=Object.assign(Object.assign({},null!==(r=t.where)&&void 0!==r?r:{}),null!==(n=a.value)&&void 0!==n?n:{}),null):new o(a.error.join(", "))}countAll(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,options:n={}}=e,s=F({},n);s.attributes=this.getAttributes(null!==(t=null==s?void 0:s.attributes)&&void 0!==t?t:[]),this.applySearch(r,s);const o=this.applyWhere(r,s);if(o)return null==r||r.error(o),0;this.applySelect(r,s);const a=null!==(i=yield this.model.count(Object.assign(Object.assign({},s),{distinct:!!s.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==i?i:0;return null==r||r.prepare(d.OK,{count:a}),a})}create(e){return be(this,void 0,void 0,function*(){var t,i;const{body:r={},ctx:n,options:o={}}=e,a=F({},o),l=yield this.model.create(Object.assign({},F({},null!==(i=null===(t=null==n?void 0:n.req)||void 0===t?void 0:t.body)&&void 0!==i?i:{},r)),Object.assign(Object.assign({},a),{ctx:n})).catch(this.error);if(!l)return null==n||n.error(new s),null;const{primaryKeyAttribute:u}=this.model;return null==n||n.prepare(d.OK,{[u]:l.getDataValue(u)}),l})}delete(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,id:s,options:o={}}=e,{primaryKeyAttribute:d}=this.model,l=null!==(t=null==r?void 0:r.getParam(d))&&void 0!==t?t:s;if(x(l))return null==r||r.error(new a),0;const u=F({},o),c=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},u),{where:Object.assign(Object.assign({},null!==(i=u.where)&&void 0!==i?i:{}),{[d]:l}),individualHooks:!0}),{ctx:r})).catch(this.error);return c?(null==r||r.success("OK"),c):(null==r||r.error(new n),0)})}filterAttributes(e,t){if(H(t))return t.length?t.filter(t=>j(t)&&e.includes(t)):e;const{exclude:i,include:r}=t,n=x(r)?e:r.filter(t=>j(t)&&e.includes(t)),s=null!=i?i:[];return s.length?n.filter(e=>!s.includes(e)):n}findAll(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,callback:n,options:s={},query:o=!0}=e,a=F({},s);if(a.attributes=this.getAttributes(null!==(t=null==a?void 0:a.attributes)&&void 0!==t?t:[]),o&&this.applySelect(r,a),this.applyOrders(r,a),this.applyPagination(r,a),(null!==(i=null==a?void 0:a.limit)&&void 0!==i?i:0)>Env.MODEL_LIMIT_MAX&&(a.limit=Env.MODEL_LIMIT_MAX),this.applySearch(r,a),o){const e=this.applyWhere(r,a);if(e)return null==r||r.error(e),{count:0,records:[]}}const[l,u]=yield Promise.all([this.model.count(Object.assign(Object.assign({},a),{distinct:!!a.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error).then(e=>null!=e?e:0),this.model.findAll(a).catch(this.error).then(e=>null!=e?e:[])]),c={count:l,records:n?yield n(u):u};return null==r||r.prepare(d.OK,c),c})}findOne(e){return be(this,void 0,void 0,function*(){var t,i,r;const{callback:s,ctx:o,id:l,options:u={},query:c=!0}=e,{primaryKeyAttribute:p}=this.model,v=null!==(t=null==o?void 0:o.getParam(p))&&void 0!==t?t:l;if(x(v))return null==o||o.error(new a),null;const g=F({},u);g.attributes=this.getAttributes(null!==(i=null==g?void 0:g.attributes)&&void 0!==i?i:[]),c&&this.applySelect(o,g);const y=yield this.model.findOne(Object.assign(Object.assign({},g),{where:Object.assign(Object.assign({},null!==(r=null==g?void 0:g.where)&&void 0!==r?r:{}),{[p]:v})})).catch(this.error);return y?(null==o||o.prepare(d.OK,s?yield s(y):y.toJSON()),y):(null==o||o.error(new n),null)})}getAttributes(e){return this.filterAttributes(this.attributes,e)}include(e,t){var i;const r=U(t),{ctx:n}=null!=t?t:{};r.attributes=this.filterAttributes(Object.keys(e.getAttributes()),null!==(i=r.attributes)&&void 0!==i?i:[]),this.applySearch(n,r);const s=this.applyWhere(n,r,t.name);return s?(null==n||n.error(s),null):(this.applySelect(n,r,t.name),Object.assign({model:e},r))}name(){return this.model.tableName}sync(){return be(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",active:!0};yield q(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=Y(e.replace(/_/g," ")," ");yield et.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${Y(i," ")}`,key:r,tags:n},t)})}))})}update(e){return be(this,void 0,void 0,function*(){var t,i,r,n,s;const{ctx:o,body:d,id:l,options:u={}}=e,{primaryKeyAttribute:c}=this.model,p=null!==(t=null==o?void 0:o.getParam(c))&&void 0!==t?t:l;if(x(p))return null==o||o.error(new a),!1;const v=F({},u),[g]=null!==(s=yield this.model.update(Object.assign({},F({},null!==(r=null===(i=null==o?void 0:o.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{},null!=d?d:{})),Object.assign(Object.assign(Object.assign({},v),{where:Object.assign(Object.assign({},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{}),{[c]:p}),individualHooks:!0}),{ctx:o})).catch(this.error))&&void 0!==s?s:[];return g?(null==o||o.success("OK"),!0):(null==o||o.success("Record not changed"),!1)})}}let gt=class UserService extends pt{constructor(){super(...arguments),this.hashOptions={algorithm:Env.PASSWORD_ALGORITHM,memoryCost:Env.PASSWORD_MEMORY_COST,parallelism:Env.PASSWORD_PARALLELISM,timeCost:Env.PASSWORD_TIME_COST}}createPassword(e,t,i){return be(this,void 0,void 0,function*(){yield nt.update({revoked_at:new Date},{where:{revoked_at:null,user_id:e}}).catch(this.error);const r=he(t+Env.PASSWORD_PEPPER,this.hashOptions);yield nt.create({hash:r,user_id:e},Object.assign({},{ctx:i})).catch(this.error)})}findAllPermission(e){return be(this,void 0,void 0,function*(){var t;return null!==(t=yield et.findAll({attributes:["name"],where:{active:!0},include:[{association:"groups_permissions",required:!0,include:[{association:"group",required:!0,attributes:["id","name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]})}getGroups(e){return be(this,void 0,void 0,function*(){var t;return(null!==(t=yield it.findAll({attributes:["name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.name)})}getGroupsPermissions(e){return be(this,void 0,void 0,function*(){const t=[],i=[];return(yield this.findAllPermission(e)).forEach(e=>{i.push(e.name),e.groups_permissions.forEach(e=>t.push(e.group.name))}),{groups:$(t),permissions:$(i)}})}getPermissions(e){return be(this,void 0,void 0,function*(){return(yield this.findAllPermission(e)).map(e=>e.name)})}};gt=Pe([ge()],gt);class Application extends l{constructor(e,t){super(e,F({},{cross:!!Env.HTTP_CROSS&&("*"===Env.HTTP_CROSS||{origin:Env.HTTP_CROSS.split(",")}),hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new SessionStore,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:K},tls:{ca:Env.HTTP_TLS_CA,cert:Env.HTTP_TLS_CRT,key:Env.HTTP_TLS_KEY}},null!=t?t:{})),this.hash=new R(Env.API_KEY_HASH)}error(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.error(e.message,t,Env.CONSOLE_ERROR)}log(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return be(this,void 0,void 0,function*(){yield Re.sync(),yield this.migrations(Re),yield W(this.controllers,e=>be(this,void 0,void 0,function*(){L(e.sync)&&(yield e.sync(this))})),this.authService=new vt,this.userService=new gt,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new X({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>be(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield G(2e3)})))})}migrations(e){return be(this,void 0,void 0,function*(){const t=[];yield W(Object.keys(e.models),i=>be(this,void 0,void 0,function*(){var r;const n=e.models[i],s=n.version();if(!s)return;const[o,d]=null!==(r=yield ut.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=s)&&(o.version=s,yield o.save().catch(this.error),t.push(n))})),yield W(t,e=>be(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let yt=class BaseController extends V{constructor(){super(...arguments),this.permissions=[]}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}session(e,t,i){return be(this,void 0,void 0,function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(k):(i.user_agent=t,i.save(k))),e.next()})}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})}))})}};Pe([Ie(0,u()),Ie(1,c("user-agent")),Ie(2,p()),we("design:type",Function),we("design:paramtypes",[r,String,Object]),we("design:returntype",Promise)],yt.prototype,"session",null),yt=Pe([ve(Loggable)],yt);let ht=class ModelController extends yt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return be(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return be(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return be(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return be(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return be(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})})),this.service=new ModelService(this.model,{attributes:this.attributes.length?this.attributes:void 0,search:this.search.length?this.search:void 0})})}update(e){return be(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};ht=Pe([v(yt)],ht);let mt=class AuditsController extends ht{constructor(){super(...arguments),this.model=ot,this.permissions=["read"]}all(e,t,i){return be(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["currently","previously"]},where:r,order:[["created_at","DESC"]]}})})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Pe([g(),He(),Ke(),Ie(0,u()),Ie(1,y("type")),Ie(2,y("table")),we("design:type",Function),we("design:paramtypes",[r,String,String]),we("design:returntype",Promise)],mt.prototype,"all",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],mt.prototype,"get",null),mt=Pe([h("/audits"),v(ht)],mt);let Et=class AuthController extends yt{constructor(){super(...arguments),this.authService=new vt}login(e,i,r,n,s,o){return be(this,void 0,void 0,function*(){var d;yield G(Env.SLEEP_AUTH);const a=yield st.findOne({where:{[le.or]:[{email:r},{username:r}]}}).catch(this.error);if(!a)return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield nt.findOne({where:{revoked_at:null,user_id:a.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!l||!(yield me(l.hash,n).catch(k)))return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield Xe.findOne({where:{active:!0,user_id:a.id}}).catch(this.error);if(u)return e.error(new t("Activation Required")),o.emit("auth.activation",{ctx:e,register:u,user:a}),void this.emit("auth.activation",{ctx:e,register:u,user:a});if(a.status!=Le.ACTIVE)return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e,user:a}),void this.emit("auth.failure",{ctx:e,user:a});const{auth:c,token:p}=null!==(d=yield this.authService.create(a).catch(t=>{e.error(t),o.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==d?d:{};c&&p&&(c.user_agent=i,c.ip_address=e.getIp(),yield c.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.setCookie(Env.API_TOKEN_COOKIE,p,{maxAge:s?Env.TOKEN_TTL:void 0}),e.json({token:p}),o.emit("auth.login",{ctx:e,auth:c,user:a}),this.emit("auth.login",{ctx:e,auth:c,user:a}))})}logout(e,i,r,n){return be(this,void 0,void 0,function*(){if(yield this.authService.destroy(i))return Env.API_TOKEN_COOKIE_SET&&e.clearCookie(Env.API_TOKEN_COOKIE),e.success("OK"),n.emit("auth.logout",{auth:i,ctx:e,user:r}),void this.emit("auth.logout",{auth:i,ctx:e,user:r});e.error(new t("Access Denied"))})}renew(e,t,i,r){return be(this,void 0,void 0,function*(){var n;const{auth:s,token:o}=null!==(n=yield this.authService.renew(i).catch(t=>{e.error(t)}))&&void 0!==n?n:{};s&&o&&(s.user_agent=t,yield s.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:s,ctx:e}),this.emit("auth.renew",{auth:s,ctx:e}))})}user(e,t){return be(this,void 0,void 0,function*(){const{groups:i,permissions:r,profile:n}=e.req;if(!i||!r)return e.error(new s);e.json(Object.assign(Object.assign({},t.toJSON()),{groups:i,permissions:r,profile:n}))})}};Pe([m("/login"),E(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),Ie(0,u()),Ie(1,c("user-agent")),Ie(2,_("username")),Ie(3,_("password")),Ie(4,_("remember")),Ie(5,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,String,Boolean,Application]),we("design:returntype",Promise)],Et.prototype,"login",null),Pe([g("/logout"),He(),Ie(0,u()),Ie(1,Ue()),Ie(2,Ge()),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,Ze,st,Application]),we("design:returntype",Promise)],Et.prototype,"logout",null),Pe([m("/renew"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,c("user-agent")),Ie(2,_("token")),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,Application]),we("design:returntype",Promise)],Et.prototype,"renew",null),Pe([g(),g("/me"),He(),Ie(0,u()),Ie(1,Ge()),we("design:type",Function),we("design:paramtypes",[r,st]),we("design:returntype",Promise)],Et.prototype,"user",null),Et=Pe([h("/auth"),v(yt)],Et);let _t=class CrudController extends ht{constructor(){super(...arguments),this._crud={}}CrudArgumentsCountAll(e){return{ctx:e}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidateCreate(){return this._crud}CrudValidateUpdate(){return this._crud}add(e){return be(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return be(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return be(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return be(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return be(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,t){return be(this,void 0,void 0,function*(){var i,r;const n=z.object(t).parse(),{error:s,message:d,value:a}=yield n.validateAsync(null!==(r=null===(i=e.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{});if(s)return e.error(new o(null!=d?d:s));e.req.body=a,e.next()})}validateCreate(e){return be(this,void 0,void 0,function*(){const t=this.CrudValidateCreate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}validateUpdate(e){return be(this,void 0,void 0,function*(){const t=this.CrudValidateUpdate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}};Pe([m(),He(),Me(),A("validateCreate"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"add",null),Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"all",null),Pe([g("/count"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"rows",null),Pe([S("/:id"),He(),ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"del",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"get",null),Pe([O("/:id"),He(),je(),A("validateUpdate"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"set",null),Pe([Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"validateCreate",null),Pe([Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"validateUpdate",null),_t=Pe([v(ht)],_t);let ft=class FilesController extends yt{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return be(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Te(this.directory,t);if(!Ee(i)||!_e(i).isDirectory())return e.error(new n);let r;return r=fe(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(J),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!Ee(e))return null;const t=_e(e),i=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})}))})}};Pe([g("/path"),g("/path/*path"),He(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],ft.prototype,"files",null),ft=Pe([h("/files"),v(yt)],ft);let At=class ForgotController extends yt{check(e,t){return be(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new n);i.secret=Q(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return be(this,void 0,void 0,function*(){yield G(Env.SLEEP_FORGOT);const r=t,s=yield st.findOne({where:{[le.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.error(new n);const o=Q(),d=Date.now()+6e4*Env.API_TOKEN_FORGOT,a=yield at.create({token:o,timestamp:d,active:!0,user_id:s.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:a,user:s}),this.emit("forgot.send",{ctx:e,forgot:a,user:s})})}reset(e,t,i,r){return be(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i)return e.error(new n);i.active=!1,yield i.save().catch(this.error),yield i.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})})}find(e){return be(this,void 0,void 0,function*(){return yield at.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}};Pe([g("/check"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,_("token")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],At.prototype,"check",null),Pe([m(),E(e=>({username:e.string().min(4).required()})),Ie(0,u()),Ie(1,_("username")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],At.prototype,"forgot",null),Pe([m("/reset"),E(e=>({token:e.string().required(),password:e.string().min(5).required()})),Ie(0,u()),Ie(1,_("token")),Ie(2,_("password")),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,Application]),we("design:returntype",Promise)],At.prototype,"reset",null),At=Pe([h("/forgot"),v(yt)],At);let St=class GroupsController extends _t{constructor(){super(...arguments),this.model=it,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),active:z.boolean().parse().required()},this.schemaUpdate={description:z.string().empty(),active:z.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};St=Pe([h("/groups"),v(_t)],St);let Ot=class GroupsPermissionsController extends ht{constructor(){super(...arguments),this.model=tt,this.permissions=[]}all(e,t){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{association:"permission"}]},callback:e=>e.map(e=>e.permission),query:!1})})}set(e,t,i){return be(this,void 0,void 0,function*(){const r=yield it.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n);const s=r.id,o=[];yield W($(i),t=>be(this,void 0,void 0,function*(){var i;if(!(yield et.count({where:{id:t}})))return;const[r]=null!==(i=yield tt.findOrCreate(Object.assign({where:{group_id:s,permission_id:t},defaults:{group_id:s,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&o.push(t)})),yield tt.destroy(Object.assign({where:{group_id:s,permission_id:{[le.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/permissions"),He(),Ke("groups"),Ie(0,u()),Ie(1,T("id")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],Ot.prototype,"all",null),Pe([O("/:id/permissions"),He(),je("groups"),E(e=>({permissions:e.array(e.string())})),Ie(0,u()),Ie(1,T("id")),Ie(2,_("permissions")),we("design:type",Function),we("design:paramtypes",[r,String,Array]),we("design:returntype",Promise)],Ot.prototype,"set",null),Ot=Pe([h("/groups"),v(ht)],Ot);let Tt=class HealthController{ping(e){return be(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}};Pe([P("/"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Tt.prototype,"ping",null),Tt=Pe([h("/health")],Tt);let Pt=class LogsController extends ht{constructor(){super(...arguments),this.model=lt,this.permissions=["read"]}all(e){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]}})})}};Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Pt.prototype,"all",null),Pt=Pe([h("/logs"),v(ht)],Pt);let It=class PermissionsController extends _t{constructor(){super(...arguments),this.model=et,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),active:z.boolean().parse().required()},this.schemaUpdate={description:z.string().empty(),active:z.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};It=Pe([h("/permissions"),v(_t)],It);let wt=class RegisterController extends yt{register(e,t,i){return be(this,void 0,void 0,function*(){yield G(Env.SLEEP_REGISTRY);const{name:r,date:n,email:o,username:d,password:a,confirm:l}=t,u=d||o,c=D(a);if(yield st.count({where:{[le.or]:[{email:o},{username:u}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(c!=D(l))return e.error("INVALID PASSWORD");const p=yield st.create({name:r,email:o,username:u,password:c,avatar:"",date:n,description:"",status:Le.PENDING}).catch(this.error);if(!p)return e.error(new s);const v=yield Xe.create({token:yield this.getId(),active:!0,user_id:p.id}).catch(this.error);if(!v)return yield p.destroy().catch(this.error),e.error(new s);e.success("OK"),i.emit("register.user",{ctx:e,register:v,user:p}),this.emit("register.user",{ctx:e,register:v,user:p})})}confirm(e,t,i){return be(this,void 0,void 0,function*(){const r=yield Xe.findOne({where:{token:t,active:!0},include:[{association:"users",required:!0}]}).catch(this.error);if(!r)return e.error(new n);r.active=!1,yield r.save().catch(this.error),r.user.status=Le.ACTIVE,yield r.user.save().catch(this.error),e.success("OK"),i.emit("register.confirm",{ctx:e,register:r,user:r.user}),this.emit("register.confirm",{ctx:e,register:r,user:r.user})})}send(e,t,i){return be(this,void 0,void 0,function*(){const r=t,s=yield Xe.findOne({where:{active:!0},include:[{model:st,required:!0,where:{[le.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!s)return e.error(new n);e.success("OK"),i.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})})}getId(){return be(this,void 0,void 0,function*(){const e=K();return(yield Xe.count({where:{token:e}}))?this.getId():e})}};Pe([m(),E(e=>({name:e.string().required(),date:e.date().required(),email:e.string().email().required(),username:e.string().min(4).empty(),password:e.string().min(5).required(),confirm:e.string().min(5).required()})),Ie(0,u()),Ie(1,_()),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,Object,Application]),we("design:returntype",Promise)],wt.prototype,"register",null),Pe([m("/confirm"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,_("token")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],wt.prototype,"confirm",null),Pe([m("/send"),E(e=>({username:e.string().min(4).required()})),Ie(0,u()),Ie(1,_("username")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],wt.prototype,"send",null),wt=Pe([h("/register"),v(yt)],wt);let bt=class SetupController extends yt{constructor(){super(...arguments),this.userService=new gt}setup(e){return be(this,void 0,void 0,function*(){var t;if(yield st.count())return e.error(new n("Endpoint Not Found"));const i=yield st.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:Le.ACTIVE},Object.assign({},{ctx:e})).catch(this.error);if(!i)return e.error(new s);yield this.userService.createPassword(i.id,"admin",e);const r=yield it.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield rt.create({user_id:i.id,group_id:r.id},Object.assign({},{ctx:e})),yield it.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield it.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const o=null!==(t=yield et.findAll({where:{active:!0}}).catch(this.error))&&void 0!==t?t:[];yield W(o,t=>be(this,void 0,void 0,function*(){yield tt.create({group_id:r.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};Pe([g(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],bt.prototype,"setup",null),bt=Pe([h("/setup"),v(yt)],bt);let Ct=class UsersController extends ht{constructor(){super(),this.model=st,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&Ee(Env.API_HTTP_PUBLIC)&&!Ee(this.path)&&Ae(this.path)}avatar(e,t){return be(this,void 0,void 0,function*(){var i;const r=e.getFiles();if(r.file&&r.file.length){const{filename:n,path:o}=null!==(i=r.file[0])&&void 0!==i?i:{};if(n){const i=yield st.findOne({where:{user_id:t.id}}).catch(this.error);if(!i)return Se(o).isFile()&&Oe(o),e.error(new s);const r=this.path+"/"+i.metadata.avatar_url;if(Ee(r)&&Se(r).isFile()&&Oe(r),i.changed("metadata",!0),i.metadata.avatar_url=n,yield i.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return be(this,void 0,void 0,function*(){var e;const t=K();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return be(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return be(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,t,i){return be(this,void 0,void 0,function*(){if(i.id==t)return e.error(new n);yield this.delete({ctx:e})})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return be(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};Pe([m("/avatar"),He(),I({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),Ie(0,u()),Ie(1,Ge()),we("design:type",Function),we("design:paramtypes",[r,st]),we("design:returntype",Promise)],Ct.prototype,"avatar",null),Pe([m(),He(),Me(),E(e=>({name:e.string().required(),email:e.string().email().required(),username:e.string().min(3).required(),description:e.string().empty(""),state:e.boolean().parse().empty(!0)})),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"add",null),Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"all",null),Pe([g("/count"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"rows",null),Pe([S("/:id"),He(),ke(),Ie(0,u()),Ie(1,T("id")),Ie(2,Ge()),we("design:type",Function),we("design:paramtypes",[r,String,st]),we("design:returntype",Promise)],Ct.prototype,"del",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"get",null),Pe([O("/:id"),He(),je(),E(e=>({name:e.string().empty(),email:e.string().email().empty(),username:e.string().min(3).empty(),description:e.string().empty(),state:e.boolean().parse().empty()})),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"set",null),Ct=Pe([h("/users"),v(ht),we("design:paramtypes",[])],Ct);let Rt=class UsersGroupsController extends ht{constructor(){super(...arguments),this.model=rt,this.permissions=[]}all(e,t){return be(this,void 0,void 0,function*(){if(!(yield st.findByPk(t,{attributes:["id"]}).catch(this.error)))return e.error(new n("User Not Found"));yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{association:"group"}]},callback:e=>e.map(e=>e.group),query:!1})})}set(e,t,i){return be(this,void 0,void 0,function*(){const r=yield st.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n("User Not Found"));const s=r.id,o=[];yield W($(i),t=>be(this,void 0,void 0,function*(){var i;if(!(yield it.count({where:{id:t}})))return;const[r]=null!==(i=yield rt.findOrCreate(Object.assign({where:{user_id:s,group_id:t},defaults:{user_id:s,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&o.push(t)})),yield rt.destroy(Object.assign({where:{user_id:s,group_id:{[le.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/groups"),He(),Ke("users"),Ie(0,u()),Ie(1,T("id")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],Rt.prototype,"all",null),Pe([O("/:id/groups"),He(),je("users"),E(e=>({groups:e.array(e.string())})),Ie(0,u()),Ie(1,T("id")),Ie(2,_("groups")),we("design:type",Function),we("design:paramtypes",[r,String,Array]),we("design:returntype",Promise)],Rt.prototype,"set",null),Rt=Pe([h("/users"),v(ht)],Rt);export{Application,Qe as Audit,ot as AuditModel,De as AuditTypes,mt as AuditsController,Et as AuthController,vt as AuthService,yt as BaseController,Me as CanCreate,ke as CanDelete,Ke as CanRead,je as CanUpdate,Config,dt as ConfigModel,_t as CrudController,Env,ft as FilesController,At as ForgotController,at as ForgotModel,it as GroupModel,tt as GroupPermissionModel,St as GroupsController,Ot as GroupsPermissionsController,Be as HasGroups,Fe as HasPermissions,Tt as HealthController,He as IsAuthenticated,Log,lt as LogModel,Loggable,xe as Loglevels,Pt as LogsController,ut as MigrationModel,ht as ModelController,ModelService,et as PermissionModel,It as PermissionsController,wt as RegisterController,Xe as RegisterModel,Ue as ReqAuth,qe as ReqGroup,Ye as ReqGroups,$e as ReqPermission,We as ReqPermissions,Ge as ReqUser,pt as Service,ct as SessionModel,SessionStore,bt as SetupController,Ze as UserAuthModel,rt as UserGroupModel,st as UserModel,nt as UserPasswordModel,gt as UserService,Le as UserStatus,Ct as UsersController,Rt as UsersGroupsController,Ne as canFactory,Re as sequelize};
7
+ import{Use as e,UnauthorizedError as t,parameterFactory as i,Context as r,NotFoundError as n,InternalServerError as s,ValidationError as o,StatusCodes as d,BadRequestError as a,Application as l,Ctx as u,Headers as c,Session as p,Extends as v,Get as g,Query as y,Controller as h,Post as m,Validate as E,Body as _,App as f,Middleware as A,Delete as S,Put as O,Params as T,All as P,Upload as I}from"@andrewcaires/express";import{Env as w,Log as b,LogColor as C,Hash as R,sha256 as D}from"@andrewcaires/node";import{isUndefined as x,isFunction as L,includesArray as N,getConstructor as M,noop as k,uuidv7 as K,isString as j,clamp as B,merge as F,isArray as H,clone as U,forEachAsync as q,upperCamelCase as Y,uniqueArray as $,forEachSeries as W,sleep as G,EventEmitter as V,Validation as z,isDef as J,uniqueID as Q}from"@andrewcaires/utils.js";import{WebSocketServer as X}from"ws";import{Sequelize as Z,Hooks as ee,Column as te,Association as ie,Database as re,ModelName as ne,Version as se,Model as oe,Index as de,DefaultValue as ae,Op as le,Where as ue}from"@andrewcaires/sequelize";import{config as ce}from"dotenv";import{Store as pe}from"express-session";import{Trait as ve,Singleton as ge}from"@andrewcaires/decorator";import ye from"jsonwebtoken";import{hashSync as he,verify as me}from"@node-rs/argon2";import{existsSync as Ee,statSync as _e,readdirSync as fe,mkdirSync as Ae,lstatSync as Se,rmSync as Oe}from"fs";import{join as Te}from"path";function Pe(e,t,i,r){var n,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(o=(s<3?n(o):s>3?n(t,i,o):n(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function Ie(e,t){return function(i,r){t(i,r,e)}}function we(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function be(e,t,i,r){return new(i||(i=Promise))(function(n,s){function o(e){try{a(r.next(e))}catch(e){s(e)}}function d(e){try{a(r.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,d)}a((r=r.apply(e,t||[])).next())})}var Ce;"function"==typeof SuppressedError&&SuppressedError,ce({quiet:!0});class Env extends w{}Ce=Env,Env.BASE_NAME=Ce.getString("BASE_NAME",""),Env.CONSOLE_ERROR=Ce.getBool("CONSOLE_ERROR",!1),Env.DATABASE_URI=Ce.getString("DATABASE_URI","",!0),Env.DATABASE_LOG=Ce.getBool("DATABASE_LOG",!1),Env.DATABASE_AUDIT=Ce.getBool("DATABASE_AUDIT",!0),Env.DATABASE_PREFIX=Ce.getString("DATABASE_PREFIX",""),Env.DATABASE_TIMEZONE=Ce.getString("DATABASE_TIMEZONE","+00:00"),Env.HTTP_CROSS=Ce.getString("HTTP_CROSS",""),Env.HTTP_TLS_CA=Ce.getFile("HTTP_TLS_CA"),Env.HTTP_TLS_CRT=Ce.getFile("HTTP_TLS_CRT"),Env.HTTP_TLS_KEY=Ce.getFile("HTTP_TLS_KEY"),Env.MODEL_LIMIT=Ce.getInt("MODEL_LIMIT",10),Env.MODEL_LIMIT_MAX=Ce.getInt("MODEL_LIMIT_MAX",100),Env.PASSWORD_ALGORITHM=Ce.getInt("PASSWORD_ALGORITHM",2),Env.PASSWORD_MEMORY_COST=Ce.getInt("PASSWORD_MEMORY_COST",4096),Env.PASSWORD_PARALLELISM=Ce.getInt("PASSWORD_PARALLELISM",1),Env.PASSWORD_PEPPER=Ce.getString("PASSWORD_PEPPER",""),Env.PASSWORD_TIME_COST=Ce.getInt("PASSWORD_TIME_COST",3),Env.SLEEP_AUTH=Ce.getMs("SLEEP_AUTH","2s"),Env.SLEEP_FORGOT=Ce.getMs("SLEEP_FORGOT","5s"),Env.SLEEP_REGISTRY=Ce.getMs("SLEEP_REGISTRY","5s"),Env.TOKEN_CRT=Ce.getFile("TOKEN_CRT"),Env.TOKEN_KEY=Ce.getFile("TOKEN_KEY"),Env.TOKEN_TTL=Ce.getMs("TOKEN_TTL","1d"),Env.TOKEN_TYPE=Ce.getString("TOKEN_TYPE","bearer"),Env.API_BODYPARSER_STRICT=Ce.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Ce.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Ce.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Ce.getString("API_BODYPARSER_TYPE","json"),Env.API_HTTP_PORT=Ce.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=Ce.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_HYBRID=Ce.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Ce.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Ce.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Ce.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Ce.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=Ce.getString("API_KEY_HEADER","x-api-key"),Env.API_SESSION_NAME=Ce.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Ce.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Ce.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_COOKIE=Ce.getString("API_TOKEN_COOKIE","authorization"),Env.API_TOKEN_COOKIE_SET=Ce.getBool("API_TOKEN_COOKIE_SET",!0),Env.API_TOKEN_FORGOT=Ce.getMs("API_TOKEN_FORGOT","1d"),Env.API_TOKEN_HEADER=Ce.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_RENEW=Ce.getMs("API_TOKEN_RENEW","1d"),Env.API_USER_HISTORY=Ce.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Ce.getBool("API_WEBSOCKET_START",!1);const Re=new Z({uri:Env.DATABASE_URI,logging:!!Env.DATABASE_LOG&&(e=>b.console(C.Magenta,"sql",e)),prefix:Env.DATABASE_PREFIX,timezone:Env.DATABASE_TIMEZONE});var De,xe,Le;!function(e){e.CREATE="CREATE",e.DELETE="DELETE",e.UPDATE="UPDATE"}(De||(De={})),function(e){e.INFO="info",e.WARN="warn",e.ERROR="error"}(xe||(xe={})),function(e){e.ACTIVE="active",e.PENDING="pending",e.DISABLED="disabled",e.LOCKED="locked",e.ARCHIVED="archived"}(Le||(Le={}));const Ne=i=>r=>(n,s,o)=>{e(e=>be(void 0,void 0,void 0,function*(){var n;x(r)&&(r=L(e.controller.name)?e.controller.name():null===(n=e.controller.constructor)||void 0===n?void 0:n.name);const{permissions:s=[]}=e.req;if(s.includes(`${r}.${i}`))return e.next();e.error(new t("Access Denied"))}))(n,s,o)},Me=Ne("create"),ke=Ne("delete"),Ke=Ne("read"),je=Ne("update"),Be=(...i)=>(r,n,s)=>{e(e=>be(void 0,void 0,void 0,function*(){const{groups:r=[]}=e.req;if(N(i,r))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},Fe=(...i)=>(r,n,s)=>{e(e=>be(void 0,void 0,void 0,function*(){const{permissions:r}=e.req;if(N(i,null!=r?r:[]))return e.next();e.error(new t("Access Denied"))}))(r,n,s)},He=()=>(i,r,n)=>{e(e=>be(void 0,void 0,void 0,function*(){yield(e=>be(void 0,void 0,void 0,function*(){var i,r,n,s;if(e.req.auth&&e.req.user)return e.next();const{[Env.API_KEY_HEADER]:o,[Env.API_TOKEN_HEADER]:d,"user-agent":a}=e.getHeaders(),l=e.getQuery(Env.API_KEY_HEADER),u=(null===(i=o||l)||void 0===i?void 0:i.toString())||"";let c=e.getCookie(Env.API_TOKEN_COOKIE);c=`${Env.TOKEN_TYPE} ${c}`;const[p,v]=null!==(n=null===(r=d||c)||void 0===r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(u||v&&p.toLowerCase()==Env.TOKEN_TYPE))return e.error(new t("Invalid token"));const{authService:g,userService:y}=e.app,{auth:h,user:m}=null!==(s=yield(u?g.key(u.toString()):g.user(v)).catch(t=>{e.error(t)}))&&void 0!==s?s:{};if(!h||!m)return;if(!u&&h.user_agent&&h.user_agent!=a)return e.error(new t("Invalid token"));e.req.auth=h,e.req.user=m;const{groups:E,permissions:_}=yield y.getGroupsPermissions(m.id);e.req.groups=E,e.req.permissions=_,e.next()}))(e)}))(i,r,n)},Ue=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.auth}),qe=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.groups)&&void 0!==r?r:[]).includes(t)}),Ye=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.groups)&&void 0!==i?i:[]}),$e=i(({ctx:e,key:t})=>{var i,r;return(null!==(r=null===(i=e.req)||void 0===i?void 0:i.permissions)&&void 0!==r?r:[]).includes(t)}),We=i(({ctx:e})=>{var t,i;return null!==(i=null===(t=e.req)||void 0===t?void 0:t.permissions)&&void 0!==i?i:[]}),Ge=i(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.user}),Ve=(e,t,i)=>{var n,s,o,d,a,l,u,c,p,v,g;const y=i.ctx instanceof r?i.ctx:null,h=null!==(n=null==y?void 0:y.id)&&void 0!==n?n:null,m=null!==(a=null!==(d=null===(o=null===(s=null==y?void 0:y.req)||void 0===s?void 0:s.user)||void 0===o?void 0:o.id)&&void 0!==d?d:i.user_id)&&void 0!==a?a:null,E={type:e,model:null!==(l=null==t?void 0:t.getTableName())&&void 0!==l?l:null,source:null!==(u=Env.BASE_NAME)&&void 0!==u?u:"",request_id:h,user_id:m};return y?Object.assign(Object.assign({},E),{full_url:null!==(c=y.getUrl())&&void 0!==c?c:"",ip_address:null!==(p=y.getIp())&&void 0!==p?p:"",user_agent:null!==(g=null===(v=y.req)||void 0===v?void 0:v.headers["user-agent"])&&void 0!==g?g:""}):E},ze=e=>{const t=M(e),i=t.primaryKeyAttribute;return{model:t,record_id:i?e.getDataValue(i):null}},Je={afterCreate:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e);yield ot.create(Object.assign(Object.assign({},Ve(De.CREATE,i,t)),{record:r,currently:e.toJSON()})).catch(b.catch)}),afterUpdate:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e),n={},s={},o=e.changed();o&&o.length&&o.forEach(t=>{n[t]=e.getDataValue(t),s[t]=e.previous(t)}),yield ot.create(Object.assign(Object.assign({},Ve(De.UPDATE,i,t)),{record:r,currently:n,previously:s})).catch(b.catch)}),afterDestroy:(e,t)=>be(void 0,void 0,void 0,function*(){const{model:i,record_id:r}=ze(e);yield ot.create(Object.assign(Object.assign({},Ve(De.DELETE,i,t)),{record:r,currently:e.toJSON()})).catch(b.catch)})},Qe=e=>(x(e)&&(e=Env.DATABASE_AUDIT),ee(e?Je:{}));let Xe=class RegisterModel extends oe{};Pe([te.Id(7),we("design:type",String)],Xe.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],Xe.prototype,"secret",void 0),Pe([te.FullDate(),we("design:type",Number)],Xe.prototype,"expired_at",void 0),Pe([te.Boolean(),we("design:type",Boolean)],Xe.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],Xe.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],Xe.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],Xe.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],Xe.prototype,"user_id",void 0),Xe=Pe([re(Re),ne("register"),se("5.2.0")],Xe);let Ze=class UserAuthModel extends oe{};Pe([te.Id(7),we("design:type",String)],Ze.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"secret",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"ip_address",void 0),Pe([te.String(),we("design:type",String)],Ze.prototype,"user_agent",void 0),Pe([te.FullDate(),we("design:type",Object)],Ze.prototype,"revoked_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],Ze.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],Ze.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],Ze.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],Ze.prototype,"user_id",void 0),Ze=Pe([re(Re),ne("users_auth"),se("5.2.0")],Ze);let et=class PermissionModel extends oe{};Pe([te.Id(7),we("design:type",String)],et.prototype,"id",void 0),Pe([te.String(),de(),we("design:type",String)],et.prototype,"name",void 0),Pe([te.Text(),we("design:type",String)],et.prototype,"description",void 0),Pe([te.Boolean(),we("design:type",Boolean)],et.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],et.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],et.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],et.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>tt),we("design:type",Array)],et.prototype,"groups_permissions",void 0),et=Pe([re(Re),ne("permission"),Qe(),se("5.2.1")],et);let tt=class GroupPermissionModel extends oe{};Pe([te.Id(7),we("design:type",String)],tt.prototype,"id",void 0),Pe([te.CreatedAt(),we("design:type",Date)],tt.prototype,"created_at",void 0),Pe([ie.BelongsTo(()=>it),we("design:type",String)],tt.prototype,"group_id",void 0),Pe([ie.BelongsTo(()=>et),we("design:type",String)],tt.prototype,"permission_id",void 0),tt=Pe([re(Re),ne("groups_permissions"),Qe(),se("5.2.0")],tt);let it=class GroupModel extends oe{};Pe([te.Id(7),we("design:type",String)],it.prototype,"id",void 0),Pe([te.String(),de(),we("design:type",String)],it.prototype,"name",void 0),Pe([te.Text(),we("design:type",String)],it.prototype,"description",void 0),Pe([te.Boolean(),we("design:type",Boolean)],it.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],it.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],it.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],it.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>rt),we("design:type",Array)],it.prototype,"users_groups",void 0),Pe([ie.HasMany(()=>tt),we("design:type",Array)],it.prototype,"groups_Permission",void 0),it=Pe([re(Re),ne("group"),Qe(),se("5.2.1")],it);let rt=class UserGroupModel extends oe{};Pe([te.Id(7),we("design:type",String)],rt.prototype,"id",void 0),Pe([te.CreatedAt(),we("design:type",Date)],rt.prototype,"created_at",void 0),Pe([ie.BelongsTo(()=>it),we("design:type",String)],rt.prototype,"group_id",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],rt.prototype,"user_id",void 0),rt=Pe([re(Re),ne("users_groups"),Qe(),se("5.2.0")],rt);let nt=class UserPasswordModel extends oe{};Pe([te.Id(7),we("design:type",String)],nt.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],nt.prototype,"hash",void 0),Pe([te.FullDate(),we("design:type",Object)],nt.prototype,"revoked_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],nt.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],nt.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],nt.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],nt.prototype,"user_id",void 0),nt=Pe([re(Re),ne("users_password"),Qe(),se("5.2.0")],nt);let st=class UserModel extends oe{};Pe([te.Id(7),we("design:type",String)],st.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"name",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"username",void 0),Pe([te.String(),we("design:type",String)],st.prototype,"email",void 0),Pe([te.Text(),we("design:type",String)],st.prototype,"notes",void 0),Pe([te.Enum(Le),ae(Le.ACTIVE),we("design:type",String)],st.prototype,"status",void 0),Pe([te.Json(),ae(()=>({})),we("design:type",Object)],st.prototype,"metadata",void 0),Pe([te.CreatedAt(),we("design:type",Date)],st.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],st.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],st.prototype,"deleted_at",void 0),Pe([ie.HasMany(()=>ot),we("design:type",Array)],st.prototype,"audits",void 0),Pe([ie.HasMany(()=>Ze),we("design:type",Array)],st.prototype,"users_auths",void 0),Pe([ie.HasMany(()=>Xe),we("design:type",Array)],st.prototype,"registers",void 0),Pe([ie.HasMany(()=>rt),we("design:type",Array)],st.prototype,"users_groups",void 0),Pe([ie.HasMany(()=>nt),we("design:type",Array)],st.prototype,"users_passwords",void 0),st=Pe([re(Re),ne("user"),Qe(),se("5.2.0")],st);let ot=class AuditModel extends oe{};Pe([te.Id(7),we("design:type",String)],ot.prototype,"id",void 0),Pe([te.Enum(De),we("design:type",String)],ot.prototype,"type",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"model",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"record",void 0),Pe([te.Json(),we("design:type",Object)],ot.prototype,"currently",void 0),Pe([te.Json(),we("design:type",Object)],ot.prototype,"previously",void 0),Pe([te.String(36),we("design:type",String)],ot.prototype,"request_id",void 0),Pe([te.Text(),we("design:type",String)],ot.prototype,"full_url",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"ip_address",void 0),Pe([te.Text(),we("design:type",String)],ot.prototype,"user_agent",void 0),Pe([te.String(),we("design:type",String)],ot.prototype,"source",void 0),Pe([te.FullDate(),we("design:type",Object)],ot.prototype,"reverted_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ot.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ot.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],ot.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],ot.prototype,"user_id",void 0),ot=Pe([re(Re),ne("audit"),se("5.2.0")],ot);let dt=class ConfigModel extends oe{};Pe([te.Id(7),we("design:type",String)],dt.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],dt.prototype,"key",void 0),Pe([te.Text(),we("design:type",String)],dt.prototype,"value",void 0),Pe([te.CreatedAt(),we("design:type",Date)],dt.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],dt.prototype,"updated_at",void 0),dt=Pe([re(Re),ne("configs"),se("5.2.0")],dt);let at=class ForgotModel extends oe{};Pe([te.Id(7),we("design:type",String)],at.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],at.prototype,"secret",void 0),Pe([te.FullDate(),we("design:type",Number)],at.prototype,"expired_at",void 0),Pe([te.Boolean(),we("design:type",Boolean)],at.prototype,"active",void 0),Pe([te.CreatedAt(),we("design:type",Date)],at.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],at.prototype,"updated_at",void 0),Pe([te.DeletedAt(),we("design:type",Object)],at.prototype,"deleted_at",void 0),Pe([ie.BelongsTo(()=>st),we("design:type",String)],at.prototype,"user_id",void 0),at=Pe([re(Re),ne("forgot"),se("5.2.0")],at);let lt=class LogModel extends oe{};Pe([te.Id(7),we("design:type",String)],lt.prototype,"id",void 0),Pe([te.Enum(xe),ae(xe.INFO),we("design:type",String)],lt.prototype,"level",void 0),Pe([te.Text(),we("design:type",String)],lt.prototype,"message",void 0),Pe([te.String(),we("design:type",String)],lt.prototype,"source",void 0),Pe([te.CreatedAt(),we("design:type",Date)],lt.prototype,"created_at",void 0),lt=Pe([re(Re),ne("log"),se("5.2.0")],lt);let ut=class MigrationModel extends oe{};Pe([te.Id(7),we("design:type",String)],ut.prototype,"id",void 0),Pe([te.String(),we("design:type",String)],ut.prototype,"model",void 0),Pe([te.String(),we("design:type",String)],ut.prototype,"version",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ut.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ut.prototype,"updated_at",void 0),ut=Pe([re(Re),ne("migration"),se("5.2.0")],ut);let ct=class SessionModel extends oe{};Pe([te.Id(7),we("design:type",String)],ct.prototype,"id",void 0),Pe([te.Json(),we("design:type",Object)],ct.prototype,"data",void 0),Pe([te.FullDate(),we("design:type",Date)],ct.prototype,"expired_at",void 0),Pe([te.CreatedAt(),we("design:type",Date)],ct.prototype,"created_at",void 0),Pe([te.UpdatedAt(),we("design:type",Date)],ct.prototype,"updated_at",void 0),ct=Pe([re(Re),ne("session"),se("5.2.0")],ct);class Log{static error(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("error",e,t,i)})}static info(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("info",e,t,i)})}static warn(e,t,i){return be(this,void 0,void 0,function*(){yield this.writeRaw("warn",e,t,i)})}static writeRaw(e,t,i,r){return be(this,void 0,void 0,function*(){var n;r&&b.console(null!==(n=this.colors[e])&&void 0!==n?n:C.White,e,t),Re&&(yield lt.create({level:e,message:t,source:null!=i?i:""}).catch(b.catch))})}}Log.colors={error:C.Red,info:C.Cyan,warn:C.Yellow};class Loggable{get log(){return e=>Loggable.logInfo(this,e)}static get log(){return e=>this.logInfo(this,e)}get error(){return e=>Loggable.logError(this,e)}static get error(){return e=>this.logError(this,e)}static logError(e,t){var i,r;Log.error(null!==(r=null!==(i=null==t?void 0:t.message)&&void 0!==i?i:t)&&void 0!==r?r:"",this.source(e),Env.CONSOLE_ERROR)}static logInfo(e,t){Log.info(null!=t?t:"",this.source(e),Env.CONSOLE_ERROR)}static source(e){var t,i,r;const n=null!==(r=null!==(i=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)&&void 0!==i?i:null==e?void 0:e.name)&&void 0!==r?r:"null";return Env.BASE_NAME?`${Env.BASE_NAME}.${n}`:n}}class Config extends Loggable{static all(e){return be(this,void 0,void 0,function*(){var t;const i=null!==(t=yield dt.findAll({where:(null==e?void 0:e.length)?{key:{[le.in]:e}}:{}}).catch(this.error))&&void 0!==t?t:[];return Object.fromEntries(i.map(e=>[e.key,e.value]))})}static del(e){return be(this,void 0,void 0,function*(){return((yield dt.destroy({where:{key:e}}).catch(this.error))||0)>0})}static get(e){return be(this,arguments,void 0,function*(e,t=""){const[i]=(yield dt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t){return be(this,void 0,void 0,function*(){const[i,r]=(yield dt.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];i&&!r&&(i.value=t,yield i.save().catch(this.error))})}}class SessionStore extends pe{constructor(){super(),this.all=e=>be(this,void 0,void 0,function*(){e=e||k;const t=yield ct.findAll({attributes:["id","expired_at"],where:{expired_at:{[le.gte]:new Date}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.id)),e()}),this.clear=e=>be(this,void 0,void 0,function*(){yield ct.destroy().catch(b.catch),e&&e()}),this.destroy=(e,t)=>be(this,void 0,void 0,function*(){yield ct.destroy({where:{id:e}}).catch(b.catch),t&&t()}),this.expired=()=>be(this,void 0,void 0,function*(){yield ct.destroy({where:{expired_at:{[le.lt]:new Date}}}).catch(b.catch)}),this.get=(e,t)=>be(this,void 0,void 0,function*(){t=t||k;const i=yield ct.findOne({where:{id:e,expired_at:{[le.gte]:new Date}}}).catch(e=>(t(e),null));if(i){if(i.data.cookie){if(new Date(i.data.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(b.catch),void t(null)}t(null,i.data)}else t(null)}),this.length=e=>be(this,void 0,void 0,function*(){e&&e(null,(yield ct.count().catch(b.catch))||0)}),this.set=(e,t,i)=>be(this,void 0,void 0,function*(){i=i||k;const r=new Date;r.setTime(r.getTime()+Env.API_SESSION_LIFETIME);const[n,s]=(yield ct.findOrCreate({where:{id:e},defaults:{id:e,data:t,expired_at:r}}).catch(b.catch))||[];n?(s||(n.data=t,n.expired_at=r,yield n.save().catch(b.catch)),i()):i()}),setInterval(this.expired,6e4)}}let pt=class Service{};pt=Pe([ve(Loggable)],pt);let vt=class AuthService extends pt{constructor(){super(...arguments),this.userAttributes={exclude:["username","notes","deleted_at"]}}create(e){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{id:t}=e,i=K(),r=yield Ze.create({secret:i,user_id:t}).catch(this.error);if(!r)throw new s;return{auth:r,token:ye.sign({id:t,secret:i},Env.TOKEN_KEY,this.options())}})}destroy(e){return be(this,void 0,void 0,function*(){return!(!e||e.revoked_at)&&(e.revoked_at=new Date,yield e.save(),!0)})}renew(e){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_KEY)throw new n("TOKEN_KEY not found");const{decode:i}=yield this.verify(e,Env.API_TOKEN_RENEW/1e3);if(!i)throw new t("Invalid token");const{id:r,secret:s}=i;if(r&&s){const e=yield st.findOne({where:{id:r,status:Le.ACTIVE}}).catch(this.error);if(e){const t=yield Ze.findOne({where:{secret:s,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at){t.secret=K(),yield t.save().catch(this.error);return{auth:t,token:ye.sign({id:r,secret:t.secret},Env.TOKEN_KEY,this.options())}}}}throw new t("Invalid token")})}user(e){return be(this,void 0,void 0,function*(){const{decode:i}=yield this.verify(e);if(!i)throw new t("Invalid token");const{id:r,secret:n}=i;if(r&&n){const e=yield st.findOne({attributes:this.userAttributes,where:{id:r,status:Le.ACTIVE}}).catch(this.error);if(e){const t=yield Ze.findOne({where:{secret:n,user_id:e.id}}).catch(this.error);if(t&&!t.revoked_at)return{auth:t,user:e}}}throw new t("Invalid token")})}options(){return{algorithm:"RS256",expiresIn:`${Env.TOKEN_TTL}ms`}}verify(e,i){return be(this,void 0,void 0,function*(){if(!Env.TOKEN_CRT)throw new n("TOKEN_CRT not found");if(!e||e.split(".").length<3)throw new t("Invalid token");try{return{decode:ye.verify(e,Env.TOKEN_CRT,{clockTolerance:i})}}catch(e){throw new t("Invalid token")}})}key(e){return be(this,void 0,void 0,function*(){if(!e)throw new t("Invalid token");const i=yield st.findOne({attributes:this.userAttributes,where:{token:e,status:Le.ACTIVE}}).catch(this.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Ze.findOrCreate({where:{secret:t,user_id:i.id},defaults:{secret:t,user_id:i.id}}).catch(this.error))||[];if(r)return r.revoked_at&&(r.revoked_at=null,yield r.save().catch(this.error)),{auth:r,user:i}}throw new t("Invalid token")})}};vt=Pe([ge()],vt);class ModelService extends pt{constructor(e,t){var i,r;super(),this.attributes=[],this.permissions=[],this.search=[],this.model=e,(null==t?void 0:t.permissions)&&(this.permissions=t.permissions);const n=Object.keys(e.getAttributes());this.attributes=this.filterAttributes(n,null!==(i=null==t?void 0:t.attributes)&&void 0!==i?i:[]),this.search=this.filterAttributes(n,null!==(r=null==t?void 0:t.search)&&void 0!==r?r:this.attributes)}applySelect(e,t,i){if(!t)return;const r=null==e?void 0:e.getQuery(i?`${i}_select`:"select"),n=t.attributes,s=e=>n.includes(e);t.attributes=[],j(r)&&r.length&&t.attributes.push(...r.split(/\s*,\s*/g).filter(s)),t.attributes.length||(t.attributes=n)}applyOrders(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("asc"),r=null==e?void 0:e.getQuery("desc"),n=[],s=t.attributes,o=e=>s.includes(e);j(i)&&i.length&&n.push(...i.split(/\s*,\s*/g).filter(o).map(e=>[e,"ASC"])),j(r)&&r.length&&n.push(...r.split(/\s*,\s*/g).filter(o).map(e=>[e,"DESC"])),n.length&&(t.order=n)}applyPagination(e,t){if(!t)return;const i=null==e?void 0:e.getQuery("limit"),r=null==e?void 0:e.getQuery("offset");x(t.limit)&&(t.limit=Env.MODEL_LIMIT,j(i)&&(t.limit=parseInt(i)||0),t.limit=B(t.limit,-1,Env.MODEL_LIMIT_MAX)),t.limit<0&&(t.limit=void 0),j(r)&&(t.offset=parseInt(r)||0,t.offset<0&&(t.offset=void 0))}applySearch(e,t){var i;if(!t)return;const r=null==e?void 0:e.getQuery("search");r&&j(r)&&(t.where=Object.assign(Object.assign({},null!==(i=t.where)&&void 0!==i?i:{}),{[le.or]:this.search.map(e=>({[e]:{[le.substring]:r}}))}))}applyWhere(e,t,i){var r,n;if(!t)return null;const s=null==e?void 0:e.getQuery(i?`${i}_where`:"where");if(!j(s))return null;const d=t.attributes,a=ue.parse(d,s);return x(a.error)?(t.where=Object.assign(Object.assign({},null!==(r=t.where)&&void 0!==r?r:{}),null!==(n=a.value)&&void 0!==n?n:{}),null):new o(a.error.join(", "))}countAll(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,options:n={}}=e,s=F({},n);s.attributes=this.getAttributes(null!==(t=null==s?void 0:s.attributes)&&void 0!==t?t:[]),this.applySearch(r,s);const o=this.applyWhere(r,s);if(o)return null==r||r.error(o),0;this.applySelect(r,s);const a=null!==(i=yield this.model.count(Object.assign(Object.assign({},s),{distinct:!!s.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error))&&void 0!==i?i:0;return null==r||r.prepare(d.OK,{count:a}),a})}create(e){return be(this,void 0,void 0,function*(){var t,i;const{body:r={},ctx:n,options:o={}}=e,a=F({},o),l=yield this.model.create(Object.assign({},F({},null!==(i=null===(t=null==n?void 0:n.req)||void 0===t?void 0:t.body)&&void 0!==i?i:{},r)),Object.assign(Object.assign({},a),{ctx:n})).catch(this.error);if(!l)return null==n||n.error(new s),null;const{primaryKeyAttribute:u}=this.model;return null==n||n.prepare(d.OK,{[u]:l.getDataValue(u)}),l})}delete(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,id:s,options:o={}}=e,{primaryKeyAttribute:d}=this.model,l=null!==(t=null==r?void 0:r.getParam(d))&&void 0!==t?t:s;if(x(l))return null==r||r.error(new a),0;const u=F({},o),c=yield this.model.destroy(Object.assign(Object.assign(Object.assign({},u),{where:{[le.and]:Object.assign({[d]:l},null!==(i=null==u?void 0:u.where)&&void 0!==i?i:{})},individualHooks:!0}),{ctx:r})).catch(this.error);return c?(null==r||r.success("OK"),c):(null==r||r.error(new n),0)})}filterAttributes(e,t){if(H(t))return t.length?t.filter(t=>j(t)&&e.includes(t)):e;const{exclude:i,include:r}=t,n=x(r)?e:r.filter(t=>j(t)&&e.includes(t)),s=null!=i?i:[];return s.length?n.filter(e=>!s.includes(e)):n}findAll(e){return be(this,void 0,void 0,function*(){var t,i;const{ctx:r,callback:n,options:s={},query:o=!0}=e,a=F({},s);if(a.attributes=this.getAttributes(null!==(t=null==a?void 0:a.attributes)&&void 0!==t?t:[]),o&&this.applySelect(r,a),this.applyOrders(r,a),this.applyPagination(r,a),(null!==(i=null==a?void 0:a.limit)&&void 0!==i?i:0)>Env.MODEL_LIMIT_MAX&&(a.limit=Env.MODEL_LIMIT_MAX),this.applySearch(r,a),o){const e=this.applyWhere(r,a);if(e)return null==r||r.error(e),{count:0,records:[]}}const[l,u]=yield Promise.all([this.model.count(Object.assign(Object.assign({},a),{distinct:!!a.include,col:this.attributes.length?this.attributes[0]:void 0})).catch(this.error).then(e=>null!=e?e:0),this.model.findAll(a).catch(this.error).then(e=>null!=e?e:[])]),c={count:l,records:n?yield n(u):u};return null==r||r.prepare(d.OK,c),c})}findOne(e){return be(this,void 0,void 0,function*(){var t,i,r;const{callback:s,ctx:o,id:l,options:u={},query:c=!0}=e,{primaryKeyAttribute:p}=this.model,v=null!==(t=null==o?void 0:o.getParam(p))&&void 0!==t?t:l;if(x(v))return null==o||o.error(new a),null;const g=F({},u);g.attributes=this.getAttributes(null!==(i=null==g?void 0:g.attributes)&&void 0!==i?i:[]),c&&this.applySelect(o,g);const y=yield this.model.findOne(Object.assign(Object.assign({},g),{where:{[le.and]:Object.assign({[p]:v},null!==(r=null==g?void 0:g.where)&&void 0!==r?r:{})}})).catch(this.error);return y?(null==o||o.prepare(d.OK,s?yield s(y):y.toJSON()),y):(null==o||o.error(new n),null)})}getAttributes(e){return this.filterAttributes(this.attributes,e)}include(e,t){var i;const r=U(t),{ctx:n}=null!=t?t:{};r.attributes=this.filterAttributes(Object.keys(e.getAttributes()),null!==(i=r.attributes)&&void 0!==i?i:[]),this.applySearch(n,r);const s=this.applyWhere(n,r,t.name);return s?(null==n||n.error(s),null):(this.applySelect(n,r,t.name),Object.assign({model:e},r))}name(){return this.model.tableName}sync(){return be(this,void 0,void 0,function*(){if(!this.permissions.length)return;const e=this.name().toLowerCase(),t={description:"",active:!0};yield q(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=Y(e.replace(/_/g," ")," ");yield et.findOrCreate({where:{key:r},defaults:Object.assign({name:`${n} ${Y(i," ")}`,key:r,tags:n},t)})}))})}update(e){return be(this,void 0,void 0,function*(){var t,i,r,n,s;const{ctx:o,body:d,id:l,options:u={}}=e,{primaryKeyAttribute:c}=this.model,p=null!==(t=null==o?void 0:o.getParam(c))&&void 0!==t?t:l;if(x(p))return null==o||o.error(new a),!1;const v=F({},u),[g]=null!==(s=yield this.model.update(Object.assign({},F({},null!==(r=null===(i=null==o?void 0:o.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{},null!=d?d:{})),Object.assign(Object.assign(Object.assign({},v),{where:{[le.and]:Object.assign({[c]:p},null!==(n=null==v?void 0:v.where)&&void 0!==n?n:{})},individualHooks:!0}),{ctx:o})).catch(this.error))&&void 0!==s?s:[];return g?(null==o||o.success("OK"),!0):(null==o||o.success("Record not changed"),!1)})}}let gt=class UserService extends pt{constructor(){super(...arguments),this.hashOptions={algorithm:Env.PASSWORD_ALGORITHM,memoryCost:Env.PASSWORD_MEMORY_COST,parallelism:Env.PASSWORD_PARALLELISM,timeCost:Env.PASSWORD_TIME_COST}}createPassword(e,t,i){return be(this,void 0,void 0,function*(){yield nt.update({revoked_at:new Date},{where:{revoked_at:null,user_id:e}}).catch(this.error);const r=he(t+Env.PASSWORD_PEPPER,this.hashOptions);yield nt.create({hash:r,user_id:e},Object.assign({},{ctx:i})).catch(this.error)})}findAllPermission(e){return be(this,void 0,void 0,function*(){var t;return null!==(t=yield et.findAll({attributes:["name"],where:{active:!0},include:[{association:"groups_permissions",required:!0,include:[{association:"group",required:!0,attributes:["id","name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}]}]}).catch(this.error))&&void 0!==t?t:[]})}getGroups(e){return be(this,void 0,void 0,function*(){var t;return(null!==(t=yield it.findAll({attributes:["name"],where:{active:!0},include:[{association:"users_groups",required:!0,where:{user_id:e}}]}).catch(this.error))&&void 0!==t?t:[]).map(e=>e.name)})}getGroupsPermissions(e){return be(this,void 0,void 0,function*(){const t=[],i=[];return(yield this.findAllPermission(e)).forEach(e=>{i.push(e.name),e.groups_permissions.forEach(e=>t.push(e.group.name))}),{groups:$(t),permissions:$(i)}})}getPermissions(e){return be(this,void 0,void 0,function*(){return(yield this.findAllPermission(e)).map(e=>e.name)})}};gt=Pe([ge()],gt);class Application extends l{constructor(e,t){super(e,F({},{cross:!!Env.HTTP_CROSS&&("*"===Env.HTTP_CROSS||{origin:Env.HTTP_CROSS.split(",")}),hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new SessionStore,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:K},tls:{ca:Env.HTTP_TLS_CA,cert:Env.HTTP_TLS_CRT,key:Env.HTTP_TLS_KEY}},null!=t?t:{})),this.hash=new R(Env.API_KEY_HASH)}error(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.error(e.message,t,Env.CONSOLE_ERROR)}log(e,t){Env.BASE_NAME&&(t=t?`${Env.BASE_NAME}.${t}`:Env.BASE_NAME),Log.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return be(this,void 0,void 0,function*(){yield Re.sync(),yield this.migrations(Re),yield W(this.controllers,e=>be(this,void 0,void 0,function*(){L(e.sync)&&(yield e.sync(this))})),this.authService=new vt,this.userService=new gt,yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new X({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>be(this,void 0,void 0,function*(){t.url||(t.url=""),e.on("close",()=>{}),yield G(2e3)})))})}migrations(e){return be(this,void 0,void 0,function*(){const t=[];yield W(Object.keys(e.models),i=>be(this,void 0,void 0,function*(){var r;const n=e.models[i],s=n.version();if(!s)return;const[o,d]=null!==(r=yield ut.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=s)&&(o.version=s,yield o.save().catch(this.error),t.push(n))})),yield W(t,e=>be(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}let yt=class BaseController extends V{constructor(){super(...arguments),this.permissions=[]}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}session(e,t,i){return be(this,void 0,void 0,function*(){i.auth&&i.user&&(i.user_agent?i.user_agent!=t&&i.regenerate(k):(i.user_agent=t,i.save(k))),e.next()})}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})}))})}};Pe([Ie(0,u()),Ie(1,c("user-agent")),Ie(2,p()),we("design:type",Function),we("design:paramtypes",[r,String,Object]),we("design:returntype",Promise)],yt.prototype,"session",null),yt=Pe([ve(Loggable)],yt);let ht=class ModelController extends yt{constructor(){super(...arguments),this.attributes=[],this.permissions=["create","read","update","delete"],this.search=[]}countAll(e){return be(this,void 0,void 0,function*(){return yield this.service.countAll(e)})}create(e){return be(this,void 0,void 0,function*(){return yield this.service.create(e)})}delete(e){return be(this,void 0,void 0,function*(){return yield this.service.delete(e)})}findAll(e){return be(this,void 0,void 0,function*(){return yield this.service.findAll(e)})}findOne(e){return be(this,void 0,void 0,function*(){return yield this.service.findOne(e)})}include(e,t){return this.service.include(e,t)}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})})),this.service=new ModelService(this.model,{attributes:this.attributes.length?this.attributes:void 0,search:this.search.length?this.search:void 0})})}update(e){return be(this,void 0,void 0,function*(){return yield this.service.update(e)})}name(){return this.model.tableName}};ht=Pe([v(yt)],ht);let mt=class AuditsController extends ht{constructor(){super(...arguments),this.model=ot,this.permissions=["read"]}all(e,t,i){return be(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["currently","previously"]},where:r,order:[["created_at","DESC"]]}})})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Pe([g(),He(),Ke(),Ie(0,u()),Ie(1,y("type")),Ie(2,y("table")),we("design:type",Function),we("design:paramtypes",[r,String,String]),we("design:returntype",Promise)],mt.prototype,"all",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],mt.prototype,"get",null),mt=Pe([h("/audits"),v(ht)],mt);let Et=class AuthController extends yt{constructor(){super(...arguments),this.authService=new vt}login(e,i,r,n,s,o){return be(this,void 0,void 0,function*(){var d;yield G(Env.SLEEP_AUTH);const a=yield st.findOne({where:{[le.or]:[{email:r},{username:r}]}}).catch(this.error);if(!a)return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield nt.findOne({where:{revoked_at:null,user_id:a.id}}).catch(this.error);if(n+=Env.PASSWORD_PEPPER,!l||!(yield me(l.hash,n).catch(k)))return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield Xe.findOne({where:{active:!0,user_id:a.id}}).catch(this.error);if(u)return e.error(new t("Activation Required")),o.emit("auth.activation",{ctx:e,register:u,user:a}),void this.emit("auth.activation",{ctx:e,register:u,user:a});if(a.status!=Le.ACTIVE)return e.error(new t("Invalid credentials")),o.emit("auth.failure",{ctx:e,user:a}),void this.emit("auth.failure",{ctx:e,user:a});const{auth:c,token:p}=null!==(d=yield this.authService.create(a).catch(t=>{e.error(t),o.emit("auth.failure",{ctx:e}),this.emit("auth.failure",{ctx:e})}))&&void 0!==d?d:{};c&&p&&(c.user_agent=i,c.ip_address=e.getIp(),yield c.save().catch(this.error),Env.API_TOKEN_COOKIE_SET&&e.setCookie(Env.API_TOKEN_COOKIE,p,{maxAge:s?Env.TOKEN_TTL:void 0}),e.json({token:p}),o.emit("auth.login",{ctx:e,auth:c,user:a}),this.emit("auth.login",{ctx:e,auth:c,user:a}))})}logout(e,i,r,n){return be(this,void 0,void 0,function*(){if(yield this.authService.destroy(i))return Env.API_TOKEN_COOKIE_SET&&e.clearCookie(Env.API_TOKEN_COOKIE),e.success("OK"),n.emit("auth.logout",{auth:i,ctx:e,user:r}),void this.emit("auth.logout",{auth:i,ctx:e,user:r});e.error(new t("Access Denied"))})}renew(e,t,i,r){return be(this,void 0,void 0,function*(){var n;const{auth:s,token:o}=null!==(n=yield this.authService.renew(i).catch(t=>{e.error(t)}))&&void 0!==n?n:{};s&&o&&(s.user_agent=t,yield s.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:s,ctx:e}),this.emit("auth.renew",{auth:s,ctx:e}))})}user(e,t){return be(this,void 0,void 0,function*(){const{groups:i,permissions:r,profile:n}=e.req;if(!i||!r)return e.error(new s);e.json(Object.assign(Object.assign({},t.toJSON()),{groups:i,permissions:r,profile:n}))})}};Pe([m("/login"),E(e=>({username:e.string().min(3).required(),password:e.string().min(5).required(),remember:e.boolean().parse().empty(!1)})),Ie(0,u()),Ie(1,c("user-agent")),Ie(2,_("username")),Ie(3,_("password")),Ie(4,_("remember")),Ie(5,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,String,Boolean,Application]),we("design:returntype",Promise)],Et.prototype,"login",null),Pe([g("/logout"),He(),Ie(0,u()),Ie(1,Ue()),Ie(2,Ge()),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,Ze,st,Application]),we("design:returntype",Promise)],Et.prototype,"logout",null),Pe([m("/renew"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,c("user-agent")),Ie(2,_("token")),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,Application]),we("design:returntype",Promise)],Et.prototype,"renew",null),Pe([g(),g("/me"),He(),Ie(0,u()),Ie(1,Ge()),we("design:type",Function),we("design:paramtypes",[r,st]),we("design:returntype",Promise)],Et.prototype,"user",null),Et=Pe([h("/auth"),v(yt)],Et);let _t=class CrudController extends ht{constructor(){super(...arguments),this._crud={}}CrudArgumentsCountAll(e){return{ctx:e}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidateCreate(){return this._crud}CrudValidateUpdate(){return this._crud}add(e){return be(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return be(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}rows(e){return be(this,void 0,void 0,function*(){yield this.countAll(this.CrudArgumentsCountAll(e))})}del(e){return be(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return be(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validate(e,t){return be(this,void 0,void 0,function*(){var i,r;const n=z.object(t).parse(),{error:s,message:d,value:a}=yield n.validateAsync(null!==(r=null===(i=e.req)||void 0===i?void 0:i.body)&&void 0!==r?r:{});if(s)return e.error(new o(null!=d?d:s));e.req.body=a,e.next()})}validateCreate(e){return be(this,void 0,void 0,function*(){const t=this.CrudValidateCreate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}validateUpdate(e){return be(this,void 0,void 0,function*(){const t=this.CrudValidateUpdate();if(t==this._crud)return e.error(new s);yield this.validate(e,t)})}};Pe([m(),He(),Me(),A("validateCreate"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"add",null),Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"all",null),Pe([g("/count"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"rows",null),Pe([S("/:id"),He(),ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"del",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"get",null),Pe([O("/:id"),He(),je(),A("validateUpdate"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"set",null),Pe([Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"validateCreate",null),Pe([Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],_t.prototype,"validateUpdate",null),_t=Pe([v(ht)],_t);let ft=class FilesController extends yt{constructor(){super(...arguments),this.directory=Env.API_HTTP_PUBLIC||"./",this.permissions=["delete","download","edit","list","read","rename","upload","write"]}files(e){return be(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Te(this.directory,t);if(!Ee(i)||!_e(i).isDirectory())return e.error(new n);let r;return r=fe(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(J),Object.assign(Object.assign({},this.info(i)),{files:r})})}info(e){if(!Ee(e))return null;const t=_e(e),i=e.split("/").pop();e=e.replace(this.directory,"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return be(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=Y(e.replace(/_/g," ")," ");yield W(this.permissions,i=>be(this,void 0,void 0,function*(){const r=`${e}.${i}`;yield et.findOrCreate({where:{name:r},defaults:{name:r,description:`${t} ${Y(i," ")}`,active:!0}})}))})}};Pe([g("/path"),g("/path/*path"),He(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],ft.prototype,"files",null),ft=Pe([h("/files"),v(yt)],ft);let At=class ForgotController extends yt{check(e,t){return be(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.error(new n);i.secret=Q(),yield i.save(),e.json({token:i.secret})})}forgot(e,t,i){return be(this,void 0,void 0,function*(){yield G(Env.SLEEP_FORGOT);const r=t,s=yield st.findOne({where:{[le.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.error(new n);const o=Q(),d=Date.now()+6e4*Env.API_TOKEN_FORGOT,a=yield at.create({token:o,timestamp:d,active:!0,user_id:s.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:a,user:s}),this.emit("forgot.send",{ctx:e,forgot:a,user:s})})}reset(e,t,i,r){return be(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i)return e.error(new n);i.active=!1,yield i.save().catch(this.error),yield i.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})})}find(e){return be(this,void 0,void 0,function*(){return yield at.findOne({where:{token:e,active:!0},include:[{association:"users",required:!0}]}).catch(this.error)})}};Pe([g("/check"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,_("token")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],At.prototype,"check",null),Pe([m(),E(e=>({username:e.string().min(4).required()})),Ie(0,u()),Ie(1,_("username")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],At.prototype,"forgot",null),Pe([m("/reset"),E(e=>({token:e.string().required(),password:e.string().min(5).required()})),Ie(0,u()),Ie(1,_("token")),Ie(2,_("password")),Ie(3,f()),we("design:type",Function),we("design:paramtypes",[r,String,String,Application]),we("design:returntype",Promise)],At.prototype,"reset",null),At=Pe([h("/forgot"),v(yt)],At);let St=class GroupsController extends _t{constructor(){super(...arguments),this.model=it,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),active:z.boolean().parse().required()},this.schemaUpdate={description:z.string().empty(),active:z.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};St=Pe([h("/groups"),v(_t)],St);let Ot=class GroupsPermissionsController extends ht{constructor(){super(...arguments),this.model=tt,this.permissions=[]}all(e,t){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{association:"permission"}]},callback:e=>e.map(e=>e.permission),query:!1})})}set(e,t,i){return be(this,void 0,void 0,function*(){const r=yield it.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n);const s=r.id,o=[];yield W($(i),t=>be(this,void 0,void 0,function*(){var i;if(!(yield et.count({where:{id:t}})))return;const[r]=null!==(i=yield tt.findOrCreate(Object.assign({where:{group_id:s,permission_id:t},defaults:{group_id:s,permission_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&o.push(t)})),yield tt.destroy(Object.assign({where:{group_id:s,permission_id:{[le.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/permissions"),He(),Ke("groups"),Ie(0,u()),Ie(1,T("id")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],Ot.prototype,"all",null),Pe([O("/:id/permissions"),He(),je("groups"),E(e=>({permissions:e.array(e.string())})),Ie(0,u()),Ie(1,T("id")),Ie(2,_("permissions")),we("design:type",Function),we("design:paramtypes",[r,String,Array]),we("design:returntype",Promise)],Ot.prototype,"set",null),Ot=Pe([h("/groups"),v(ht)],Ot);let Tt=class HealthController{ping(e){return be(this,void 0,void 0,function*(){e.json({status:"ok",timestamp:Date.now(),uptime:process.uptime()})})}};Pe([P("/"),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Tt.prototype,"ping",null),Tt=Pe([h("/health")],Tt);let Pt=class LogsController extends ht{constructor(){super(...arguments),this.model=lt,this.permissions=["read"]}all(e){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{order:[["created_at","DESC"]]}})})}};Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Pt.prototype,"all",null),Pt=Pe([h("/logs"),v(ht)],Pt);let It=class PermissionsController extends _t{constructor(){super(...arguments),this.model=et,this.schemaCreate={name:z.string().required(),description:z.string().empty(""),active:z.boolean().parse().required()},this.schemaUpdate={description:z.string().empty(),active:z.boolean().parse().empty()}}CrudValidateCreate(){return this.schemaCreate}CrudValidateUpdate(){return this.schemaUpdate}};It=Pe([h("/permissions"),v(_t)],It);let wt=class RegisterController extends yt{register(e,t,i){return be(this,void 0,void 0,function*(){yield G(Env.SLEEP_REGISTRY);const{name:r,date:n,email:o,username:d,password:a,confirm:l}=t,u=d||o,c=D(a);if(yield st.count({where:{[le.or]:[{email:o},{username:u}]}}).catch(this.error))return e.error("INVALID EMAIL OR USERNAME");if(c!=D(l))return e.error("INVALID PASSWORD");const p=yield st.create({name:r,email:o,username:u,password:c,avatar:"",date:n,description:"",status:Le.PENDING}).catch(this.error);if(!p)return e.error(new s);const v=yield Xe.create({token:yield this.getId(),active:!0,user_id:p.id}).catch(this.error);if(!v)return yield p.destroy().catch(this.error),e.error(new s);e.success("OK"),i.emit("register.user",{ctx:e,register:v,user:p}),this.emit("register.user",{ctx:e,register:v,user:p})})}confirm(e,t,i){return be(this,void 0,void 0,function*(){const r=yield Xe.findOne({where:{token:t,active:!0},include:[{association:"users",required:!0}]}).catch(this.error);if(!r)return e.error(new n);r.active=!1,yield r.save().catch(this.error),r.user.status=Le.ACTIVE,yield r.user.save().catch(this.error),e.success("OK"),i.emit("register.confirm",{ctx:e,register:r,user:r.user}),this.emit("register.confirm",{ctx:e,register:r,user:r.user})})}send(e,t,i){return be(this,void 0,void 0,function*(){const r=t,s=yield Xe.findOne({where:{active:!0},include:[{model:st,required:!0,where:{[le.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!s)return e.error(new n);e.success("OK"),i.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})})}getId(){return be(this,void 0,void 0,function*(){const e=K();return(yield Xe.count({where:{token:e}}))?this.getId():e})}};Pe([m(),E(e=>({name:e.string().required(),date:e.date().required(),email:e.string().email().required(),username:e.string().min(4).empty(),password:e.string().min(5).required(),confirm:e.string().min(5).required()})),Ie(0,u()),Ie(1,_()),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,Object,Application]),we("design:returntype",Promise)],wt.prototype,"register",null),Pe([m("/confirm"),E(e=>({token:e.string().required()})),Ie(0,u()),Ie(1,_("token")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],wt.prototype,"confirm",null),Pe([m("/send"),E(e=>({username:e.string().min(4).required()})),Ie(0,u()),Ie(1,_("username")),Ie(2,f()),we("design:type",Function),we("design:paramtypes",[r,String,Application]),we("design:returntype",Promise)],wt.prototype,"send",null),wt=Pe([h("/register"),v(yt)],wt);let bt=class SetupController extends yt{constructor(){super(...arguments),this.userService=new gt}setup(e){return be(this,void 0,void 0,function*(){var t;if(yield st.count())return e.error(new n("Endpoint Not Found"));const i=yield st.create({name:"Admin",username:"admin",email:"admin@localhost.com",notes:"",status:Le.ACTIVE},Object.assign({},{ctx:e})).catch(this.error);if(!i)return e.error(new s);yield this.userService.createPassword(i.id,"admin",e);const r=yield it.create({name:"root",description:"Root",active:!0},Object.assign({},{ctx:e}));yield rt.create({user_id:i.id,group_id:r.id},Object.assign({},{ctx:e})),yield it.create({name:"admin",description:"Admin",active:!0},Object.assign({},{ctx:e})),yield it.create({name:"user",description:"User",active:!0},Object.assign({},{ctx:e}));const o=null!==(t=yield et.findAll({where:{active:!0}}).catch(this.error))&&void 0!==t?t:[];yield W(o,t=>be(this,void 0,void 0,function*(){yield tt.create({group_id:r.id,permission_id:t.id},Object.assign({},{ctx:e}))})),e.success("OK")})}};Pe([g(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],bt.prototype,"setup",null),bt=Pe([h("/setup"),v(yt)],bt);let Ct=class UsersController extends ht{constructor(){super(),this.model=st,this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&Ee(Env.API_HTTP_PUBLIC)&&!Ee(this.path)&&Ae(this.path)}avatar(e,t){return be(this,void 0,void 0,function*(){var i;const r=e.getFiles();if(r.file&&r.file.length){const{filename:n,path:o}=null!==(i=r.file[0])&&void 0!==i?i:{};if(n){const i=yield st.findOne({where:{user_id:t.id}}).catch(this.error);if(!i)return Se(o).isFile()&&Oe(o),e.error(new s);const r=this.path+"/"+i.metadata.avatar_url;if(Ee(r)&&Se(r).isFile()&&Oe(r),i.changed("metadata",!0),i.metadata.avatar_url=n,yield i.save(Object.assign({},{ctx:e})).catch(this.error))return e.success("OK")}}e.success("Record not Changed")})}token_new(){return be(this,void 0,void 0,function*(){var e;const t=K();return(null!==(e=yield this.model.count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e){return be(this,void 0,void 0,function*(){yield this.create({ctx:e})})}all(e){return be(this,void 0,void 0,function*(){yield this.findAll({ctx:e})})}rows(e){return be(this,void 0,void 0,function*(){yield this.countAll({ctx:e})})}del(e,t,i){return be(this,void 0,void 0,function*(){if(i.id==t)return e.error(new n);yield this.delete({ctx:e})})}get(e){return be(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e){return be(this,void 0,void 0,function*(){yield this.update({ctx:e})})}};Pe([m("/avatar"),He(),I({file:{count:1,path:`${Env.API_HTTP_PUBLIC}/avatar`,types:["image/bmp","image/jpeg","image/png"],size:32}}),Ie(0,u()),Ie(1,Ge()),we("design:type",Function),we("design:paramtypes",[r,st]),we("design:returntype",Promise)],Ct.prototype,"avatar",null),Pe([m(),He(),Me(),E(e=>({name:e.string().required(),email:e.string().email().required(),username:e.string().min(3).required(),description:e.string().empty(""),state:e.boolean().parse().empty(!0)})),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"add",null),Pe([g(),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"all",null),Pe([g("/count"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"rows",null),Pe([S("/:id"),He(),ke(),Ie(0,u()),Ie(1,T("id")),Ie(2,Ge()),we("design:type",Function),we("design:paramtypes",[r,String,st]),we("design:returntype",Promise)],Ct.prototype,"del",null),Pe([g("/:id"),He(),Ke(),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"get",null),Pe([O("/:id"),He(),je(),E(e=>({name:e.string().empty(),email:e.string().email().empty(),username:e.string().min(3).empty(),description:e.string().empty(),state:e.boolean().parse().empty()})),Ie(0,u()),we("design:type",Function),we("design:paramtypes",[r]),we("design:returntype",Promise)],Ct.prototype,"set",null),Ct=Pe([h("/users"),v(ht),we("design:paramtypes",[])],Ct);let Rt=class UsersGroupsController extends ht{constructor(){super(...arguments),this.model=rt,this.permissions=[]}all(e,t){return be(this,void 0,void 0,function*(){if(!(yield st.findByPk(t,{attributes:["id"]}).catch(this.error)))return e.error(new n("User Not Found"));yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{association:"group"}]},callback:e=>e.map(e=>e.group),query:!1})})}set(e,t,i){return be(this,void 0,void 0,function*(){const r=yield st.findByPk(t,{attributes:["id"]}).catch(this.error);if(!r)return e.error(new n("User Not Found"));const s=r.id,o=[];yield W($(i),t=>be(this,void 0,void 0,function*(){var i;if(!(yield it.count({where:{id:t}})))return;const[r]=null!==(i=yield rt.findOrCreate(Object.assign({where:{user_id:s,group_id:t},defaults:{user_id:s,group_id:t}},{ctx:e})).catch(this.error))&&void 0!==i?i:[];r&&o.push(t)})),yield rt.destroy(Object.assign({where:{user_id:s,group_id:{[le.notIn]:o}},individualHooks:!0},{ctx:e})).catch(this.error),e.success("OK")})}};Pe([g("/:id/groups"),He(),Ke("users"),Ie(0,u()),Ie(1,T("id")),we("design:type",Function),we("design:paramtypes",[r,String]),we("design:returntype",Promise)],Rt.prototype,"all",null),Pe([O("/:id/groups"),He(),je("users"),E(e=>({groups:e.array(e.string())})),Ie(0,u()),Ie(1,T("id")),Ie(2,_("groups")),we("design:type",Function),we("design:paramtypes",[r,String,Array]),we("design:returntype",Promise)],Rt.prototype,"set",null),Rt=Pe([h("/users"),v(ht)],Rt);export{Application,Qe as Audit,ot as AuditModel,De as AuditTypes,mt as AuditsController,Et as AuthController,vt as AuthService,yt as BaseController,Me as CanCreate,ke as CanDelete,Ke as CanRead,je as CanUpdate,Config,dt as ConfigModel,_t as CrudController,Env,ft as FilesController,At as ForgotController,at as ForgotModel,it as GroupModel,tt as GroupPermissionModel,St as GroupsController,Ot as GroupsPermissionsController,Be as HasGroups,Fe as HasPermissions,Tt as HealthController,He as IsAuthenticated,Log,lt as LogModel,Loggable,xe as Loglevels,Pt as LogsController,ut as MigrationModel,ht as ModelController,ModelService,et as PermissionModel,It as PermissionsController,wt as RegisterController,Xe as RegisterModel,Ue as ReqAuth,qe as ReqGroup,Ye as ReqGroups,$e as ReqPermission,We as ReqPermissions,Ge as ReqUser,pt as Service,ct as SessionModel,SessionStore,bt as SetupController,Ze as UserAuthModel,rt as UserGroupModel,st as UserModel,nt as UserPasswordModel,gt as UserService,Le as UserStatus,Ct as UsersController,Rt as UsersGroupsController,Ne as canFactory,Re as sequelize};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrewcaires/api",
3
- "version": "5.2.1",
3
+ "version": "5.2.2",
4
4
  "description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs.js",
@@ -51,7 +51,7 @@
51
51
  "@andrewcaires/express": "^2.3.0",
52
52
  "@andrewcaires/node": "^1.3.3",
53
53
  "@andrewcaires/sequelize": "^3.2.1",
54
- "@andrewcaires/utils.js": "^0.4.36",
54
+ "@andrewcaires/utils.js": "^0.4.37",
55
55
  "@node-rs/argon2": "^2.0.2",
56
56
  "cors": "^2.8.6",
57
57
  "dotenv": "^17.4.2",
@@ -69,13 +69,13 @@
69
69
  "@types/cors": "^2.8.19",
70
70
  "@types/express-session": "^1.19.0",
71
71
  "@types/jsonwebtoken": "^9.0.10",
72
- "@types/node": "^25.6.2",
72
+ "@types/node": "^25.7.0",
73
73
  "@types/ws": "^8.18.1",
74
74
  "eslint": "^10.3.0",
75
75
  "mariadb": "^3.5.2",
76
76
  "rollup": "^4.60.3",
77
77
  "rollup-plugin-dts": "^6.4.1",
78
78
  "tslib": "^2.8.1",
79
- "typescript-eslint": "^8.59.2"
79
+ "typescript-eslint": "^8.59.3"
80
80
  }
81
81
  }