insite-users-server 2.1.5 → 2.1.7
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.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +4 -4
- package/dist/users/errors.d.ts +7 -3
- package/dist/users/errors.d.ts.map +1 -1
- package/package.json +6 -6
- package/bun.lock +0 -1017
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ export type { Org, OrgDoc, Orgs } from "./orgs";
|
|
|
4
4
|
export type { Role, RoleDoc, Roles } from "./roles";
|
|
5
5
|
export { RolesError } from "./roles";
|
|
6
6
|
export type { Session, SessionDoc, Sessions } from "./sessions";
|
|
7
|
-
export { SubordinationError, Users } from "./users";
|
|
7
|
+
export { PermissionError, SubordinationError, UnauthorizedError, Users } from "./users";
|
|
8
8
|
export type { AvatarDoc, Options, User, UserDoc } from "./users";
|
|
9
9
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC1J,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAChD,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,YAAY,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC1J,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAChD,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,YAAY,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACxF,YAAY,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
`);n!==U.get(this._id)&&(U.set(this._id,n),this.#e.users.isInited&&this.#e.updateDebounced().then(()=>this.#e.users.emit("roles-role-update",this,r)))}}delete(){this.#e.delete(this._id),U.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 u={required:["_id","involves","abilities","title","description","meta","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},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var fe=[[{involves:1}]];function H(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var O=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 h(this,{...s,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",meta:{},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&&T(e.required,u.required),e.properties&&B(e,Object.keys(u.properties)));let s={...u,...e,required:[...u.required,...e?.required??[]],properties:{...u.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{jsonSchema:s}),{deleteOne:H,deleteMany:H}),this.collection.ensureIndexes([...fe,...t??[]]),await this.#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 o=new h(this,i.fullDocument);this.users.emit("roles-role-update",o,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}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}load(e){new h(this,e)}resolve(e,t){t=[e,...t];for(let s of e.ownInvolveIds){let i=this.get(s);if(i){for(let o of t)ue(o.involves,i),this.abilities.merge(o.inheritedAbilities,i.abilities);i!==e&&this.resolve(i,t)}}}sorted=[];#i(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(o=>o.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=F(this,i.ownInvolveIds,!0).sort(this.#i).reverse();let t=[this.root];for(let i=0;i<t.length;i++){let o=t[i];for(let r of o.ownInvolves){let n=t.indexOf(r);~n&&(t.splice(n,1),i--),t.splice(i+1,0,r)}}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=me(this.update,100);create({_id:e,involves:t,title:s,description:i,...o}){return this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:s??"",description:i??"",meta:{},...B(o,["abilities"]),createdAt:Date.now()})}async updateRole(e,t){let s=this.get(e);if(!s)return!1;if(t.involves){T(t.involves,[e]);for(let i of t.involves)this.get(i)?.involves.has(s)&&T(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=he(this.sorted,F(this,e,!0)),s=[];for(let i of t)t.every(o=>o===i||!o.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 o=this.get(e);return o?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(o.ownAbilities,t,s,i)}}),!0):!1}};import{Err as be}from"@nesvet/n";var $=class extends be{constructor(e,t,s){switch(arguments.length){case 1:s=e,e=void 0;break;case 2:s=t,t=void 0}super("Insubordination attempt","subordination",{...e&&{type:e},...t&&{ids:Array.isArray(t)?t:[t]},...s})}name="SubordinationError"};import*as S from"argon2";import Ce from"eventemitter3";import{_ids as Me,debounce as te,deleteProps as ie,removeAll as Ee,StatefulPromise as qe,without as Ge}from"@nesvet/n";import{newObjectIdString as ke}from"insite-db";import{_ids as ge,debounce as ye,deleteProps as J,EmptyArray as Ae,EmptySet as M,removeAll as Se,sort as we,union as Oe,without as Z}from"@nesvet/n";import{newObjectIdString as ve}from"insite-db";var C=new Map,p=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},o){if(Object.assign(this,i),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),s){this.ownerIds=s;let r=this.ownerIds.join(",");r!==C.get(this._id)&&(C.set(this._id,r),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,o))}}delete(){this.orgs.delete(this._id),C.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}};var f={required:["_id","title","note","owners","meta","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},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var _e=[[{owners:1}]];function X(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var v=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&&Se(e.required,f.required),e.properties&&J(e,Object.keys(f.properties)));let i={...f,...e,required:[...f.required,...e?.required??[]],properties:{...f.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{jsonSchema:i}),{deleteOne:X,deleteMany:X}),this.collection.ensureIndexes([..._e,...t??[]]),this.null=Object.assign(new p(this,{...s,_id:"",title:"",note:"",owners:[],meta:{},createdAt:Date.now()}),{_id:null,ownerIds:new Ae,ownerOrgs:new M,ownerUsers:new M,slaveOrgs:new M}),await this.#t();for(let o of await this.collection.find().toArray())this.load(o);delete this.preinitOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#i=!1;init(){this.#i||(this.#i=!0,this.update(),this.collection.changeListeners.add(e=>{switch(e.operationType){case"insert":{let t=new p(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 p(this,e)}#s(e,t){t=[e,...t];for(let s of e.ownerOrgs){this.#s(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 o=this.get(i);if(o)s.ownerOrgs.add(o);else{let r=this.users.get(i);r&&s.ownerUsers.add(r)}}!s.ownerOrgs.size&&s._id&&t.push(s)}for(let s of e)e.some(i=>i.ownerOrgs.has(s))||this.#s(s,[]);t.sort(this.#o);for(let s of e)we(s.slaveOrgs,this.#o);for(let s=0;s<t.length;s++){let i=t[s];for(let o of[...i.slaveOrgs].reverse())if(o.ownerOrgs.has(i)){let r=t.indexOf(o);~r&&(t.splice(r,1),s--),t.splice(s+1,0,o)}}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())}#o(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}updateDebounced=ye(this.update,250);create({title:e,note:t,...s},i){return this.collection.insertOne({_id:ve(),title:e??"",note:t??"",owners:i?[i]:[],meta:{},...J(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(Oe(s?Z(i.ownerIds,s.slaveIds):[],Z(t.owners,[e,...ge(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 Y from"node:crypto";import{deleteProps as De,random as Q,removeAll as xe}from"@nesvet/n";var b={required:["_id","user","remoteAddress","isOnline","meta","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"},meta:{bsonType:"object"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var g=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 E=3600*24*7,Ie=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:E}]],_=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&&xe(e.required,b.required),e.properties&&De(e,Object.keys(b.properties)));let s={...b,...e,required:[...b.required,...e?.required??[]],properties:{...b.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{jsonSchema:s}),{expireAfterSeconds:E}),this.collection.ensureIndexes([...Ie,...t??[]]),await this.#e();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 g(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}}async#e(){await this.collection.bulkWrite([{updateMany:{filter:{meta:{$exists:!1}},update:{$set:{meta:{}}}}},{updateMany:{filter:{isOnline:!0},update:{$set:{isOnline:!1}}}}])}uid(){let e;do e=`${Y.randomBytes(Q(8,16)).toString("hex")}$${Y.randomBytes(Q(8,16)).toString("hex")}`;while(this.has(e));return e}load(e){new g(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,meta:{},createdAt:s,prolongedAt:s,expiresAt:new Date(s+E*1e3)},o=new g(this,i);return await this.collection.insertOne(i),o}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as Pe}from"insite-db";var V={required:["_id","type","size","ts","data","meta"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"},meta:{bsonType:"object"}},additionalProperties:!1};var D=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:V}),await this.#t())}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}async save(e,t,s){let i=Pe.createFromBase64(s.slice(s.indexOf(","))),o=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:i.length(),ts:o,data:i,meta:{}},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:o}})])}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 y={required:["_id","email","password","roles","name","org","job","meta","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"}]},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};import{_ids as ee,debounce as Re,empty as je,hasAny as Ue,removeOne as Te}from"@nesvet/n";var q=new Map,G=new Map,$e=process.env.INSITE_STATIC_URL??"http://localhost:8080",m=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:o,avatar:r,...n}){Object.assign(this,n);let a;s&&this.email!==s&&(this.#e.byEmail.delete(this.email),this.email=s,this.#e.byEmail.set(s,this),a=!0);let d,A;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(A=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(),d=!0),(a||d)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let L;if(i){this.ownRoleIds=i;let W=this.ownRoleIds.join(",");W!==q.get(this._id)&&(q.set(this._id,W),this.updateRoles(),L=!0)}let N;o!==void 0&&this.org?._id!==o&&(this.org?.users.delete(this),this.org=o&&this.#e.orgs.get(o)||this.#e.orgs.null,this.org.users.add(this),N=!0),r!==void 0&&this.avatar!==r&&(this.avatar=r,this.avatarUrl=r&&`${$e}/avatars/${this._id}-${r}.webp`),L||N?(this.updatePermissions(),A&&(this.#e.isSortRequired=!0),this.#e.isInited&&this.#e.updateDebounced()):A&&this.#e.sortDebounced()}updateRoles(){if(this.#e.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),je(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=ee(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 o of i.slaveOrgs)this.slaveOrgs.add(o),this.slaves.add(o),e.add(o._id)}for(let i of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let o of i.users)o!==this&&(Ue(this.slaveRoles,o.ownRoles)||!o.ownRoles.length)&&(this.slaveUsers.add(o),this.slaves.add(o),e.add(o._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
|
-
`);
|
|
1
|
+
function x(r){if(r instanceof Set){let e=[];for(let t of r)e.push(t._id);return e}return r.map(e=>e._id)}function de(r,...e){let t=0;for(let i of e)r.includes(i)||(r.push(i),t++);return t}function E(r,e,t){if(r&&e){if(e.includes(".")){let i=e.split("."),s=r;for(let o=0;o<i.length-1;o++){let n=i[o],l=s[n];s=l&&typeof l=="object"?l:s[n]={}}return s[i.at(-1)]=t}return r[e]=t}return null}function ue(r,...e){for(let t of e)for(let i in t)Object.hasOwn(t,i)&&E(r,i,t[i]);return r}function _(){}function m(r,e=0,t={}){let{leading:i=!1,trailing:s=!0}=t,{maxWait:o=1/0}=t,n,l,a,p,y,A,d,O,pe=async()=>{let v=Date.now();v>=a?(n=void 0,a=void 0,clearTimeout(l),typeof d=="function"&&await d(),g.resolve(O),g.promise.isResolved=!0,A=i):(clearTimeout(n),n=setTimeout(pe,a-v))},J=Number.isFinite(o)?()=>{d===S&&(d=!1),S(),l=setTimeout(J,o)}:null;async function S(){return O=await r.apply(p,y)}i&&typeof i=="boolean"&&(i=S),A=i,s&&typeof s=="boolean"&&(s=S),d=s;let g=Object.assign(function(...v){return y=v,p=this,a=Date.now()+e,d=s,g.promise.isResolved&&(g.promise=Object.assign(new Promise(De=>{g.resolve=De,typeof A=="function"&&(A(),A=!1,d===S&&(d=!1)),n||(n=setTimeout(pe,e),J&&(l=setTimeout(J,o)))}),{isResolved:!1})),g.promise},{callback:r,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:S,clear:async v=>{clearTimeout(n),n=void 0,clearTimeout(l),g.promise.isResolved=!0,g.resolve(v?await S():O)}});return g}m.noop=Object.assign(()=>{},{callback:_,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:_,clear:_});function me(r,e){if(r&&e){if(e.includes(".")){let t=e.split("."),i=r;for(let o=0;o<t.length-1;o++){let n=t[o],l=i[n];if(l&&typeof l=="object")i=l;else return!1}let s=t.at(-1);return s in i&&delete i[s]}return e in r&&delete r[e]}return!1}function u(r,e){if(r){for(let t of e)delete r[t];return r}return null}function k(r){for(let e in r)delete r[e];return r}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 f=class extends Error{constructor(e,t=null,i){super(e),t&&typeof t=="object"&&(i=t,t=null),this.tag=t,i&&Object.assign(this,i)}name="Err-or";tag};function X(r,e,t=!1){return t&&(e=e.filter(i=>r.has(i))),e.map(i=>r.get(i))}function G(r,e){if(e){if(e.includes(".")){let t=r;for(let i of e.split("."))if(t=t?.[i],t===void 0)break;return t}return r[e]}return r}function fe(r,e){for(let t of e)if(r.has(t))return!0;return!1}function he(r,e,t,i,s=!0){return Array.isArray(r)&&(r=r.length),typeof i!="string"&&(s=i??!0,i=t),(s?`${r}\xA0`:"")+he.raw(r,e,t,i)}he.raw=(r,e,t,i=t)=>{r=Math.abs(r);let s=r%10,o=r%100;return s===1&&o!==11?e:s>=2&&s<=4&&!(o>=12&&o<=15)?t:i};function L(...r){let e=[];if(r.length){let[t,...i]=r;e:for(let s of t){for(let o of i)if(o instanceof Set?!o.has(s):!o.includes(s))continue e;e.push(s)}}return e}function be(r,e){let t={};for(let i of e)i in r&&(t[i]=r[i]);return t}function N(r,e){return Math.floor(Math.random()*(e-r+1)+r)}function ge(r,e){return r.delete(e),r.add(e),r}function h(r,e){let t,i=0;for(let s of e)for(;(t=r.indexOf(s))>-1;)r.splice(t,1),i++;return i}function ye(r,e){let t=r.indexOf(e);return t>-1?(r.splice(t,1),!0):!1}function Ae(r,e){for(let t of[...r].sort(e))r.delete(t),r.add(t);return r}var U=new WeakMap,W=class extends Promise{constructor(e){let t,i;super((s,o)=>{t=s,i=o}),U.set(this,{resolve:t,reject:i}),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=U.get(this);t&&(t.resolve.call(this,e),U.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=U.get(this);t&&(t.reject.call(this,e),U.delete(this))}}};function Se(...r){return[...new Set(r.flat())]}function M(r,e){return r.filter(t=>!e.includes(t))}var Z=class extends f{constructor(e,t){typeof e=="object"&&(t=e,e=void 0),super("User lacks ability","lacksability",{...e&&{ability:e},...t})}name="AbilityError"};function Y(r){return typeof r=="object"}function Q(r){return typeof r=="number"}function V(r){return Array.isArray(r)}var xe=new Map,B=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(i,s,o){for(let n of i){if(xe.set(n,s),n.level=o,!s||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=s?`${s.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,o+1)}}).call(this,e,null,0)}#e=[];get(e,t){let i=e.split("."),s=t??super.get(i.shift());if(s&&i.length){for(let o of i)if(s=s?.abilities?.find(({_id:n,top:l})=>!l&&n===o),!s)break}return s}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:i})=>i===t)}getDefaultParam(e,t,i){(t===void 0||typeof t=="boolean")&&(i=t);let s=typeof e=="string"?this.getParamSchema(e,t):e;if(s)switch(s.type){case"number":return i?s.max??1/0:s.min??0;case"items":return i?s.items.map(({_id:o})=>o):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let i={};if(e.params)for(let s of e.params)i[s._id]=this.getDefaultParam(s,t);if(t&&e.abilities)for(let s of e.abilities)s.top||(i[s._id]=this.getDefaultAbility(s,t));return i}return!0}}getDefaultAbilities(e,t=!e){let i=(e?(Array.isArray(e)?e:[e]).map(o=>typeof o=="string"?this.get(o):o).filter(Boolean):[...this.values()]).sort((o,n)=>o.level-n.level),s=new Map;for(let o of i)(function n(l){let a=xe.get(l);a&&(n(a),s.has(a)||s.set(a,!1))})(o),t?function n(l){if(s.has(l)||s.set(l,!0),l.abilities)for(let a of l.abilities)a.top&&n(a)}(o):s.has(o)||s.set(o,!1);return ue({},Object.fromEntries([...s].map(([o,n])=>[o.longId,this.getDefaultAbility(o,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(i,s){for(let o=0;o<i.length;o++){let n=i[o],l=n.top?e[n._id]:s[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:y})=>p.includes(y))}}n.abilities&&(t(n.abilities,l),n.abilities.length||delete n.abilities)}else i.splice(o--,1)}return i}(structuredClone(this.#e),e)}getParam(e,t,i){if(this.getParamSchema(t,i)){let s=G(e,`${t}.${i}`);return this.isParamFits(t,i,s)?s:this.getDefaultParam(t,i)}}setParam(e,t,i,s){let o=this.getParamSchema(t,i);if(!o)throw new Error(`No such ability param: ${t}.${i}`);return E(e,`${t}.${i}`,this.adjustParam(o,s)),e}isParamFits(e,t,i,s){if(i!==void 0){let o=this.getParamSchema(e,t);if(o)switch(o.type){case"number":return Q(i)&&(o.min===void 0||i>=o.min)&&(s===void 0?o.max===void 0||i<=o.max:i<=s);case"items":return V(i)&&i.length===new Set(i).size&&(s===void 0?i.every(n=>o.items.find(({_id:l})=>l===n)):i.every(n=>s.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(i=>i._id),t):[]}}adjust(e,t){let i={};for(let[s,o]of Object.entries(e)){let n=this.get(s,t);if(n)if(n.params||n.abilities){let l={};if(n.params)if(Y(o))for(let a of n.params)l[a._id]=this.adjustParam(a,o[a._id]);else for(let a of n.params)l[a._id]=this.getDefaultParam(a);n.abilities&&Y(o)&&Object.assign(l,this.adjust(be(o,n.abilities.filter(a=>!a.top).map(a=>a._id)),n)),i[s]=l}else i[s]=!0}return Object.assign(k(e),i)}merge(e,t,i){i||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[s,o]of Object.entries(t)){let n=this.get(s,i);if(n&&n.isInheritable!==!1)if(s in e&&(n.params||n.abilities)){let l=e[s],a=o;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":de(l[p._id],...a[p._id])}}n.abilities&&this.merge(l,a,n)}else e[s]=o}return e}hasAbility(e,t){return!!G(e,t)}setAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(i)),e}unsetAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return function s(o){if(me(e,o.longId),o.abilities)for(let n of o.abilities)s(n)}(i),e}};var ee=class extends f{constructor(e,t){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e],...t})}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:i,title:s,...o},n){if(Object.assign(this,o),t&&(this.ownInvolveIds=t),i&&(this.ownAbilities=i),s!==void 0&&(this.title=s,this.displayTitle=s||this._id),t||i){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","meta","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},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var Pe=[[{involves:1}]];function we(){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:i,...s}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new P(this,{...i,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",meta:{},createdAt:Date.now()}),this.initOptions=s}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&&h(e.required,I.required),e.properties&&u(e,Object.keys(I.properties)));let i={...I,...e,required:[...I.required,...e?.required??[]],properties:{...I.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{jsonSchema:i}),{deleteOne:we,deleteMany:we}),this.collection.ensureIndexes([...Pe,...t??[]]),await this.#t();for(let s of await this.collection.find().toArray())this.abilities.adjust(s.abilities)&&await this.collection.updateOne({_id:s._id},{$set:{abilities:s.abilities}}),this.load(s);this.update(),this.collection.changeListeners.add(s=>{switch(s.operationType){case"insert":{let o=new P(this,s.fullDocument);this.users.emit("roles-role-update",o,s);break}case"replace":this.get(s.documentKey._id)?.update(s.fullDocument,s);break;case"update":this.get(s.documentKey._id)?.update(s.updateDescription.updatedFields,s);break;case"delete":this.get(s.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,s)}}),delete this.initOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}load(e){new P(this,e)}resolve(e,t){t=[e,...t];for(let i of e.ownInvolveIds){let s=this.get(i);if(s){for(let o of t)ge(o.involves,s),this.abilities.merge(o.inheritedAbilities,s.abilities);s!==e&&this.resolve(s,t)}}}sorted=[];#i(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 s of e)s!==this.root&&!e.some(o=>o.ownInvolveIds.includes(s._id))&&this.root.ownInvolveIds.push(s._id),s.involves.clear(),s.abilities=structuredClone(s.ownAbilities),s.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let s of e)s.ownInvolves=X(this,s.ownInvolveIds,!0).sort(this.#i).reverse();let t=[this.root];for(let s=0;s<t.length;s++){let o=t[s];for(let n of o.ownInvolves){let l=t.indexOf(n);~l&&(t.splice(l,1),s--),t.splice(s+1,0,n)}}let i=0;for(let s of t)this.abilities.merge(s.abilities,s.inheritedAbilities),s._o=i++;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:i,description:s,...o}){return this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:i??"",description:s??"",meta:{},...u(o,["abilities"]),createdAt:Date.now()})}async updateRole(e,t){let i=this.get(e);if(!i)return!1;if(t.involves){h(t.involves,[e]);for(let s of t.involves)this.get(s)?.involves.has(i)&&h(t.involves,[s]);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)),i=[];for(let s of t)t.every(o=>o===s||!o.involves.has(s))&&i.push(s._id);return i}async setAbility(e,t,i){let s=this.get(e);return s?(await this.collection.updateOne({_id:e},{$set:{abilities:i?this.abilities.setAbility(s.ownAbilities,t):this.abilities.unsetAbility(s.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,i,s){let o=this.get(e);return o?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(o.ownAbilities,t,i,s)}}),!0):!1}};var ie=class extends f{constructor(e){super("Unauthorized","unauthorized",e)}name="UnauthorizedError"},se=class extends f{constructor(e,t,i){switch(arguments.length){case 1:i=e,e=void 0;break;case 2:i=t,t=void 0}super("Insubordination attempt","subordination",{...e&&{type:e},...t&&{ids:Array.isArray(t)?t:[t]},...i})}name="SubordinationError"},oe=class extends f{constructor(e){super("Insufficient permissions","permissions",e)}name="PermissionError"};import*as C from"argon2";import Ue from"eventemitter3";import{newObjectIdString as Me}from"insite-db";import{newObjectIdString as Ie}from"insite-db";var re=new Map,b=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:i,...s},o){if(Object.assign(this,s),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),i){this.ownerIds=i;let n=this.ownerIds.join(",");n!==re.get(this._id)&&(re.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,o))}}delete(){this.orgs.delete(this._id),re.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}};var j={required:["_id","title","note","owners","meta","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},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var je=[[{owners:1}]];function Oe(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var z=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:i}=this.preinitOptions;e&&(e.required&&h(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("orgs",{jsonSchema:s}),{deleteOne:Oe,deleteMany:Oe}),this.collection.ensureIndexes([...je,...t??[]]),this.null=Object.assign(new b(this,{...i,_id:"",title:"",note:"",owners:[],meta:{},createdAt:Date.now()}),{_id:null,ownerIds:new q,ownerOrgs:new D,ownerUsers:new D,slaveOrgs:new D}),await this.#t();for(let o of await this.collection.find().toArray())this.load(o);delete this.preinitOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#i=!1;init(){this.#i||(this.#i=!0,this.update(),this.collection.changeListeners.add(e=>{switch(e.operationType){case"insert":{let t=new b(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 b(this,e)}#s(e,t){t=[e,...t];for(let i of e.ownerOrgs){this.#s(i,t);for(let s of t)i.slaveOrgs.add(s)}}sorted=[];update(){let e=[...this.values()],t=[];for(let i of e){i.ownerOrgs.clear(),i.ownerUsers.clear(),i.slaveOrgs.clear();for(let s of i.ownerIds){let o=this.get(s);if(o)i.ownerOrgs.add(o);else{let n=this.users.get(s);n&&i.ownerUsers.add(n)}}!i.ownerOrgs.size&&i._id&&t.push(i)}for(let i of e)e.some(s=>s.ownerOrgs.has(i))||this.#s(i,[]);t.sort(this.#o);for(let i of e)Ae(i.slaveOrgs,this.#o);for(let i=0;i<t.length;i++){let s=t[i];for(let o of[...s.slaveOrgs].reverse())if(o.ownerOrgs.has(s)){let n=t.indexOf(o);~n&&(t.splice(n,1),i--),t.splice(i+1,0,o)}}for(let i=0,{length:s}=t;i<s;)t[i]._o=i++;this.sorted=t,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}#o(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,...i},s){return this.collection.insertOne({_id:Ie(),title:e??"",note:t??"",owners:s?[s]:[],meta:{},...u(i,["_id","owners"]),createdAt:Date.now()})}async updateOrg(e,t,i){let s=this.get(e);return s?(t.owners&&(t.owners=this.users.sortIds(Se(i?M(s.ownerIds,i.slaveIds):[],M(t.owners,[e,...x(s.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 i of this.replaceHandlers)await i(e,t)}};import ve from"node:crypto";var R={required:["_id","user","remoteAddress","isOnline","meta","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"},meta:{bsonType:"object"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var T=class{constructor(e,t){let i=e.users.get(t.user);i?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=i,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:i,...s}){i!==void 0&&this.isOnline!==i&&(this.isOnline=i,this.#e.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,s)}prolong({_id:e,user:t,...i}){let s=Date.now();return i.prolongedAt=s,i.expiresAt=new Date(s+this.#e.collection.expireAfterSeconds*1e3),this.update(i),this.#e.collection.updateOne({_id:this._id},{$set:i})}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 ne=3600*24*7,Re=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:ne}]],K=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&&h(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("sessions",{jsonSchema:i}),{expireAfterSeconds:ne}),this.collection.ensureIndexes([...Re,...t??[]]),await this.#e();for(let s of await this.collection.find().toArray())this.load(s);this.collection.changeListeners.add(s=>{switch(s.operationType){case"insert":this.has(s.documentKey._id)||new T(this,s.fullDocument),this.users.get(s.fullDocument.user)?.trimSessions();break;case"replace":this.get(s.documentKey._id)?.update(s.fullDocument);break;case"update":this.get(s.documentKey._id)?.update(s.updateDescription.updatedFields);break;case"delete":this.get(s.documentKey._id)?.delete()}}),delete this.initOptions}}async#e(){await this.collection.bulkWrite([{updateMany:{filter:{meta:{$exists:!1}},update:{$set:{meta:{}}}}},{updateMany:{filter:{isOnline:!0},update:{$set:{isOnline:!1}}}}])}uid(){let e;do e=`${ve.randomBytes(N(8,16)).toString("hex")}$${ve.randomBytes(N(8,16)).toString("hex")}`;while(this.has(e));return e}load(e){new T(this,e)}async create(e,t){let i=Date.now(),s={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,meta:{},createdAt:i,prolongedAt:i,expiresAt:new Date(i+ne*1e3)},o=new T(this,s);return await this.collection.insertOne(s),o}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as Te}from"insite-db";var _e={required:["_id","type","size","ts","data","meta"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"},meta:{bsonType:"object"}},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:_e}),await this.#t())}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}async save(e,t,i){let s=Te.createFromBase64(i.slice(i.indexOf(","))),o=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:s.length(),ts:o,data:s,meta:{}},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:o}})])}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 $={required:["_id","email","password","roles","name","org","job","meta","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"}]},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var le=new Map,ae=new Map,$e=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:i,roles:s,org:o,avatar:n,...l}){Object.assign(this,l);let a;i&&this.email!==i&&(this.#e.byEmail.delete(this.email),this.email=i,this.#e.byEmail.set(i,this),a=!0);let p,y;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(y=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 A;if(s){this.ownRoleIds=s;let O=this.ownRoleIds.join(",");O!==le.get(this._id)&&(le.set(this._id,O),this.updateRoles(),A=!0)}let d;o!==void 0&&this.org?._id!==o&&(this.org?.users.delete(this),this.org=o&&this.#e.orgs.get(o)||this.#e.orgs.null,this.org.users.add(this),d=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${$e}/avatars/${this._id}-${n}.webp`),A||d?(this.updatePermissions(),y&&(this.#e.isSortRequired=!0),this.#e.isInited&&this.#e.updateDebounced()):y&&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 i of t.involves)this.roles.add(i),this.slaveRoles.add(i);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 s of this.#e.orgs.sorted)if((s.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(s)){this.slaveOrgs.add(s),this.slaves.add(s),e.add(s._id);for(let o of s.slaveOrgs)this.slaveOrgs.add(o),this.slaves.add(o),e.add(o._id)}for(let s of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let o of s.users)o!==this&&(fe(this.slaveRoles,o.ownRoles)||!o.ownRoles.length)&&(this.slaveUsers.add(o),this.slaves.add(o),e.add(o._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let s of this.org.slaveOrgs)this.slaveOrgs.has(s)||t.push(s._id)}this.permissiveIds=[...t,this._id,...e];let i=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
|
|
3
|
+
`);i!==ae.get(this._id)&&(ae.set(this._id,i),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,i)=>t.expiresAt.valueOf()-i.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),ye(this.#e.sorted,this),le.delete(this._id),ae.delete(this._id),this.#e.replace(this._id),this.#e.updateDebounced()}};var Ce=[[{email:1},{unique:!0}],[{org:1}]],ce=class r extends Map{constructor(e,t){super();let i=new Ue;this._events=i._events,this._eventsCount=i._eventsCount,this.emit=i.emit,this.on=i.on,this.once=i.once,this.addListener=i.addListener,this.off=i.off,this.removeListener=i.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:i}=this.initOptions;t&&(t.required&&h(t.required,$.required),t.properties&&u(t,Object.keys($.properties)));let s={...$,...t,required:[...$.required,...t?.required??[]],properties:{...$.properties,...t?.properties}};this.collection=await this.collections.ensure("users",{jsonSchema:s}),this.collection.ensureIndexes([...Ce,...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",...i,roles:["root"],org:null,meta:{}}),await this.#t();for(let o of await this.collection.find().toArray())this.load(o)}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{roles:e,orgs:t,sessions:i}=this.initOptions;this.roles=new F(this,e),this.orgs=new z(this,t),this.sessions=new K(this,i),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(s=>{switch(s.operationType){case"insert":new w(this,s.fullDocument);break;case"replace":this.get(s.documentKey._id)?.update(s.fullDocument);break;case"update":this.get(s.documentKey._id)?.update(s.updateDescription.updatedFields);break;case"delete":this.get(s.documentKey._id)?.delete()}}),await this.sessions.init(),delete this.initOptions,this.#i.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);#i=new W;whenReady(){return this.#i}async create({email:e,password:t,roles:i,name:s,org:o,job:n,...l}){if(this.byEmail.has(e))throw new Error("User exists");return await this.collection.insertOne({_id:Me(),email:e,password:await C.hash(t),roles:this.isInited?this.roles.cleanUpIds(i):i,name:{first:s.first??"",middle:s.middle??"",last:s.last??""},org:o??null,job:n??"",meta:{},...u(l,["_id"]),createdAt:Date.now()}),!0}async updateUser(e,t,i){let s=this.get(e);return s?(t.roles&&(t.roles=s.isRoot?["root"]:this.roles.cleanUpIds(i?M(s.ownRoleIds,i.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,i){let s=this.byEmail.get(e);if(!s)throw new Error("usernotfound");if(!await C.verify(s.password,t))throw new Error("incorrectpassword");if(!s.abilities.login)throw new Error("userisnotabletologin");return this.sessions.create(s,i)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}#s(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 b&&t instanceof b?e.title>t.title?1:e.title<t.title?-1:0:e instanceof b?-1:1}sortIds(e){return x(e.map(t=>this.get(t)||this.orgs.get(t)).filter(Boolean).sort(this.#s))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}async deleteUser(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}static init(e,t){return new r(e,t).whenReady()}};export{Z as AbilityError,oe as PermissionError,ee as RolesError,se as SubordinationError,ie as UnauthorizedError,ce as Users};
|
|
4
4
|
//# sourceMappingURL=index.js.map
|