insite-users-server 2.0.101 → 2.1.0

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.js CHANGED
@@ -1,4 +1,4 @@
1
- function x(o){if(o instanceof Set){let e=[];for(let t of o)e.push(t._id);return e}return o.map(e=>e._id)}function ce(o,...e){let t=0;for(let s of e)o.includes(s)||(o.push(s),t++);return t}function E(o,e,t){if(o&&e){if(e.includes(".")){let s=e.split("."),i=o;for(let r=0;r<s.length-1;r++){let n=s[r],l=i[n];i=l&&typeof l=="object"?l:i[n]={}}return i[s.at(-1)]=t}return o[e]=t}return null}function pe(o,...e){for(let t of e)for(let s in t)Object.hasOwn(t,s)&&E(o,s,t[s]);return o}function _(){}function m(o,e=0,t={}){let{leading:s=!1,trailing:i=!0}=t,{maxWait:r=1/0}=t,n,l,a,p,g,y,d,O,ae=async()=>{let v=Date.now();v>=a?(n=void 0,a=void 0,clearTimeout(l),typeof d=="function"&&await d(),b.resolve(O),b.promise.isResolved=!0,y=s):(clearTimeout(n),n=setTimeout(ae,a-v))},J=Number.isFinite(r)?()=>{d===S&&(d=!1),S(),l=setTimeout(J,r)}:null;async function S(){return O=await o.apply(p,g)}s&&typeof s=="boolean"&&(s=S),y=s,i&&typeof i=="boolean"&&(i=S),d=i;let b=Object.assign(function(...v){return g=v,p=this,a=Date.now()+e,d=i,b.promise.isResolved&&(b.promise=Object.assign(new Promise(ve=>{b.resolve=ve,typeof y=="function"&&(y(),y=!1,d===S&&(d=!1)),n||(n=setTimeout(ae,e),J&&(l=setTimeout(J,r)))}),{isResolved:!1})),b.promise},{callback:o,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:S,clear:async v=>{clearTimeout(n),n=void 0,clearTimeout(l),b.promise.isResolved=!0,b.resolve(v?await S():O)}});return b}m.noop=Object.assign(()=>{},{callback:_,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:_,clear:_});function de(o,e){if(o&&e){if(e.includes(".")){let t=e.split("."),s=o;for(let r=0;r<t.length-1;r++){let n=t[r],l=s[n];if(l&&typeof l=="object")s=l;else return!1}let i=t.at(-1);return i in s&&delete s[i]}return e in o&&delete o[e]}return!1}function u(o,e){if(o){for(let t of e)delete o[t];return o}return null}function k(o){for(let e in o)delete o[e];return o}var q=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var I=class extends Set{constructor(){super()}add(){return this}};var A=class extends Error{constructor(e,t=null,s){super(e),t&&typeof t=="object"&&(s=t,t=null),this.tag=t,s&&Object.assign(this,s)}name="Err-or";tag};function X(o,e,t=!1){return t&&(e=e.filter(s=>o.has(s))),e.map(s=>o.get(s))}function G(o,e){if(e){if(e.includes(".")){let t=o;for(let s of e.split("."))if(t=t?.[s],t===void 0)break;return t}return o[e]}return o}function ue(o,e){for(let t of e)if(o.has(t))return!0;return!1}function me(o,e,t,s,i=!0){return Array.isArray(o)&&(o=o.length),typeof s!="string"&&(i=s??!0,s=t),(i?`${o}\xA0`:"")+me.raw(o,e,t,s)}me.raw=(o,e,t,s=t)=>{o=Math.abs(o);let i=o%10,r=o%100;return i===1&&r!==11?e:i>=2&&i<=4&&!(r>=12&&r<=15)?t:s};function L(...o){let e=[];if(o.length){let[t,...s]=o;e:for(let i of t){for(let r of s)if(r instanceof Set?!r.has(i):!r.includes(i))continue e;e.push(i)}}return e}function fe(o,e){let t={};for(let s of e)s in o&&(t[s]=o[s]);return t}function N(o,e){return Math.floor(Math.random()*(e-o+1)+o)}function he(o,e){return o.delete(e),o.add(e),o}function f(o,e){let t,s=0;for(let i of e)for(;(t=o.indexOf(i))>-1;)o.splice(t,1),s++;return s}function be(o,e){let t=o.indexOf(e);return t>-1?(o.splice(t,1),!0):!1}function ge(o,e){for(let t of[...o].sort(e))o.delete(t),o.add(t);return o}var $=new WeakMap,W=class extends Promise{constructor(e){let t,s;super((i,r)=>{t=i,s=r}),$.set(this,{resolve:t,reject:s}),e?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=e=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=e;let t=$.get(this);t&&(t.resolve.call(this,e),$.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=$.get(this);t&&(t.reject.call(this,e),$.delete(this))}}};function ye(...o){return[...new Set(o.flat())]}function M(o,e){return o.filter(t=>!e.includes(t))}var Z=class extends A{constructor(e){super("User lacks ability","lacksability",{ability:e})}name="AbilityError"};function Y(o){return typeof o=="object"}function Q(o){return typeof o=="number"}function V(o){return Array.isArray(o)}var Ae=new Map,B=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(s,i,r){for(let n of s){if(Ae.set(n,i),n.level=r,!i||n.top){if(n.longId=n._id,this.has(n._id))throw new Error(`Top-level ability duplicate: ${n._id}`);this.set(n._id,n)}else n.longId=i?`${i.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,r+1)}}).call(this,e,null,0)}#e=[];get(e,t){let s=e.split("."),i=t??super.get(s.shift());if(i&&s.length){for(let r of s)if(i=i?.abilities?.find(({_id:n,top:l})=>!l&&n===r),!i)break}return i}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:s})=>s===t)}getDefaultParam(e,t,s){(t===void 0||typeof t=="boolean")&&(s=t);let i=typeof e=="string"?this.getParamSchema(e,t):e;if(i)switch(i.type){case"number":return s?i.max??1/0:i.min??0;case"items":return s?i.items.map(({_id:r})=>r):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let s={};if(e.params)for(let i of e.params)s[i._id]=this.getDefaultParam(i,t);if(t&&e.abilities)for(let i of e.abilities)i.top||(s[i._id]=this.getDefaultAbility(i,t));return s}return!0}}getDefaultAbilities(e,t=!e){let s=(e?(Array.isArray(e)?e:[e]).map(r=>typeof r=="string"?this.get(r):r).filter(Boolean):[...this.values()]).sort((r,n)=>r.level-n.level),i=new Map;for(let r of s)(function n(l){let a=Ae.get(l);a&&(n(a),i.has(a)||i.set(a,!1))})(r),t?function n(l){if(i.has(l)||i.set(l,!0),l.abilities)for(let a of l.abilities)a.top&&n(a)}(r):i.has(r)||i.set(r,!1);return pe({},Object.fromEntries([...i].map(([r,n])=>[r.longId,this.getDefaultAbility(r,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(s,i){for(let r=0;r<s.length;r++){let n=s[r],l=n.top?e[n._id]:i[n._id];if(l){if(n.params)for(let a of n.params){let p=l[a._id];switch(a.type){case"number":a.max=p;break;case"items":a.items=a.items.filter(({_id:g})=>p.includes(g))}}n.abilities&&(t(n.abilities,l),n.abilities.length||delete n.abilities)}else s.splice(r--,1)}return s}(structuredClone(this.#e),e)}getParam(e,t,s){if(this.getParamSchema(t,s)){let i=G(e,`${t}.${s}`);return this.isParamFits(t,s,i)?i:this.getDefaultParam(t,s)}}setParam(e,t,s,i){let r=this.getParamSchema(t,s);if(!r)throw new Error(`No such ability param: ${t}.${s}`);return E(e,`${t}.${s}`,this.adjustParam(r,i)),e}isParamFits(e,t,s,i){if(s!==void 0){let r=this.getParamSchema(e,t);if(r)switch(r.type){case"number":return Q(s)&&(r.min===void 0||s>=r.min)&&(i===void 0?r.max===void 0||s<=r.max:s<=i);case"items":return V(s)&&s.length===new Set(s).size&&(i===void 0?s.every(n=>r.items.find(({_id:l})=>l===n)):s.every(n=>i.includes(n)))}}return!1}adjustParam(e,t){switch(e.type){case"number":return Q(t)?Math.max(Math.min(t,e.max??1/0),e.min??0):e.min??0;default:return V(t)?L(e.items.map(s=>s._id),t):[]}}adjust(e,t){let s={};for(let[i,r]of Object.entries(e)){let n=this.get(i,t);if(n)if(n.params||n.abilities){let l={};if(n.params)if(Y(r))for(let a of n.params)l[a._id]=this.adjustParam(a,r[a._id]);else for(let a of n.params)l[a._id]=this.getDefaultParam(a);n.abilities&&Y(r)&&Object.assign(l,this.adjust(fe(r,n.abilities.filter(a=>!a.top).map(a=>a._id)),n)),s[i]=l}else s[i]=!0}return Object.assign(k(e),s)}merge(e,t,s){s||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[i,r]of Object.entries(t)){let n=this.get(i,s);if(n&&n.isInheritable!==!1)if(i in e&&(n.params||n.abilities)){let l=e[i],a=r;if(n.params){for(let p of n.params)if(p.isInheritable!==!1)switch(p.type){case"number":l[p._id]=Math.max(l[p._id],a[p._id]);break;case"items":ce(l[p._id],...a[p._id])}}n.abilities&&this.merge(l,a,n)}else e[i]=r}return e}hasAbility(e,t){return!!G(e,t)}setAbility(e,t){let s=typeof t=="string"?this.get(t):t;if(!s)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(s)),e}unsetAbility(e,t){let s=typeof t=="string"?this.get(t):t;if(!s)throw new Error(`No such ability: ${t}`);return function i(r){if(de(e,r.longId),r.abilities)for(let n of r.abilities)i(n)}(s),e}};var ee=class extends A{constructor(e){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e]})}name="RolesError"};var te=new Map,D=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t)}#e;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:s,title:i,...r},n){if(Object.assign(this,r),t&&(this.ownInvolveIds=t),s&&(this.ownAbilities=s),i!==void 0&&(this.title=i,this.displayTitle=i||this._id),t||s){let l=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
2
- `);l!==te.get(this._id)&&(te.set(this._id,l),this.#e.users.isInited&&this.#e.updateDebounced().then(()=>this.#e.users.emit("roles-role-update",this,n)))}}delete(){this.#e.delete(this._id),te.delete(this._id),this.#e.updateDebounced()}};var c={_id:/^[\dA-Fa-f]{24}$/,email:/^[^\s@]{1,63}@[^\s@]{1,63}\.[^\s@]{1,63}$/,argon2:/^\$argon2(?:i|d|id)\$v=\d+\$m=\d+,t=\d+,p=\d+(?:\$[\d+/A-Za-z]+){2}$/,sessionId:/^[\dA-Fa-f]{16,32}\$[\dA-Fa-f]{16,32}$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/};var P={required:["_id","involves","abilities","title","description","createdAt"],properties:{_id:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},createdAt:{bsonType:"number"}},additionalProperties:!1};var _e=[[{involves:1}]];function Se(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var F=class extends Map{constructor(e,t={}){super();let{root:s,...i}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new D(this,{...s,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",createdAt:Date.now()}),this.initOptions=i}users;collections;collection;abilities;root;initOptions;#e=!1;async init(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t}=this.initOptions;e&&(e.required&&f(e.required,P.required),e.properties&&u(e,Object.keys(P.properties)));let s={...P,...e,required:[...P.required,...e?.required??[]],properties:{...P.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{jsonSchema:s}),{deleteOne:Se,deleteMany:Se}),this.collection.ensureIndexes([..._e,...t??[]]);for(let i of await this.collection.find().toArray())this.abilities.adjust(i.abilities)&&await this.collection.updateOne({_id:i._id},{$set:{abilities:i.abilities}}),this.load(i);this.update(),this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":{let r=new D(this,i.fullDocument);this.users.emit("roles-role-update",r,i);break}case"replace":this.get(i.documentKey._id)?.update(i.fullDocument,i);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields,i);break;case"delete":this.get(i.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,i)}}),delete this.initOptions}}load(e){new D(this,e)}resolve(e,t){t=[e,...t];for(let s of e.ownInvolveIds){let i=this.get(s);if(i){for(let r of t)he(r.involves,i),this.abilities.merge(r.inheritedAbilities,i.abilities);i!==e&&this.resolve(i,t)}}}sorted=[];#t(e,t){return t.involves.size-e.involves.size||(e.title&&t.title?e.title>t.title?1:e.title<t.title?-1:0:e.title?-1:t.title||e._id>t._id?1:e._id<t._id?-1:0)}update(){let e=[...this.values()];this.root.ownInvolveIds=[];for(let i of e)i!==this.root&&!e.some(r=>r.ownInvolveIds.includes(i._id))&&this.root.ownInvolveIds.push(i._id),i.involves.clear(),i.abilities=structuredClone(i.ownAbilities),i.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let i of e)i.ownInvolves=X(this,i.ownInvolveIds,!0).sort(this.#t).reverse();let t=[this.root];for(let i=0;i<t.length;i++){let r=t[i];for(let n of r.ownInvolves){let l=t.indexOf(n);~l&&(t.splice(l,1),i--),t.splice(i+1,0,n)}}let s=0;for(let i of t)this.abilities.merge(i.abilities,i.inheritedAbilities),i._o=s++;this.sorted=t,this.users.emit("roles-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update(!0))}updateDebounced=m(this.update,100);create({_id:e,involves:t,title:s,description:i,...r}){return this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:s??"",description:i??"",...u(r,["abilities"]),createdAt:Date.now()})}async updateRole(e,t){let s=this.get(e);if(!s)return!1;if(t.involves){f(t.involves,[e]);for(let i of t.involves)this.get(i)?.involves.has(s)&&f(t.involves,[i]);t.involves=this.cleanUpIds(t.involves)}return await this.collection.updateOne({_id:e},{$set:t}),!0}deleteRole(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{involves:t},update:{$pullAll:{involves:[t]}}}},{deleteOne:{filter:{_id:t}}}])}cleanUpIds(e){let t=L(this.sorted,X(this,e,!0)),s=[];for(let i of t)t.every(r=>r===i||!r.involves.has(i))&&s.push(i._id);return s}async setAbility(e,t,s){let i=this.get(e);return i?(await this.collection.updateOne({_id:e},{$set:{abilities:s?this.abilities.setAbility(i.ownAbilities,t):this.abilities.unsetAbility(i.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,s,i){let r=this.get(e);return r?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(r.ownAbilities,t,s,i)}}),!0):!1}};var ie=class extends A{constructor(e,t){super("Insubordination attempt","subordination",{type:e,ids:Array.isArray(t)?t:[t]})}name="SubordinationError"};import*as C from"argon2";import Te from"eventemitter3";import{newObjectIdString as Ue}from"insite-db";import{newObjectIdString as Ie}from"insite-db";var se=new Map,h=class{constructor(e,t){this.orgs=e,this._id=t._id,e.set(this._id,this),this.update(t)}_id;title="";initials="";displayLabel="";_o=0;orgs;isOrg=!0;ownerOrgs=new Set;ownerUsers=new Set;users=new Set;slaveOrgs=new Set;ownerIds=[];update({_id:e,title:t,owners:s,...i},r){if(Object.assign(this,i),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),s){this.ownerIds=s;let n=this.ownerIds.join(",");n!==se.get(this._id)&&(se.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,r))}}delete(){this.orgs.delete(this._id),se.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}};var R={required:["_id","title","note","owners","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c._id.source},additionalItems:!1},createdAt:{bsonType:"number"}},additionalProperties:!1};var De=[[{owners:1}]];function xe(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var K=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,null:s}=this.preinitOptions;e&&(e.required&&f(e.required,R.required),e.properties&&u(e,Object.keys(R.properties)));let i={...R,...e,required:[...R.required,...e?.required??[]],properties:{...R.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{jsonSchema:i}),{deleteOne:xe,deleteMany:xe}),this.collection.ensureIndexes([...De,...t??[]]),this.null=Object.assign(new h(this,{...s,_id:"",title:"",note:"",owners:[],createdAt:Date.now()}),{_id:null,ownerIds:new q,ownerOrgs:new I,ownerUsers:new I,slaveOrgs:new I});for(let r of await this.collection.find().toArray())this.load(r);delete this.preinitOptions}}#t=!1;init(){this.#t||(this.#t=!0,this.update(),this.collection.changeListeners.add(e=>{switch(e.operationType){case"insert":{let t=new h(this,e.fullDocument);this.users.emit("orgs-org-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("orgs-org-update",null,e)}}))}load(e){new h(this,e)}#i(e,t){t=[e,...t];for(let s of e.ownerOrgs){this.#i(s,t);for(let i of t)s.slaveOrgs.add(i)}}sorted=[];update(){let e=[...this.values()],t=[];for(let s of e){s.ownerOrgs.clear(),s.ownerUsers.clear(),s.slaveOrgs.clear();for(let i of s.ownerIds){let r=this.get(i);if(r)s.ownerOrgs.add(r);else{let n=this.users.get(i);n&&s.ownerUsers.add(n)}}!s.ownerOrgs.size&&s._id&&t.push(s)}for(let s of e)e.some(i=>i.ownerOrgs.has(s))||this.#i(s,[]);t.sort(this.#s);for(let s of e)ge(s.slaveOrgs,this.#s);for(let s=0;s<t.length;s++){let i=t[s];for(let r of[...i.slaveOrgs].reverse())if(r.ownerOrgs.has(i)){let n=t.indexOf(r);~n&&(t.splice(n,1),s--),t.splice(s+1,0,r)}}for(let s=0,{length:i}=t;s<i;)t[s]._o=s++;this.sorted=t,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}#s(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}updateDebounced=m(this.update,250);create({title:e,note:t,...s},i){return this.collection.insertOne({_id:Ie(),title:e??"",note:t??"",owners:i?[i]:[],...u(s,["_id","owners"]),createdAt:Date.now()})}async updateOrg(e,t,s){let i=this.get(e);return i?(t.owners&&(t.owners=this.users.sortIds(ye(s?M(i.ownerIds,s.slaveIds):[],M(t.owners,[e,...x(i.slaveOrgs)])))),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}deleteOrg(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{owners:t},update:{$pullAll:{owners:[t]}}}},{deleteOne:{filter:{_id:t}}}])}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let s of this.replaceHandlers)await s(e,t)}};import we from"node:crypto";var j={required:["_id","user","remoteAddress","isOnline","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:c.sessionId.source},user:{bsonType:"string",pattern:c._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:c.ip.source},isOnline:{bsonType:"bool"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var T=class{constructor(e,t){let s=e.users.get(t.user);s?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=s,this.user.sessions.add(this),this.#e.users.bySessionId.set(this._id,this.user),this.update(t)):e.collection.deleteOne({_id:t._id})}_id;user;isOnline=!1;userAgent;remoteAddress;createdAt;prolongedAt;expiresAt;#e;update({_id:e,user:t,isOnline:s,...i}){s!==void 0&&this.isOnline!==s&&(this.isOnline=s,this.#e.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,i)}prolong({_id:e,user:t,...s}){let i=Date.now();return s.prolongedAt=i,s.expiresAt=new Date(i+this.#e.collection.expireAfterSeconds*1e3),this.update(s),this.#e.collection.updateOne({_id:this._id},{$set:s})}offline(){let e={isOnline:!1};return this.update(e),this.#e.collection.updateOne({_id:this._id},{$set:e})}delete(){this.#e.delete(this._id),this.user.sessions.delete(this),this.#e.users.bySessionId.delete(this._id),this.#e.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}};var re=3600*24*7,Pe=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:re}]],z=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{schema:e,indexes:t}=this.initOptions;e&&(e.required&&f(e.required,j.required),e.properties&&u(e,Object.keys(j.properties)));let s={...j,...e,required:[...j.required,...e?.required??[]],properties:{...j.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{jsonSchema:s}),{expireAfterSeconds:re}),this.collection.ensureIndexes([...Pe,...t??[]]),await this.collection.updateMany({isOnline:!0},{$set:{isOnline:!1}});for(let i of await this.collection.find().toArray())this.load(i);this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":this.has(i.documentKey._id)||new T(this,i.fullDocument),this.users.get(i.fullDocument.user)?.trimSessions();break;case"replace":this.get(i.documentKey._id)?.update(i.fullDocument);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields);break;case"delete":this.get(i.documentKey._id)?.delete()}}),delete this.initOptions}}uid(){let e;do e=`${we.randomBytes(N(8,16)).toString("hex")}$${we.randomBytes(N(8,16)).toString("hex")}`;while(this.has(e));return e}load(e){new T(this,e)}async create(e,t){let s=Date.now(),i={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,createdAt:s,prolongedAt:s,expiresAt:new Date(s+re*1e3)},r=new T(this,i);return await this.collection.insertOne(i),r}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as Re}from"insite-db";var Oe={required:["_id","type","size","ts","data"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"}},additionalProperties:!1};var H=class{constructor(e){this.users=e,this.collections=e.collections}TYPES_ACCEPTED=["image/webp"];MAX_SIZE=1024*512;users;collections;collection;#e=!1;async init(){this.#e||(this.#e=!0,this.collection=await this.collections.ensure("users.avatars",{jsonSchema:Oe}))}async save(e,t,s){let i=Re.createFromBase64(s.slice(s.indexOf(","))),r=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:i.length(),ts:r,data:i},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:r}})])}async deleteAvatar(e){let[{deletedCount:t}]=await Promise.all([this.collection.deleteOne({_id:e}),this.users.collection.updateOne({_id:e},{$set:{avatar:null}})]);return!!t}};var U={required:["_id","email","password","roles","name","org","job","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},email:{bsonType:"string",pattern:c.email.source},password:{bsonType:"string",pattern:c.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source},additionalItems:!1},name:{bsonType:"object",required:["first","middle","last"],properties:{first:{bsonType:"string",maxLength:512},middle:{bsonType:"string",maxLength:512},last:{bsonType:"string",maxLength:512}},additionalProperties:!1},org:{oneOf:[{bsonType:"string",pattern:c._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},createdAt:{bsonType:"number"}},additionalProperties:!1};var oe=new Map,ne=new Map,je=process.env.INSITE_STATIC_URL??"http://localhost:8080",w=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t),e.isInited&&e.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;#e;isUser=!0;isRoot;roles=new Set;ownRoles=[];ownRoleIds=[];slaveRoles=new Set;slaveRoleIds=[];abilities={};slaveOrgs=new Set;slaveUsers=new Set;slaves=new Set;slaveIds=[];permissiveIds=[];sessions=new Set;isOnline=!1;update({_id:e,name:t,email:s,roles:i,org:r,avatar:n,...l}){Object.assign(this,l);let a;s&&this.email!==s&&(this.#e.byEmail.delete(this.email),this.email=s,this.#e.byEmail.set(s,this),a=!0);let p,g;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(g=this.name.last!==t.last,this.name={first:t.first??"",middle:t.middle??"",last:t.last??""},this.initials=((t.first?.[0]??"")+(t.last?.[0]??"")||this.email[0]).toUpperCase(),p=!0),(a||p)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let y;if(i){this.ownRoleIds=i;let O=this.ownRoleIds.join(",");O!==oe.get(this._id)&&(oe.set(this._id,O),this.updateRoles(),y=!0)}let d;r!==void 0&&this.org?._id!==r&&(this.org?.users.delete(this),this.org=r&&this.#e.orgs.get(r)||this.#e.orgs.null,this.org.users.add(this),d=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${je}/avatars/${this._id}-${n}.webp`),y||d?(this.updatePermissions(),g&&(this.#e.isSortRequired=!0),this.#e.isInited&&this.#e.updateDebounced()):g&&this.#e.sortDebounced()}updateRoles(){if(this.#e.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),k(this.abilities);for(let e of this.ownRoleIds){let t=this.#e.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let s of t.involves)this.roles.add(s),this.slaveRoles.add(s);this.slaveRoleIds=x(this.slaveRoles),this.#e.abilities.merge(this.abilities,t.abilities)}}this.roles.has(this.#e.roles.root)&&(this.isRoot=!0),this.trimSessions()}}updatePermissions(){if(this.#e.isInited){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let i of this.#e.orgs.sorted)if((i.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(i)){this.slaveOrgs.add(i),this.slaves.add(i),e.add(i._id);for(let r of i.slaveOrgs)this.slaveOrgs.add(r),this.slaves.add(r),e.add(r._id)}for(let i of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let r of i.users)r!==this&&(ue(this.slaveRoles,r.ownRoles)||!r.ownRoles.length)&&(this.slaveUsers.add(r),this.slaves.add(r),e.add(r._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let i of this.org.slaveOrgs)this.slaveOrgs.has(i)||t.push(i._id)}this.permissiveIds=[...t,this._id,...e];let s=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
1
+ function x(o){if(o instanceof Set){let e=[];for(let t of o)e.push(t._id);return e}return o.map(e=>e._id)}function ce(o,...e){let t=0;for(let s of e)o.includes(s)||(o.push(s),t++);return t}function E(o,e,t){if(o&&e){if(e.includes(".")){let s=e.split("."),i=o;for(let r=0;r<s.length-1;r++){let n=s[r],l=i[n];i=l&&typeof l=="object"?l:i[n]={}}return i[s.at(-1)]=t}return o[e]=t}return null}function pe(o,...e){for(let t of e)for(let s in t)Object.hasOwn(t,s)&&E(o,s,t[s]);return o}function _(){}function m(o,e=0,t={}){let{leading:s=!1,trailing:i=!0}=t,{maxWait:r=1/0}=t,n,l,a,p,g,y,d,O,ae=async()=>{let v=Date.now();v>=a?(n=void 0,a=void 0,clearTimeout(l),typeof d=="function"&&await d(),b.resolve(O),b.promise.isResolved=!0,y=s):(clearTimeout(n),n=setTimeout(ae,a-v))},J=Number.isFinite(r)?()=>{d===S&&(d=!1),S(),l=setTimeout(J,r)}:null;async function S(){return O=await o.apply(p,g)}s&&typeof s=="boolean"&&(s=S),y=s,i&&typeof i=="boolean"&&(i=S),d=i;let b=Object.assign(function(...v){return g=v,p=this,a=Date.now()+e,d=i,b.promise.isResolved&&(b.promise=Object.assign(new Promise(ve=>{b.resolve=ve,typeof y=="function"&&(y(),y=!1,d===S&&(d=!1)),n||(n=setTimeout(ae,e),J&&(l=setTimeout(J,r)))}),{isResolved:!1})),b.promise},{callback:o,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:S,clear:async v=>{clearTimeout(n),n=void 0,clearTimeout(l),b.promise.isResolved=!0,b.resolve(v?await S():O)}});return b}m.noop=Object.assign(()=>{},{callback:_,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:_,clear:_});function de(o,e){if(o&&e){if(e.includes(".")){let t=e.split("."),s=o;for(let r=0;r<t.length-1;r++){let n=t[r],l=s[n];if(l&&typeof l=="object")s=l;else return!1}let i=t.at(-1);return i in s&&delete s[i]}return e in o&&delete o[e]}return!1}function u(o,e){if(o){for(let t of e)delete o[t];return o}return null}function k(o){for(let e in o)delete o[e];return o}var q=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var D=class extends Set{constructor(){super()}add(){return this}};var A=class extends Error{constructor(e,t=null,s){super(e),t&&typeof t=="object"&&(s=t,t=null),this.tag=t,s&&Object.assign(this,s)}name="Err-or";tag};function X(o,e,t=!1){return t&&(e=e.filter(s=>o.has(s))),e.map(s=>o.get(s))}function G(o,e){if(e){if(e.includes(".")){let t=o;for(let s of e.split("."))if(t=t?.[s],t===void 0)break;return t}return o[e]}return o}function ue(o,e){for(let t of e)if(o.has(t))return!0;return!1}function me(o,e,t,s,i=!0){return Array.isArray(o)&&(o=o.length),typeof s!="string"&&(i=s??!0,s=t),(i?`${o}\xA0`:"")+me.raw(o,e,t,s)}me.raw=(o,e,t,s=t)=>{o=Math.abs(o);let i=o%10,r=o%100;return i===1&&r!==11?e:i>=2&&i<=4&&!(r>=12&&r<=15)?t:s};function L(...o){let e=[];if(o.length){let[t,...s]=o;e:for(let i of t){for(let r of s)if(r instanceof Set?!r.has(i):!r.includes(i))continue e;e.push(i)}}return e}function fe(o,e){let t={};for(let s of e)s in o&&(t[s]=o[s]);return t}function N(o,e){return Math.floor(Math.random()*(e-o+1)+o)}function he(o,e){return o.delete(e),o.add(e),o}function f(o,e){let t,s=0;for(let i of e)for(;(t=o.indexOf(i))>-1;)o.splice(t,1),s++;return s}function be(o,e){let t=o.indexOf(e);return t>-1?(o.splice(t,1),!0):!1}function ge(o,e){for(let t of[...o].sort(e))o.delete(t),o.add(t);return o}var $=new WeakMap,W=class extends Promise{constructor(e){let t,s;super((i,r)=>{t=i,s=r}),$.set(this,{resolve:t,reject:s}),e?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=e=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=e;let t=$.get(this);t&&(t.resolve.call(this,e),$.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=$.get(this);t&&(t.reject.call(this,e),$.delete(this))}}};function ye(...o){return[...new Set(o.flat())]}function M(o,e){return o.filter(t=>!e.includes(t))}var Z=class extends A{constructor(e){super("User lacks ability","lacksability",{ability:e})}name="AbilityError"};function Y(o){return typeof o=="object"}function Q(o){return typeof o=="number"}function V(o){return Array.isArray(o)}var Ae=new Map,B=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(s,i,r){for(let n of s){if(Ae.set(n,i),n.level=r,!i||n.top){if(n.longId=n._id,this.has(n._id))throw new Error(`Top-level ability duplicate: ${n._id}`);this.set(n._id,n)}else n.longId=i?`${i.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,r+1)}}).call(this,e,null,0)}#e=[];get(e,t){let s=e.split("."),i=t??super.get(s.shift());if(i&&s.length){for(let r of s)if(i=i?.abilities?.find(({_id:n,top:l})=>!l&&n===r),!i)break}return i}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:s})=>s===t)}getDefaultParam(e,t,s){(t===void 0||typeof t=="boolean")&&(s=t);let i=typeof e=="string"?this.getParamSchema(e,t):e;if(i)switch(i.type){case"number":return s?i.max??1/0:i.min??0;case"items":return s?i.items.map(({_id:r})=>r):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let s={};if(e.params)for(let i of e.params)s[i._id]=this.getDefaultParam(i,t);if(t&&e.abilities)for(let i of e.abilities)i.top||(s[i._id]=this.getDefaultAbility(i,t));return s}return!0}}getDefaultAbilities(e,t=!e){let s=(e?(Array.isArray(e)?e:[e]).map(r=>typeof r=="string"?this.get(r):r).filter(Boolean):[...this.values()]).sort((r,n)=>r.level-n.level),i=new Map;for(let r of s)(function n(l){let a=Ae.get(l);a&&(n(a),i.has(a)||i.set(a,!1))})(r),t?function n(l){if(i.has(l)||i.set(l,!0),l.abilities)for(let a of l.abilities)a.top&&n(a)}(r):i.has(r)||i.set(r,!1);return pe({},Object.fromEntries([...i].map(([r,n])=>[r.longId,this.getDefaultAbility(r,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(s,i){for(let r=0;r<s.length;r++){let n=s[r],l=n.top?e[n._id]:i[n._id];if(l){if(n.params)for(let a of n.params){let p=l[a._id];switch(a.type){case"number":a.max=p;break;case"items":a.items=a.items.filter(({_id:g})=>p.includes(g))}}n.abilities&&(t(n.abilities,l),n.abilities.length||delete n.abilities)}else s.splice(r--,1)}return s}(structuredClone(this.#e),e)}getParam(e,t,s){if(this.getParamSchema(t,s)){let i=G(e,`${t}.${s}`);return this.isParamFits(t,s,i)?i:this.getDefaultParam(t,s)}}setParam(e,t,s,i){let r=this.getParamSchema(t,s);if(!r)throw new Error(`No such ability param: ${t}.${s}`);return E(e,`${t}.${s}`,this.adjustParam(r,i)),e}isParamFits(e,t,s,i){if(s!==void 0){let r=this.getParamSchema(e,t);if(r)switch(r.type){case"number":return Q(s)&&(r.min===void 0||s>=r.min)&&(i===void 0?r.max===void 0||s<=r.max:s<=i);case"items":return V(s)&&s.length===new Set(s).size&&(i===void 0?s.every(n=>r.items.find(({_id:l})=>l===n)):s.every(n=>i.includes(n)))}}return!1}adjustParam(e,t){switch(e.type){case"number":return Q(t)?Math.max(Math.min(t,e.max??1/0),e.min??0):e.min??0;default:return V(t)?L(e.items.map(s=>s._id),t):[]}}adjust(e,t){let s={};for(let[i,r]of Object.entries(e)){let n=this.get(i,t);if(n)if(n.params||n.abilities){let l={};if(n.params)if(Y(r))for(let a of n.params)l[a._id]=this.adjustParam(a,r[a._id]);else for(let a of n.params)l[a._id]=this.getDefaultParam(a);n.abilities&&Y(r)&&Object.assign(l,this.adjust(fe(r,n.abilities.filter(a=>!a.top).map(a=>a._id)),n)),s[i]=l}else s[i]=!0}return Object.assign(k(e),s)}merge(e,t,s){s||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[i,r]of Object.entries(t)){let n=this.get(i,s);if(n&&n.isInheritable!==!1)if(i in e&&(n.params||n.abilities)){let l=e[i],a=r;if(n.params){for(let p of n.params)if(p.isInheritable!==!1)switch(p.type){case"number":l[p._id]=Math.max(l[p._id],a[p._id]);break;case"items":ce(l[p._id],...a[p._id])}}n.abilities&&this.merge(l,a,n)}else e[i]=r}return e}hasAbility(e,t){return!!G(e,t)}setAbility(e,t){let s=typeof t=="string"?this.get(t):t;if(!s)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(s)),e}unsetAbility(e,t){let s=typeof t=="string"?this.get(t):t;if(!s)throw new Error(`No such ability: ${t}`);return function i(r){if(de(e,r.longId),r.abilities)for(let n of r.abilities)i(n)}(s),e}};var ee=class extends A{constructor(e){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e]})}name="RolesError"};var te=new Map,P=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t)}#e;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:s,title:i,...r},n){if(Object.assign(this,r),t&&(this.ownInvolveIds=t),s&&(this.ownAbilities=s),i!==void 0&&(this.title=i,this.displayTitle=i||this._id),t||s){let l=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
2
+ `);l!==te.get(this._id)&&(te.set(this._id,l),this.#e.users.isInited&&this.#e.updateDebounced().then(()=>this.#e.users.emit("roles-role-update",this,n)))}}delete(){this.#e.delete(this._id),te.delete(this._id),this.#e.updateDebounced()}};var c={_id:/^[\dA-Fa-f]{24}$/,email:/^[^\s@]{1,63}@[^\s@]{1,63}\.[^\s@]{1,63}$/,argon2:/^\$argon2(?:i|d|id)\$v=\d+\$m=\d+,t=\d+,p=\d+(?:\$[\d+/A-Za-z]+){2}$/,sessionId:/^[\dA-Fa-f]{16,32}\$[\dA-Fa-f]{16,32}$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/};var I={required:["_id","involves","abilities","title","description","createdAt"],properties:{_id:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},createdAt:{bsonType:"number"}},additionalProperties:!1};var _e=[[{involves:1}]];function Se(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var F=class extends Map{constructor(e,t={}){super();let{root:s,...i}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new P(this,{...s,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",createdAt:Date.now()}),this.initOptions=i}users;collections;collection;abilities;root;initOptions;#e=!1;async init(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t}=this.initOptions;e&&(e.required&&f(e.required,I.required),e.properties&&u(e,Object.keys(I.properties)));let s={...I,...e,required:[...I.required,...e?.required??[]],properties:{...I.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{jsonSchema:s}),{deleteOne:Se,deleteMany:Se}),this.collection.ensureIndexes([..._e,...t??[]]);for(let i of await this.collection.find().toArray())this.abilities.adjust(i.abilities)&&await this.collection.updateOne({_id:i._id},{$set:{abilities:i.abilities}}),this.load(i);this.update(),this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":{let r=new P(this,i.fullDocument);this.users.emit("roles-role-update",r,i);break}case"replace":this.get(i.documentKey._id)?.update(i.fullDocument,i);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields,i);break;case"delete":this.get(i.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,i)}}),delete this.initOptions}}load(e){new P(this,e)}resolve(e,t){t=[e,...t];for(let s of e.ownInvolveIds){let i=this.get(s);if(i){for(let r of t)he(r.involves,i),this.abilities.merge(r.inheritedAbilities,i.abilities);i!==e&&this.resolve(i,t)}}}sorted=[];#t(e,t){return t.involves.size-e.involves.size||(e.title&&t.title?e.title>t.title?1:e.title<t.title?-1:0:e.title?-1:t.title||e._id>t._id?1:e._id<t._id?-1:0)}update(){let e=[...this.values()];this.root.ownInvolveIds=[];for(let i of e)i!==this.root&&!e.some(r=>r.ownInvolveIds.includes(i._id))&&this.root.ownInvolveIds.push(i._id),i.involves.clear(),i.abilities=structuredClone(i.ownAbilities),i.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let i of e)i.ownInvolves=X(this,i.ownInvolveIds,!0).sort(this.#t).reverse();let t=[this.root];for(let i=0;i<t.length;i++){let r=t[i];for(let n of r.ownInvolves){let l=t.indexOf(n);~l&&(t.splice(l,1),i--),t.splice(i+1,0,n)}}let s=0;for(let i of t)this.abilities.merge(i.abilities,i.inheritedAbilities),i._o=s++;this.sorted=t,this.users.emit("roles-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update(!0))}updateDebounced=m(this.update,100);create({_id:e,involves:t,title:s,description:i,...r}){return this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:s??"",description:i??"",...u(r,["abilities"]),createdAt:Date.now()})}async updateRole(e,t){let s=this.get(e);if(!s)return!1;if(t.involves){f(t.involves,[e]);for(let i of t.involves)this.get(i)?.involves.has(s)&&f(t.involves,[i]);t.involves=this.cleanUpIds(t.involves)}return await this.collection.updateOne({_id:e},{$set:t}),!0}deleteRole(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{involves:t},update:{$pullAll:{involves:[t]}}}},{deleteOne:{filter:{_id:t}}}])}cleanUpIds(e){let t=L(this.sorted,X(this,e,!0)),s=[];for(let i of t)t.every(r=>r===i||!r.involves.has(i))&&s.push(i._id);return s}async setAbility(e,t,s){let i=this.get(e);return i?(await this.collection.updateOne({_id:e},{$set:{abilities:s?this.abilities.setAbility(i.ownAbilities,t):this.abilities.unsetAbility(i.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,s,i){let r=this.get(e);return r?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(r.ownAbilities,t,s,i)}}),!0):!1}};var ie=class extends A{constructor(e,t){super("Insubordination attempt","subordination",{type:e,ids:Array.isArray(t)?t:[t]})}name="SubordinationError"};import*as C from"argon2";import Te from"eventemitter3";import{newObjectIdString as Ue}from"insite-db";import{newObjectIdString as De}from"insite-db";var se=new Map,h=class{constructor(e,t){this.orgs=e,this._id=t._id,e.set(this._id,this),this.update(t)}_id;title="";initials="";displayLabel="";_o=0;orgs;isOrg=!0;ownerOrgs=new Set;ownerUsers=new Set;users=new Set;slaveOrgs=new Set;ownerIds=[];update({_id:e,title:t,owners:s,...i},r){if(Object.assign(this,i),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),s){this.ownerIds=s;let n=this.ownerIds.join(",");n!==se.get(this._id)&&(se.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,r))}}delete(){this.orgs.delete(this._id),se.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}};var R={required:["_id","title","note","owners","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c._id.source},additionalItems:!1},createdAt:{bsonType:"number"}},additionalProperties:!1};var Pe=[[{owners:1}]];function xe(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var K=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,null:s}=this.preinitOptions;e&&(e.required&&f(e.required,R.required),e.properties&&u(e,Object.keys(R.properties)));let i={...R,...e,required:[...R.required,...e?.required??[]],properties:{...R.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{jsonSchema:i}),{deleteOne:xe,deleteMany:xe}),this.collection.ensureIndexes([...Pe,...t??[]]),this.null=Object.assign(new h(this,{...s,_id:"",title:"",note:"",owners:[],createdAt:Date.now()}),{_id:null,ownerIds:new q,ownerOrgs:new D,ownerUsers:new D,slaveOrgs:new D});for(let r of await this.collection.find().toArray())this.load(r);delete this.preinitOptions}}#t=!1;init(){this.#t||(this.#t=!0,this.update(),this.collection.changeListeners.add(e=>{switch(e.operationType){case"insert":{let t=new h(this,e.fullDocument);this.users.emit("orgs-org-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("orgs-org-update",null,e)}}))}load(e){new h(this,e)}#i(e,t){t=[e,...t];for(let s of e.ownerOrgs){this.#i(s,t);for(let i of t)s.slaveOrgs.add(i)}}sorted=[];update(){let e=[...this.values()],t=[];for(let s of e){s.ownerOrgs.clear(),s.ownerUsers.clear(),s.slaveOrgs.clear();for(let i of s.ownerIds){let r=this.get(i);if(r)s.ownerOrgs.add(r);else{let n=this.users.get(i);n&&s.ownerUsers.add(n)}}!s.ownerOrgs.size&&s._id&&t.push(s)}for(let s of e)e.some(i=>i.ownerOrgs.has(s))||this.#i(s,[]);t.sort(this.#s);for(let s of e)ge(s.slaveOrgs,this.#s);for(let s=0;s<t.length;s++){let i=t[s];for(let r of[...i.slaveOrgs].reverse())if(r.ownerOrgs.has(i)){let n=t.indexOf(r);~n&&(t.splice(n,1),s--),t.splice(s+1,0,r)}}for(let s=0,{length:i}=t;s<i;)t[s]._o=s++;this.sorted=t,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}#s(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}updateDebounced=m(this.update,250);create({title:e,note:t,...s},i){return this.collection.insertOne({_id:De(),title:e??"",note:t??"",owners:i?[i]:[],...u(s,["_id","owners"]),createdAt:Date.now()})}async updateOrg(e,t,s){let i=this.get(e);return i?(t.owners&&(t.owners=this.users.sortIds(ye(s?M(i.ownerIds,s.slaveIds):[],M(t.owners,[e,...x(i.slaveOrgs)])))),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}deleteOrg(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{owners:t},update:{$pullAll:{owners:[t]}}}},{deleteOne:{filter:{_id:t}}}])}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let s of this.replaceHandlers)await s(e,t)}};import we from"node:crypto";var j={required:["_id","user","remoteAddress","isOnline","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:c.sessionId.source},user:{bsonType:"string",pattern:c._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:c.ip.source},isOnline:{bsonType:"bool"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var T=class{constructor(e,t){let s=e.users.get(t.user);s?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=s,this.user.sessions.add(this),this.#e.users.bySessionId.set(this._id,this.user),this.update(t)):e.collection.deleteOne({_id:t._id})}_id;user;isOnline=!1;userAgent;remoteAddress;createdAt;prolongedAt;expiresAt;#e;update({_id:e,user:t,isOnline:s,...i}){s!==void 0&&this.isOnline!==s&&(this.isOnline=s,this.#e.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,i)}prolong({_id:e,user:t,...s}){let i=Date.now();return s.prolongedAt=i,s.expiresAt=new Date(i+this.#e.collection.expireAfterSeconds*1e3),this.update(s),this.#e.collection.updateOne({_id:this._id},{$set:s})}offline(){let e={isOnline:!1};return this.update(e),this.#e.collection.updateOne({_id:this._id},{$set:e})}delete(){this.#e.delete(this._id),this.user.sessions.delete(this),this.#e.users.bySessionId.delete(this._id),this.#e.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}};var re=3600*24*7,Ie=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:re}]],z=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{schema:e,indexes:t}=this.initOptions;e&&(e.required&&f(e.required,j.required),e.properties&&u(e,Object.keys(j.properties)));let s={...j,...e,required:[...j.required,...e?.required??[]],properties:{...j.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{jsonSchema:s}),{expireAfterSeconds:re}),this.collection.ensureIndexes([...Ie,...t??[]]),await this.collection.updateMany({isOnline:!0},{$set:{isOnline:!1}});for(let i of await this.collection.find().toArray())this.load(i);this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":this.has(i.documentKey._id)||new T(this,i.fullDocument),this.users.get(i.fullDocument.user)?.trimSessions();break;case"replace":this.get(i.documentKey._id)?.update(i.fullDocument);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields);break;case"delete":this.get(i.documentKey._id)?.delete()}}),delete this.initOptions}}uid(){let e;do e=`${we.randomBytes(N(8,16)).toString("hex")}$${we.randomBytes(N(8,16)).toString("hex")}`;while(this.has(e));return e}load(e){new T(this,e)}async create(e,t){let s=Date.now(),i={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,createdAt:s,prolongedAt:s,expiresAt:new Date(s+re*1e3)},r=new T(this,i);return await this.collection.insertOne(i),r}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as Re}from"insite-db";var Oe={required:["_id","type","size","ts","data"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"}},additionalProperties:!1};var H=class{constructor(e){this.users=e,this.collections=e.collections}TYPES_ACCEPTED=["image/webp"];MAX_SIZE=1024*512;users;collections;collection;#e=!1;async init(){this.#e||(this.#e=!0,this.collection=await this.collections.ensure("users.avatars",{jsonSchema:Oe}))}async save(e,t,s){let i=Re.createFromBase64(s.slice(s.indexOf(","))),r=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:i.length(),ts:r,data:i},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:r}})])}async deleteAvatar(e){let[{deletedCount:t}]=await Promise.all([this.collection.deleteOne({_id:e}),this.users.collection.updateOne({_id:e},{$set:{avatar:null}})]);return!!t}};var U={required:["_id","email","password","roles","name","org","job","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},email:{bsonType:"string",pattern:c.email.source},password:{bsonType:"string",pattern:c.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source},additionalItems:!1},name:{bsonType:"object",required:["first","middle","last"],properties:{first:{bsonType:"string",maxLength:512},middle:{bsonType:"string",maxLength:512},last:{bsonType:"string",maxLength:512}},additionalProperties:!1},org:{oneOf:[{bsonType:"string",pattern:c._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},createdAt:{bsonType:"number"}},additionalProperties:!1};var oe=new Map,ne=new Map,je=process.env.INSITE_STATIC_URL??"http://localhost:8080",w=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t),e.isInited&&e.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;#e;isUser=!0;isRoot;roles=new Set;ownRoles=[];ownRoleIds=[];slaveRoles=new Set;slaveRoleIds=[];abilities={};slaveOrgs=new Set;slaveUsers=new Set;slaves=new Set;slaveIds=[];permissiveIds=[];sessions=new Set;isOnline=!1;update({_id:e,name:t,email:s,roles:i,org:r,avatar:n,...l}){Object.assign(this,l);let a;s&&this.email!==s&&(this.#e.byEmail.delete(this.email),this.email=s,this.#e.byEmail.set(s,this),a=!0);let p,g;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(g=this.name.last!==t.last,this.name={first:t.first??"",middle:t.middle??"",last:t.last??""},this.initials=((t.first?.[0]??"")+(t.last?.[0]??"")||this.email[0]).toUpperCase(),p=!0),(a||p)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let y;if(i){this.ownRoleIds=i;let O=this.ownRoleIds.join(",");O!==oe.get(this._id)&&(oe.set(this._id,O),this.updateRoles(),y=!0)}let d;r!==void 0&&this.org?._id!==r&&(this.org?.users.delete(this),this.org=r&&this.#e.orgs.get(r)||this.#e.orgs.null,this.org.users.add(this),d=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${je}/avatars/${this._id}-${n}.webp`),y||d?(this.updatePermissions(),g&&(this.#e.isSortRequired=!0),this.#e.isInited&&this.#e.updateDebounced()):g&&this.#e.sortDebounced()}updateRoles(){if(this.#e.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),k(this.abilities);for(let e of this.ownRoleIds){let t=this.#e.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let s of t.involves)this.roles.add(s),this.slaveRoles.add(s);this.slaveRoleIds=x(this.slaveRoles),this.#e.abilities.merge(this.abilities,t.abilities)}}this.roles.has(this.#e.roles.root)&&(this.isRoot=!0),this.trimSessions()}}updatePermissions(){if(this.#e.isInited){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let i of this.#e.orgs.sorted)if((i.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(i)){this.slaveOrgs.add(i),this.slaves.add(i),e.add(i._id);for(let r of i.slaveOrgs)this.slaveOrgs.add(r),this.slaves.add(r),e.add(r._id)}for(let i of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let r of i.users)r!==this&&(ue(this.slaveRoles,r.ownRoles)||!r.ownRoles.length)&&(this.slaveUsers.add(r),this.slaves.add(r),e.add(r._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let i of this.org.slaveOrgs)this.slaveOrgs.has(i)||t.push(i._id)}this.permissiveIds=[...t,this._id,...e];let s=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
3
3
  `);s!==ne.get(this._id)&&(ne.set(this._id,s),this.#e.emit("user-permissions-change",this))}}trimSessions(){let e=this.abilities.login?.sessionsLimit??0;return this.sessions.size>e?this.#e.sessions.collection.deleteMany({_id:{$in:x([...this.sessions].sort((t,s)=>t.expiresAt.valueOf()-s.expiresAt.valueOf()).slice(0,this.sessions.size-e))}}):null}updateIsOnline=m(()=>{let e=!1;for(let t of this.sessions)if(t.isOnline){e=!0;break}this.isOnline!==e&&(this.isOnline=e,this.#e.emit("user-is-online",this))},500);delete(){this.org.users.delete(this),this.#e.delete(this._id),this.#e.byEmail.delete(this.email),be(this.#e.sorted,this),oe.delete(this._id),ne.delete(this._id),this.#e.replace(this._id),this.#e.updateDebounced()}};var $e=[[{email:1},{unique:!0}],[{org:1}]],le=class o extends Map{constructor(e,t){super();let s=new Te;this._events=s._events,this._eventsCount=s._eventsCount,this.emit=s.emit,this.on=s.on,this.once=s.once,this.addListener=s.addListener,this.off=s.off,this.removeListener=s.removeListener,this.collections=e,this.abilities=new B(t.abilities),this.initOptions=t,this.init()}_events;_eventsCount;emit;on;once;addListener;off;removeListener;initOptions;collections;abilities;collection;roles;sessions;orgs;avatars;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!1;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{indexes:e,schema:t,initialRoot:s}=this.initOptions;t&&(t.required&&f(t.required,U.required),t.properties&&u(t,Object.keys(U.properties)));let i={...U,...t,required:[...U.required,...t?.required??[]],properties:{...U.properties,...t?.properties}};this.collection=await this.collections.ensure("users",{jsonSchema:i}),this.collection.ensureIndexes([...$e,...e??[]]),await this.collection.countDocuments({roles:"root"})||await this.create({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",name:{first:"Root"},job:"Root",...s,roles:["root"],org:null});for(let r of await this.collection.find().toArray())this.load(r)}}isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{roles:e,orgs:t,sessions:s}=this.initOptions;this.roles=new F(this,e),this.orgs=new K(this,t),this.sessions=new z(this,s),this.avatars=new H(this),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),await this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":new w(this,i.fullDocument);break;case"replace":this.get(i.documentKey._id)?.update(i.fullDocument);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields);break;case"delete":this.get(i.documentKey._id)?.delete()}}),await this.sessions.init(),delete this.initOptions,this.#t.resolve(this)}}load(e){new w(this,e)}sort(){this.isSortRequired=!1,this.sorted=[...this.values()].sort((e,t)=>e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0)}sortDebounced=m(()=>this.sort(),250);update(e){if(e)for(let t of this.values())t.updateRoles();for(let t of this.values())t.updatePermissions();this.isSortRequired&&this.sort()}updateDebounced=m(()=>this.update(),250);#t=new W;whenReady(){return this.#t}async create({email:e,password:t,roles:s,name:i,org:r,job:n,...l}){if(this.byEmail.has(e))throw new Error("User exists");return await this.collection.insertOne({_id:Ue(),email:e,password:await C.hash(t),roles:this.isInited?this.roles.cleanUpIds(s):s,name:{first:i.first??"",middle:i.middle??"",last:i.last??""},org:r??null,job:n??"",...u(l,["_id"]),createdAt:Date.now()}),!0}async updateUser(e,t,s){let i=this.get(e);return i?(t.roles&&(t.roles=i.isRoot?["root"]:this.roles.cleanUpIds(s?M(i.ownRoleIds,s.slaveRoleIds).concat(t.roles):t.roles)),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}async changePassword(e,t){if(!this.has(e))throw new Error("usernotfound");if(!t)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:e},{$set:{password:await C.hash(t)}}),this.sessions.collection.deleteMany({user:e})])}async login(e,t,s){let i=this.byEmail.get(e);if(!i)throw new Error("usernotfound");if(!await C.verify(i.password,t))throw new Error("incorrectpassword");if(!i.abilities.login)throw new Error("userisnotabletologin");return this.sessions.create(i,s)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}#i(e,t){return e instanceof w&&t instanceof w?e.name.last&&t.name.last?e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0:!e.name.last&&!t.name.last?e.displayLabel>t.displayLabel?1:e.displayLabel<t.displayLabel?-1:0:e.name.last?-1:1:e instanceof h&&t instanceof h?e.title>t.title?1:e.title<t.title?-1:0:e instanceof h?-1:1}sortIds(e){return x(e.map(t=>this.get(t)||this.orgs.get(t)).filter(Boolean).sort(this.#i))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let s of this.replaceHandlers)await s(e,t)}async deleteUser(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}static init(e,t){return new o(e,t).whenReady()}};export{Z as AbilityError,ee as RolesError,ie as SubordinationError,le as Users};
4
4
  //# sourceMappingURL=index.js.map