@ionite/redis-core 0.0.27-beta.20261102.2 → 0.0.27
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 +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -173,7 +173,7 @@ if D==0 then
|
|
|
173
173
|
else
|
|
174
174
|
redis.call('SADD',KEYS[2],subjectMember)
|
|
175
175
|
end
|
|
176
|
-
return 'ok'`;function D(e,t){return`${t}:${e}`}function V(e){return e&&e.length>0?e:q}function Z(e){return JSON.stringify([e.subject,e.targetType,e.target,e.rToken])}function j(e){let t;try{t=JSON.parse(e)}catch{t=[]}let[s,r,i,a]=Array.isArray(t)?t:[];return{subject:s??"",targetType:r??"permission",target:i??"",rToken:a??q}}class Ae{constructor(e){this.redis=e.redis,this.prefix=x(e,"access-index"),this.log=S(e)}key(...e){return f(this.prefix,...e)}subjectKeyPart(e){let t=e.indexOf(":");if(t<=0)return h(e);return`${e.slice(0,t)}:${h(e.slice(t+1))}`}hasKey(e,t,s,r){return this.key("idx:has",this.subjectKeyPart(e),t,h(s),h(r))}anyKey(e,t,s){return this.key("idx:any",this.subjectKeyPart(e),t,h(s))}edgeRootsKey(e,t,s,r){return this.key("idx:er",this.subjectKeyPart(e),t,h(s),h(r))}tripleKey(e,t,s){return this.key("idx:tr",this.subjectKeyPart(e),t,h(s))}rootKey(e){return this.key("idx:root",h(e))}subjectKey(e){return this.key("idx:subj",this.subjectKeyPart(e))}subjectsKey(){return this.key("idx:subjects")}disabledKey(e){return this.key("idx:disabled",this.subjectKeyPart(e))}async has(e,t,s,r,i){O(i);let a=P(e),n=P(s);if(!a||!n)return{allow:!1};let o=D(a,i);if(r===void 0){let[p,E]=await this.redis.mget([this.disabledKey(o),this.anyKey(o,t,n)]);if(p!=null)return{allow:!1,metadata:{reason:"subject_disabled"}};return E!=null?this.allow(a,i,t,n,void 0):{allow:!1}}let d=P(r),l=await this.redis.mget([this.disabledKey(o),this.hasKey(o,t,n,V(d)),this.hasKey(o,t,n,q)]);if(l[0]!=null)return{allow:!1,metadata:{reason:"subject_disabled"}};if(l[1]!=null)return this.allow(a,i,t,n,d);if(l[2]!=null)return this.allow(a,i,t,n,void 0);return{allow:!1}}async hasGroup(e,t,s,r){return this.has(e,"group",t,s,r)}async hasRole(e,t,s,r){return this.has(e,"role",t,s,r)}async hasPermission(e,t,s,r){return this.has(e,"permission",t,s,r)}async hasAny(e,t,s){if(t.length===0)return{allow:!1};this.warnLargeCheck("redis.access_index.has_any",t.length);let r=await this.evaluateTargets(e,t,s);for(let i of r)if(i.allow)return i;return{allow:!1}}async hasAll(e,t,s){if(t.length===0){let a=P(e);if(a){if(await this.redis.get(this.disabledKey(D(a,s)))!=null)return{allow:!1,metadata:{reason:"subject_disabled"}}}return{allow:!0}}this.warnLargeCheck("redis.access_index.has_all",t.length);let r=await this.evaluateTargets(e,t,s),i=[];for(let a of r){if(!a.allow)return{allow:!1,matched:i};if(a.matched)i.push(...a.matched)}return{allow:!0,matched:i}}async evaluateTargets(e,t,s){let r=P(e);if(!r)return t.map(()=>({allow:!1}));let i=D(r,s),a=[this.disabledKey(i)],n=t.map((d)=>{let l=P(d.target);if(!l)return{kind:"invalid"};if(d.resource===void 0){let T=a.push(this.anyKey(i,d.targetType,l))-1;return{kind:"any",targetType:d.targetType,targetId:l,idx:T}}let p=P(d.resource),E=a.push(this.hasKey(i,d.targetType,l,V(p)))-1,y=a.push(this.hasKey(i,d.targetType,l,q))-1;return{kind:"resource",targetType:d.targetType,targetId:l,resourceId:p,idxResource:E,idxApp:y}}),o=await this.redis.mget(a);if(o[0]!=null)return t.map(()=>({allow:!1,metadata:{reason:"subject_disabled"}}));return n.map((d)=>{if(d.kind==="invalid")return{allow:!1};if(d.kind==="any")return o[d.idx]!=null?this.allow(r,s,d.targetType,d.targetId,void 0):{allow:!1};if(o[d.idxResource]!=null)return this.allow(r,s,d.targetType,d.targetId,d.resourceId);if(o[d.idxApp]!=null)return this.allow(r,s,d.targetType,d.targetId,void 0);return{allow:!1}})}edgeKeys(e){return[this.edgeRootsKey(e.subject,e.targetType,e.target,e.rToken),this.hasKey(e.subject,e.targetType,e.target,e.rToken),this.tripleKey(e.subject,e.targetType,e.target),this.anyKey(e.subject,e.targetType,e.target),this.subjectKey(e.subject)]}async materialize(e,t){let s=new Map;for(let n of t){let o=P(n.subject),d=P(n.target);if(!o||!d)continue;O(n.subjectType,"Effective edge subjectType");let l=D(o,n.subjectType),p=V(n.resource),E={subject:l,targetType:n.targetType,target:d,rToken:p};s.set(Z(E),E)}let r=new Set(await this.redis.smembers(this.rootKey(e))),i=[];for(let[n,o]of s)if(!r.has(n))i.push({encoded:n,d:o});let a=[];for(let n of r)if(!s.has(n))a.push({encoded:n,d:j(n)});if(i.length===0&&a.length===0)return;if(A(this.redis)){let n=[this.rootKey(e),this.subjectsKey()],o=[e,String(i.length),String(a.length)];for(let{encoded:d,d:l}of i)n.push(...this.edgeKeys(l)),o.push(d,l.rToken,l.subject);for(let{encoded:d,d:l}of a)n.push(...this.edgeKeys(l)),o.push(d,l.rToken);await this.redis.runScript(ct,n,o);return}for(let{encoded:n,d:o}of i)await this.redis.sadd(this.edgeRootsKey(o.subject,o.targetType,o.target,o.rToken),e),await this.redis.set(this.hasKey(o.subject,o.targetType,o.target,o.rToken),"1"),await this.redis.sadd(this.tripleKey(o.subject,o.targetType,o.target),o.rToken),await this.redis.set(this.anyKey(o.subject,o.targetType,o.target),"1"),await this.redis.sadd(this.rootKey(e),n),await this.redis.sadd(this.subjectKey(o.subject),n),await this.redis.sadd(this.subjectsKey(),o.subject);for(let{encoded:n,d:o}of a)await this.dropRootFromEdge(e,o.subject,o.targetType,o.target,o.rToken),await this.redis.srem(this.rootKey(e),n)}async replaceSubject(e,t,s){if(!A(this.redis))throw Error("RedisAccessIndex.replaceSubject requires an adapter with atomic runScript support.");let r=P(e);if(!r)return;let i=D(r,t),a=[];for(let y of s){let T=P(y.subject);O(y.subjectType,"Effective edge subjectType");let I=y.subjectType;if(T!==r||I!==t)throw Error(`AccessIndex.replaceSubject received an edge for ${I}:${T}; expected ${i}.`);let v=P(y.target);if(!v)continue;let b={subject:i,targetType:y.targetType,target:v,rToken:V(y.resource)};a.push({rootId:y.rootId,encoded:Z(b),d:b})}let o=(await this.redis.smembers(this.subjectKey(i))).map(j),d=await Promise.all(o.map((y)=>this.redis.smembers(this.edgeRootsKey(y.subject,y.targetType,y.target,y.rToken)))),l=[...new Set(d.flat())],p=[this.subjectKey(i),this.subjectsKey()];for(let y of o){let[T,I,v,b]=this.edgeKeys(y);p.push(T,I,v,b)}for(let y of l)p.push(this.rootKey(y));for(let y of a){let[T,I,v,b]=this.edgeKeys(y.d);p.push(this.rootKey(y.rootId),T,I,v,b)}let E=[i,String(o.length),String(l.length),String(a.length)];for(let y of a)E.push(y.rootId,y.encoded,y.d.rToken);await this.redis.runScript(gt,p,E)}async removeByRoot(e){let t=this.rootKey(e),s=await this.redis.smembers(t);if(s.length===0){await this.redis.del(t);return}if(A(this.redis)){let r=[t],i=[e,String(s.length)];for(let a of s){let n=j(a);r.push(...this.edgeKeys(n)),i.push(a,n.rToken)}await this.redis.runScript(lt,r,i);return}for(let r of s){let{subject:i,targetType:a,target:n,rToken:o}=j(r);await this.dropRootFromEdge(e,i,a,n,o)}await this.redis.del(t)}async listSubjects(){let e=await this.redis.smembers(this.subjectsKey()),t=[];for(let s of e){let r=s.indexOf(":");if(r<=0)throw Error(`AccessIndex subject key "${s}" is missing a subjectType prefix.`);let i=s.slice(0,r);O(i,"AccessIndex subject key subjectType"),t.push({subjectType:i,subject:s.slice(r+1)})}return t}async setSubjectDisabled(e,t,s){let r=P(e);if(!r)return;let i=this.disabledKey(D(r,t));if(s)await this.redis.set(i,"1");else await this.redis.del(i)}async isSubjectDisabled(e,t){O(t);let s=P(e);if(!s)return!1;return await this.redis.get(this.disabledKey(D(s,t)))!=null}async clear(e,t){if(e===void 0){let i=await this.redis.smembers(this.subjectsKey());for(let a of i)await this.clearSubject(a);await this.redis.del(this.subjectsKey());return}O(t);let s=P(e);if(!s)return;let r=D(s,t);await this.clearSubject(r),await this.redis.srem(this.subjectsKey(),r)}async clearSubject(e){let t=this.subjectKey(e),s=await this.redis.smembers(t);if(s.length===0){await this.redis.del(t);return}if(A(this.redis)){let r=[t];for(let a of s){let{targetType:n,target:o,rToken:d}=j(a);r.push(this.edgeRootsKey(e,n,o,d),this.hasKey(e,n,o,d),this.tripleKey(e,n,o),this.anyKey(e,n,o))}let i=dt(await this.redis.runScript(ut,r,[String(s.length)]));if(i.length>0)await this.redis.runScript(pt,i.map((a)=>this.rootKey(a)),[]);return}for(let r of s){let{targetType:i,target:a,rToken:n}=j(r),o=this.edgeRootsKey(e,i,a,n),d=await this.redis.smembers(o);for(let p of d)await this.redis.srem(this.rootKey(p),r);if(await this.redis.del(o),await this.redis.del(this.hasKey(e,i,a,n)),await this.redis.srem(this.tripleKey(e,i,a),n),(await this.redis.smembers(this.tripleKey(e,i,a))).length===0)await this.redis.del(this.tripleKey(e,i,a)),await this.redis.del(this.anyKey(e,i,a))}await this.redis.del(t)}async dropRootFromEdge(e,t,s,r,i){let a=this.edgeRootsKey(t,s,r,i);if(await this.redis.srem(a,e),(await this.redis.smembers(a)).length>0)return;await this.redis.del(a),await this.redis.del(this.hasKey(t,s,r,i));let o=Z({subject:t,targetType:s,target:r,rToken:i});if(await this.redis.srem(this.subjectKey(t),o),await this.redis.srem(this.tripleKey(t,s,r),i),(await this.redis.smembers(this.tripleKey(t,s,r))).length===0)await this.redis.del(this.tripleKey(t,s,r)),await this.redis.del(this.anyKey(t,s,r))}allow(e,t,s,r,i){return{allow:!0,matched:[{subject:e,subjectType:t,targetType:s,target:r,resources:i?[i]:void 0}]}}warnLargeCheck(e,t){if(t<=Re)return;this.log.warn("Redis access index check received a large bounded target set; issuing per-target reads.",{"ion.operation":e,"ion.outcome":"degraded",count:t,threshold:Re})}}var ht=512;async function yt(e,t,s=512){if(e.length===0)return[];let r=s>0?s:512,i=[];for(let a=0;a<e.length;a+=r){let n=await t(e.slice(a,a+r));for(let o of n)i.push(o??null)}return i}import{list as ft,StoreConflictError as mt}from"@ionite/core";var St="customer:ids",wt="customer:name:",xt="customer:external:";function kt(e){let t=e.createdAt??new Date,s=e.updatedAt??t,r={...e,createdAt:t.toISOString(),updatedAt:s.toISOString()};if(r.ciam&&typeof r.ciam==="object"&&r.ciam!==null){let i=r.ciam;if(i.expires instanceof Date)i.expires=i.expires.toISOString()}return JSON.stringify(r)}function Q(e,t){let s=m(e,{store:"customer",log:t});if(s===void 0)return;if(s.ciam&&typeof s.ciam==="object"&&s.ciam!==null){let r=s.ciam;if(typeof r.expires==="string")r.expires=new Date(r.expires)}return{...s,createdAt:typeof s.createdAt==="string"?new Date(s.createdAt):void 0,updatedAt:typeof s.updatedAt==="string"?new Date(s.updatedAt):void 0}}class Ee{constructor(e){this.redis=e.redis,this.prefix=x(e,"customer-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("customer",h(e))}idsSetKey(){return this.key(St)}nameIndexKey(e){return this.key(wt+h(e))}externalIdIndexKey(e){return this.key(xt+h(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return Q(t,this.log)}async lookup(e){if(e.id){let t=await this.get(e.id);if(t)return t}if(e.userName){let t=await this.redis.get(this.nameIndexKey(e.userName.toLowerCase()));if(t!=null)return this.get(t)}if(e.externalId)return this.getByExternalId(e.externalId);return}async getByExternalId(e){let t=await this.redis.get(this.externalIdIndexKey(e));if(t==null)return;return this.get(t)}async upsert(e){let t=e.id?.trim()||crypto.randomUUID(),s={...e,id:t},r=this.entityKey(t),i=await this.redis.get(r),a=i!=null?Q(i,this.log)??null:null,n=s.userName?.toLowerCase(),o=a?.userName?.toLowerCase(),d=s.externalId,l=a?.externalId,p=new w;if(n)p.claimUnique(this.nameIndexKey(n),t);if(d)p.claimUnique(this.externalIdIndexKey(d),t);if(o&&o!==n)p.del(this.nameIndexKey(o));if(l&&l!==d)p.del(this.externalIdIndexKey(l));if(p.set(r,kt(s)),n)p.set(this.nameIndexKey(n),t);if(d)p.set(this.externalIdIndexKey(d),t);if(p.sadd(this.idsSetKey(),t),await p.exec(this.redis)==="conflict")throw new mt(`userName "${s.userName}" is already in use`,"unique_violation","userName");return s}async delete(e){let t=await this.get(e);if(t==null)return 0;let s=new w;if(s.del(this.entityKey(e)),t.userName)s.del(this.nameIndexKey(t.userName.toLowerCase()));if(t.externalId)s.del(this.externalIdIndexKey(t.externalId));return s.srem(this.idsSetKey(),e),await s.exec(this.redis),1}async list(e){let t=C(e),s=(await this.redis.smembers(this.idsSetKey())).sort();if(s.length===0)return ft(0,[],t.start??0,t.limit);let r=s.map((n)=>this.entityKey(n)),a=(await this.redis.mget(r)).filter((n)=>n!=null).map((n)=>Q(n,this.log)).filter((n)=>n!=null);return R(a,t)}}import{StoreConflictError as Tt}from"@ionite/core";var Rt="delegate:ids";function be(e){let t=e.createdAt??new Date,s=e.updatedAt??t;return JSON.stringify({...e,createdAt:t.toISOString(),updatedAt:s.toISOString(),expiresAt:e.expiresAt?.toISOString(),previousTokenHashExpiresAt:e.previousTokenHashExpiresAt?.toISOString(),lastUsedAt:e.lastUsedAt?.toISOString()})}function ee(e,t){let s=m(e,{store:"delegate",log:t});if(s===void 0)return;let r=(i)=>typeof i==="string"?new Date(i):void 0;return{...s,createdAt:r(s.createdAt),updatedAt:r(s.updatedAt),expiresAt:r(s.expiresAt),previousTokenHashExpiresAt:r(s.previousTokenHashExpiresAt),lastUsedAt:r(s.lastUsedAt)}}class ve{constructor(e){this.redis=e.redis,this.prefix=x(e,"delegate-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("delegate",h(e))}tokenHashKey(e){return this.key("delegate:token",h(e))}externalIdKey(e){return this.key("delegate:external",h(e))}idsSetKey(){return this.key(Rt)}async get(e){let t=await this.redis.get(this.entityKey(e));return t==null?void 0:ee(t,this.log)}async lookup(e){return await this.get(e.id)??(e.externalId?this.getByExternalId(e.externalId):void 0)}async getByTokenHash(e){let t=await this.redis.get(this.tokenHashKey(e));if(!t)return;let s=await this.get(t);if(!s)return;if(s.tokenHash===e)return s;if(s.previousTokenHash===e&&s.previousTokenHashExpiresAt&&s.previousTokenHashExpiresAt.getTime()>Date.now())return s;return}async getByExternalId(e){let t=await this.redis.get(this.externalIdKey(e));return t?this.get(t):void 0}async listByOwner(e,t,s){let r=await this.all();return R(r.filter((i)=>i.owner.id===e&&i.owner.type===t),C(s))}async upsert(e){let t=e.id?.trim()||crypto.randomUUID(),s=await this.get(t),r=new Date,i={...e,id:t,createdAt:s?.createdAt??e.createdAt??r,updatedAt:r},a=new w;if(a.claimUnique(this.tokenHashKey(i.tokenHash),t),i.previousTokenHash)a.claimUnique(this.tokenHashKey(i.previousTokenHash),t);if(i.externalId)a.claimUnique(this.externalIdKey(i.externalId),t);if(s?.tokenHash&&s.tokenHash!==i.tokenHash)a.del(this.tokenHashKey(s.tokenHash));if(s?.previousTokenHash&&s.previousTokenHash!==i.previousTokenHash)a.del(this.tokenHashKey(s.previousTokenHash));if(s?.externalId&&s.externalId!==i.externalId)a.del(this.externalIdKey(s.externalId));if(a.set(this.entityKey(t),be(i)),a.set(this.tokenHashKey(i.tokenHash),t),i.previousTokenHash)a.set(this.tokenHashKey(i.previousTokenHash),t);if(i.externalId)a.set(this.externalIdKey(i.externalId),t);if(a.sadd(this.idsSetKey(),t),await a.exec(this.redis)==="conflict")throw new Tt("Delegate token hash or externalId is already in use","unique_violation");return i}async delete(e){let t=await this.get(e);if(!t)return 0;let s=new w;if(s.del(this.entityKey(e)),s.del(this.tokenHashKey(t.tokenHash)),t.previousTokenHash)s.del(this.tokenHashKey(t.previousTokenHash));if(t.externalId)s.del(this.externalIdKey(t.externalId));return s.srem(this.idsSetKey(),e),await s.exec(this.redis),1}async list(e){return R(await this.all(),C(e))}async touch(e,t){let s=this.entityKey(e);for(let r=0;r<3;r+=1){let i=await this.redis.get(s);if(i==null)return;let a=ee(i,this.log);if(!a)return;let n=be({...a,lastUsedAt:t}),o=await G(this.redis,s,i,n);if(o==="ok"||o==="missing")return;if(o==="unsupported"){await this.redis.set(s,n);return}}this.log.warn("Delegate usage timestamp update lost a concurrent race",{"ion.operation":"delegate.touch","ion.outcome":"skipped",delegateId:e})}async all(){let e=(await this.redis.smembers(this.idsSetKey())).sort();if(e.length===0)return[];return(await this.redis.mget(e.map((s)=>this.entityKey(s)))).filter((s)=>s!=null).map((s)=>ee(s,this.log)).filter((s)=>s!==void 0)}}import{createHash as At}from"node:crypto";function Ie(e){return At("sha1").update(e,"utf8").digest("hex")}function Et(e){return(e instanceof Error?e.message:String(e)).includes("NOSCRIPT")}function bt(e){let t=new Map;return async(s,r,i)=>{let a=t.get(s);if(!a)a=Ie(s),t.set(s,a);try{return await e.evalsha(a,r,i)}catch(n){if(Et(n))return e.eval(s,r,i);throw n}}}function Ke(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function vt(e){let t=Ke(e.clientOptions)?{...e.clientOptions}:Ke(e)?{...e}:{};return delete t.redisUrl,delete t.clientOptions,{redisUrl:(typeof e.redisUrl==="string"?e.redisUrl.trim():"")||void 0,clientOptions:t}}var It=500;function Kt(e){return e.replace(/[*?[\]\\]/g,"\\$&")}async function*U(e,t){if(!e.scan)throw Error("Redis adapter does not support scan; keyspace teardown needs an adapter that implements it.");let s=`${Kt(t)}*`,r="0";do{let i=await e.scan(r,s,It);if(r=i.cursor,i.keys.length>0)yield i.keys}while(r!=="0")}async function Pt(e,t){let s=0;for await(let r of U(e,N(t)))await Promise.all(r.map((i)=>e.del(i))),s+=r.length;return s}import{defaultLogger as Lt}from"@ionite/core";function Pe(e,t){return`${e}:${encodeURIComponent(t)}`}function Ct(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let s=e,r=s.headers;return s.kind==="delivery"&&typeof s.key==="string"&&typeof s.rawBody==="string"&&typeof r==="object"&&r!==null&&r.requestId===t&&typeof r.keyId==="string"&&typeof r.signature==="string"}function Dt(e,t={}){if(!e.getdel)throw Error("Redis adapter must implement getdel() for LFV callback coordination");let s=e.getdel.bind(e),r=t.channelPrefix?.trim()||"ionite:lfv:otp",i=t.logger??Lt;return{async put(a,n,o){if(n.kind!=="delivery"||n.headers.requestId!==a)throw Error("LFV callback mailbox only accepts matching delivery envelopes");let d=Math.max(1,Math.ceil(o/1000));await e.setex(Pe(r,a),d,JSON.stringify(n))},async take(a){let n=await s(Pe(r,a));if(n==null)return;let o;try{o=JSON.parse(n)}catch(d){i.warn("Invalid JSON received from LFV Redis callback mailbox",{"ion.operation":"lfv.callback.redis.take","ion.outcome":"rejected",requestId:a,error:d instanceof Error?d.message:String(d)});return}if(!Ct(o,a)){i.warn("Invalid envelope received from LFV Redis callback mailbox",{"ion.operation":"lfv.callback.redis.take","ion.outcome":"rejected",requestId:a});return}return o}}}import{StoreConflictError as Ot}from"@ionite/core";function jt(e){return JSON.stringify({token:e.token,customer:e.customer,createdAt:e.createdAt.toISOString(),expiresAt:e.expiresAt.toISOString()})}function Le(e,t){let s=m(e,{store:"magic-link",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),expiresAt:new Date(s.expiresAt)}}class Ce{constructor(e){this.redis=e.redis,this.prefix=x(e,"magic-link-store"),this.log=S(e)}key(e){return f(this.prefix,"magic",h(e))}async create(e,t,s){let r=this.key(e),i={token:e,customer:t,createdAt:new Date,expiresAt:s},a=Math.max(1,Math.floor((s.getTime()-Date.now())/1000));if(await _(this.redis,r,jt(i),{ttlSeconds:a})==="conflict")throw new Ot(`Magic link with token ${e} already exists`,"already_exists","token")}async get(e){let t=await this.redis.get(this.key(e));if(t==null)return null;return Le(t,this.log)??null}async getAndDelete(e){let t=this.key(e),s;if(typeof this.redis.getdel==="function")s=await this.redis.getdel(t);else if(s=await this.redis.get(t),s!=null)await this.redis.del(t);if(s==null)return null;let r=Le(s,this.log);if(r==null)return null;if(Date.now()>r.expiresAt.getTime())return null;return r}async delete(e){await this.redis.del(this.key(e))}}import{defaultLogger as _t}from"@ionite/core";function Gt(e,t){if(typeof t!=="number"||t<=0)return e;return new Promise((s,r)=>{let i=setTimeout(()=>{r(Error(`Reactive Redis adapter did not become ready within ${t}ms`))},t);e.then(()=>{clearTimeout(i),s()},(a)=>{clearTimeout(i),r(a)})})}function Bt(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}function te(e){return typeof e==="function"}function Nt(e){let t=e.logger??_t,s=e.sourceName?.trim()||"redis",r=e.path.trim(),i,a,n=!1,o,d,l,p=!1,E=!1,y=!1,T=new Map,I=Promise.resolve(),v=Bt();v.promise.catch(()=>{});let b={async get(c){return L((u)=>u.get(c))},async set(c,u){await L((g)=>g.set(c,u))},async setex(c,u,g){await L((k)=>k.setex(c,u,g))},async expire(c,u){await L((g)=>g.expire(c,u))},async del(c){await L((u)=>u.del(c))},async sadd(c,...u){await L((g)=>g.sadd(c,...u))},async srem(c,...u){await L((g)=>g.srem(c,...u))},async smembers(c){return L((u)=>u.smembers(c))},async mget(c){return L((u)=>u.mget(c))},async publish(c,u){await L(async(g)=>{if(!g.publish)throw Error("Active Redis adapter does not support publish (Pub/Sub)");await g.publish(c,u)})},async subscribeChannel(c,u){let g=T.get(c);if(!g){let K=new Set;g={listeners:K,dispatch:($e)=>{for(let ze of Array.from(K))try{ze($e)}catch(W){t.warn("Redis channel listener threw",{"ion.operation":"redis.adapter.subscribe","ion.outcome":"failure",sourceName:s,path:r,channel:c,error:W instanceof Error?W.message:String(W)})}}},T.set(c,g)}let k=g;k.listeners.add(u);try{await qe(c,k)}catch(K){if(k.listeners.delete(u),k.listeners.size===0)T.delete(c);throw K}return async()=>{if(k.listeners.delete(u),k.listeners.size===0){T.delete(c);let K=k.unsubscribe;k.unsubscribe=void 0,await K?.()}}},ready(c){return Gt(v.promise,c)},isReady(){return i!==void 0},async close(){if(p=!0,oe(),!n)n=!0,v.reject(Error(`Reactive Redis adapter for source "${s}" at path "${r}" was closed before becoming ready.`));await I.catch(()=>{}),await Y(i),i=void 0;for(let c of T.values())c.unsubscribe=void 0;T.clear(),z()}};function ne(c){I=I.then(c).catch((u)=>{if(!n)n=!0,v.reject(u);t.warn("Reactive Redis adapter update failed",{"ion.operation":"redis.adapter.update","ion.outcome":"degraded",sourceName:s,path:r,error:u instanceof Error?u.message:String(u)})})}async function ae(){if(p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let c=i?.adapter;if(c)return c;if(await I.catch(()=>{}),p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let u=i?.adapter;if(u)return u;if(await v.promise,p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let g=i?.adapter;if(!g)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" did not become ready.`);return g}async function L(c){let u=await ae();return c(u)}function oe(){a?.(),a=void 0}async function qe(c,u){if(u.unsubscribe)return;if(!u.attaching)u.attaching=(async()=>{let g=await ae();if(!g.subscribeChannel)throw Error("Active Redis adapter does not support subscribeChannel (Pub/Sub)");if(u.listeners.size===0)return;u.unsubscribe=await g.subscribeChannel(c,u.dispatch)})().finally(()=>{u.attaching=void 0});await u.attaching}async function Ue(c){for(let[u,g]of T){if(g.attaching)await g.attaching.catch(()=>{});if(g.unsubscribe=void 0,!c.subscribeChannel){t.warn("Active Redis adapter does not support subscribeChannel; channel subscriptions dropped.",{"ion.operation":"redis.adapter.capabilities","ion.outcome":"degraded",sourceName:s,path:r,capability:"subscribeChannel"});return}try{g.unsubscribe=await c.subscribeChannel(u,g.dispatch)}catch(k){t.warn("Failed to re-subscribe Redis channel after client rotation",{"ion.operation":"redis.adapter.subscribe","ion.outcome":"failure",sourceName:s,path:r,channel:u,error:k instanceof Error?k.message:String(k)})}}}async function Me(c){oe(),a=await c.subscribe(r,(u)=>{ne(async()=>{if(p)return;await Ye(u)})},e.subscription??e.secretOptions)}async function Ye(c){if(p)return;let u=`${s}:${r}:${c.metadata.version}`;if(i!==void 0&&d===u&&o===c.metadata.version)return;let g=e.endpointOf?.(c);if(i!==void 0&&g!=null&&g!==""&&l!=null&&l!==""&&g!==l)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" rejected a rotation that changed the endpoint (${l} -> ${g}); only credentials may rotate under an active adapter.`);let k=await e.createClient(c);if(p){await Y(k);return}let K=i;if(i=k,d=u,o=c.metadata.version,g!=null&&g!=="")l=g;if(z(),K!==void 0)await Ue(k.adapter);if(!n)n=!0,v.resolve();await Y(K)}async function Y(c){if(!c?.dispose)return;await c.dispose()}function z(){let c=i?.adapter;if(c?.runScript&&te(c.runScript))b.runScript=async(u,g,k)=>L(async(K)=>{if(!K.runScript)throw Error("Active Redis adapter does not support runScript");return K.runScript(u,g,k)});else if(delete b.runScript,c!==void 0&&!E)E=!0,t.warn("Active Redis adapter does not support runScript (EVAL); stores fall back to non-isolated writes.",{"ion.operation":"redis.adapter.capabilities","ion.outcome":"degraded",sourceName:s,path:r,capability:"runScript"});if(c?.getdel&&te(c.getdel))b.getdel=async(u)=>L(async(g)=>{if(!g.getdel)return null;return g.getdel(u)});else if(delete b.getdel,c!==void 0&&!y)y=!0,t.warn("Active Redis adapter does not support getdel (GETDEL); single-use consume falls back to get+del.",{"ion.operation":"redis.adapter.capabilities","ion.outcome":"degraded",sourceName:s,path:r,capability:"getdel"});if(c?.scan&&te(c.scan))b.scan=async(u,g,k)=>L(async(K)=>{if(!K.scan)throw Error("Active Redis adapter does not support scan");return K.scan(u,g,k)});else delete b.scan}return z(),ne(async()=>{if(p)return;await Me(e.source)}),b}import{StoreConflictError as Ht}from"@ionite/core";var Vt=5;function qt(e,t){let s;try{s=JSON.parse(e)}catch{return}if(s==null||typeof s!=="object"||Array.isArray(s))return;return JSON.stringify({...s,...t})}function De(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString()})}function B(e,t){let s=m(e,{store:"session",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt)}}function se(e){if(!e)return;let t=e instanceof Date?e.getTime():new Date(e).getTime();if(Number.isNaN(t))return;let s=Math.ceil((t-Date.now())/1000);return s>0?s:1}class Oe{constructor(e){this.capabilities={derivedEntitlements:!0};this.redis=e.redis,this.prefix=x(e,"session-store"),this.log=S(e)}key(e){return f(this.prefix,"session",h(e))}idpSidKey(e){return f(this.prefix,"session-idp-sid",h(e))}async addToIdpIndex(e){if(!e.idpSid)return;let t=this.idpSidKey(e.idpSid);await this.redis.sadd(t,e.sid);let s=se(e.expiresAt);if(s===void 0)return;let r=await this.redis.ttl?.(t)??-1;await this.redis.expire(t,Math.max(s,r>0?r:0))}async removeFromIdpIndex(e){if(!e.idpSid)return;let t=this.idpSidKey(e.idpSid);if(await this.redis.srem(t,e.sid),(await this.redis.smembers(t)).length===0)await this.redis.del(t)}async create(e){let t=this.key(e.sid),s=se(e.expiresAt);if(await _(this.redis,t,De(e),{ttlSeconds:s})==="conflict")throw new Ht(`Session with sid ${e.sid} already exists`,"already_exists","sid");await this.addToIdpIndex(e)}async get(e){let t=await this.redis.get(this.key(e));if(t==null)return null;return B(t,this.log)??null}async update(e,t){let s=this.key(e),r=await this.redis.get(s),i=r==null?void 0:B(r,this.log);if(!i)throw Error(`Session with sid ${e} not found`);let a={...i,...t},n=async()=>{if(i.idpSid!==a.idpSid)await this.removeFromIdpIndex(i);await this.addToIdpIndex(a)},o=JSON.parse(JSON.stringify(t)),d="expiresAt"in o?se(o.expiresAt):void 0;if(A(this.redis))for(let T=0;T<Vt;T++){let I=await this.redis.get(s);if(I==null)throw Error(`Session with sid ${e} not found`);let v=qt(I,o);if(v===void 0)throw Error(`Session with sid ${e} not found`);let b=await G(this.redis,s,I,v,d);if(b==="ok"){await n();return}if(b==="missing")throw Error(`Session with sid ${e} not found`)}let l=await this.redis.get(s);if(l==null)throw Error(`Session with sid ${e} not found`);let p=B(l,this.log);if(p==null)throw Error(`Session with sid ${e} not found`);let E={...p,...t},y=De(E);if(d!=null&&d>0)await this.redis.setex(s,Math.max(1,Math.floor(d)),y);else await this.redis.set(s,y);await n()}async delete(e){let t=await this.redis.get(this.key(e));if(await this.redis.del(this.key(e)),t!=null){let s=B(t,this.log);if(s)await this.removeFromIdpIndex(s)}}async deleteByTenant(e){let t=new Set(typeof e==="string"?[e]:e),s=0;for await(let r of U(this.redis,f(this.prefix,"session","")))for(let i of await this.redis.mget(r)){let a=i==null?void 0:B(i,this.log);if(a?.tenantId===void 0||!t.has(a.tenantId))continue;await this.delete(a.sid),s++}return s}async deleteByIdpSid(e){let t=this.idpSidKey(e),s=await this.redis.smembers(t);for(let r of s)await this.delete(r);await this.redis.del(t)}}var Ut="tenant:ids",Mt=`
|
|
176
|
+
return 'ok'`;function D(e,t){return`${t}:${e}`}function V(e){return e&&e.length>0?e:q}function Z(e){return JSON.stringify([e.subject,e.targetType,e.target,e.rToken])}function j(e){let t;try{t=JSON.parse(e)}catch{t=[]}let[s,r,i,a]=Array.isArray(t)?t:[];return{subject:s??"",targetType:r??"permission",target:i??"",rToken:a??q}}class Ae{constructor(e){this.redis=e.redis,this.prefix=x(e,"access-index"),this.log=S(e)}key(...e){return f(this.prefix,...e)}subjectKeyPart(e){let t=e.indexOf(":");if(t<=0)return h(e);return`${e.slice(0,t)}:${h(e.slice(t+1))}`}hasKey(e,t,s,r){return this.key("idx:has",this.subjectKeyPart(e),t,h(s),h(r))}anyKey(e,t,s){return this.key("idx:any",this.subjectKeyPart(e),t,h(s))}edgeRootsKey(e,t,s,r){return this.key("idx:er",this.subjectKeyPart(e),t,h(s),h(r))}tripleKey(e,t,s){return this.key("idx:tr",this.subjectKeyPart(e),t,h(s))}rootKey(e){return this.key("idx:root",h(e))}subjectKey(e){return this.key("idx:subj",this.subjectKeyPart(e))}subjectsKey(){return this.key("idx:subjects")}disabledKey(e){return this.key("idx:disabled",this.subjectKeyPart(e))}async has(e,t,s,r,i){O(i);let a=P(e),n=P(s);if(!a||!n)return{allow:!1};let o=D(a,i);if(r===void 0){let[p,E]=await this.redis.mget([this.disabledKey(o),this.anyKey(o,t,n)]);if(p!=null)return{allow:!1,metadata:{reason:"subject_disabled"}};return E!=null?this.allow(a,i,t,n,void 0):{allow:!1}}let d=P(r),l=await this.redis.mget([this.disabledKey(o),this.hasKey(o,t,n,V(d)),this.hasKey(o,t,n,q)]);if(l[0]!=null)return{allow:!1,metadata:{reason:"subject_disabled"}};if(l[1]!=null)return this.allow(a,i,t,n,d);if(l[2]!=null)return this.allow(a,i,t,n,void 0);return{allow:!1}}async hasGroup(e,t,s,r){return this.has(e,"group",t,s,r)}async hasRole(e,t,s,r){return this.has(e,"role",t,s,r)}async hasPermission(e,t,s,r){return this.has(e,"permission",t,s,r)}async hasAny(e,t,s){if(t.length===0)return{allow:!1};this.warnLargeCheck("redis.access_index.has_any",t.length);let r=await this.evaluateTargets(e,t,s);for(let i of r)if(i.allow)return i;return{allow:!1}}async hasAll(e,t,s){if(t.length===0){let a=P(e);if(a){if(await this.redis.get(this.disabledKey(D(a,s)))!=null)return{allow:!1,metadata:{reason:"subject_disabled"}}}return{allow:!0}}this.warnLargeCheck("redis.access_index.has_all",t.length);let r=await this.evaluateTargets(e,t,s),i=[];for(let a of r){if(!a.allow)return{allow:!1,matched:i};if(a.matched)i.push(...a.matched)}return{allow:!0,matched:i}}async evaluateTargets(e,t,s){let r=P(e);if(!r)return t.map(()=>({allow:!1}));let i=D(r,s),a=[this.disabledKey(i)],n=t.map((d)=>{let l=P(d.target);if(!l)return{kind:"invalid"};if(d.resource===void 0){let T=a.push(this.anyKey(i,d.targetType,l))-1;return{kind:"any",targetType:d.targetType,targetId:l,idx:T}}let p=P(d.resource),E=a.push(this.hasKey(i,d.targetType,l,V(p)))-1,y=a.push(this.hasKey(i,d.targetType,l,q))-1;return{kind:"resource",targetType:d.targetType,targetId:l,resourceId:p,idxResource:E,idxApp:y}}),o=await this.redis.mget(a);if(o[0]!=null)return t.map(()=>({allow:!1,metadata:{reason:"subject_disabled"}}));return n.map((d)=>{if(d.kind==="invalid")return{allow:!1};if(d.kind==="any")return o[d.idx]!=null?this.allow(r,s,d.targetType,d.targetId,void 0):{allow:!1};if(o[d.idxResource]!=null)return this.allow(r,s,d.targetType,d.targetId,d.resourceId);if(o[d.idxApp]!=null)return this.allow(r,s,d.targetType,d.targetId,void 0);return{allow:!1}})}edgeKeys(e){return[this.edgeRootsKey(e.subject,e.targetType,e.target,e.rToken),this.hasKey(e.subject,e.targetType,e.target,e.rToken),this.tripleKey(e.subject,e.targetType,e.target),this.anyKey(e.subject,e.targetType,e.target),this.subjectKey(e.subject)]}async materialize(e,t){let s=new Map;for(let n of t){let o=P(n.subject),d=P(n.target);if(!o||!d)continue;O(n.subjectType,"Effective edge subjectType");let l=D(o,n.subjectType),p=V(n.resource),E={subject:l,targetType:n.targetType,target:d,rToken:p};s.set(Z(E),E)}let r=new Set(await this.redis.smembers(this.rootKey(e))),i=[];for(let[n,o]of s)if(!r.has(n))i.push({encoded:n,d:o});let a=[];for(let n of r)if(!s.has(n))a.push({encoded:n,d:j(n)});if(i.length===0&&a.length===0)return;if(A(this.redis)){let n=[this.rootKey(e),this.subjectsKey()],o=[e,String(i.length),String(a.length)];for(let{encoded:d,d:l}of i)n.push(...this.edgeKeys(l)),o.push(d,l.rToken,l.subject);for(let{encoded:d,d:l}of a)n.push(...this.edgeKeys(l)),o.push(d,l.rToken);await this.redis.runScript(ct,n,o);return}for(let{encoded:n,d:o}of i)await this.redis.sadd(this.edgeRootsKey(o.subject,o.targetType,o.target,o.rToken),e),await this.redis.set(this.hasKey(o.subject,o.targetType,o.target,o.rToken),"1"),await this.redis.sadd(this.tripleKey(o.subject,o.targetType,o.target),o.rToken),await this.redis.set(this.anyKey(o.subject,o.targetType,o.target),"1"),await this.redis.sadd(this.rootKey(e),n),await this.redis.sadd(this.subjectKey(o.subject),n),await this.redis.sadd(this.subjectsKey(),o.subject);for(let{encoded:n,d:o}of a)await this.dropRootFromEdge(e,o.subject,o.targetType,o.target,o.rToken),await this.redis.srem(this.rootKey(e),n)}async replaceSubject(e,t,s){if(!A(this.redis))throw Error("RedisAccessIndex.replaceSubject requires an adapter with atomic runScript support.");let r=P(e);if(!r)return;let i=D(r,t),a=[];for(let y of s){let T=P(y.subject);O(y.subjectType,"Effective edge subjectType");let I=y.subjectType;if(T!==r||I!==t)throw Error(`AccessIndex.replaceSubject received an edge for ${I}:${T}; expected ${i}.`);let v=P(y.target);if(!v)continue;let b={subject:i,targetType:y.targetType,target:v,rToken:V(y.resource)};a.push({rootId:y.rootId,encoded:Z(b),d:b})}let o=(await this.redis.smembers(this.subjectKey(i))).map(j),d=await Promise.all(o.map((y)=>this.redis.smembers(this.edgeRootsKey(y.subject,y.targetType,y.target,y.rToken)))),l=[...new Set(d.flat())],p=[this.subjectKey(i),this.subjectsKey()];for(let y of o){let[T,I,v,b]=this.edgeKeys(y);p.push(T,I,v,b)}for(let y of l)p.push(this.rootKey(y));for(let y of a){let[T,I,v,b]=this.edgeKeys(y.d);p.push(this.rootKey(y.rootId),T,I,v,b)}let E=[i,String(o.length),String(l.length),String(a.length)];for(let y of a)E.push(y.rootId,y.encoded,y.d.rToken);await this.redis.runScript(gt,p,E)}async removeByRoot(e){let t=this.rootKey(e),s=await this.redis.smembers(t);if(s.length===0){await this.redis.del(t);return}if(A(this.redis)){let r=[t],i=[e,String(s.length)];for(let a of s){let n=j(a);r.push(...this.edgeKeys(n)),i.push(a,n.rToken)}await this.redis.runScript(lt,r,i);return}for(let r of s){let{subject:i,targetType:a,target:n,rToken:o}=j(r);await this.dropRootFromEdge(e,i,a,n,o)}await this.redis.del(t)}async listSubjects(){let e=await this.redis.smembers(this.subjectsKey()),t=[];for(let s of e){let r=s.indexOf(":");if(r<=0)throw Error(`AccessIndex subject key "${s}" is missing a subjectType prefix.`);let i=s.slice(0,r);O(i,"AccessIndex subject key subjectType"),t.push({subjectType:i,subject:s.slice(r+1)})}return t}async setSubjectDisabled(e,t,s){let r=P(e);if(!r)return;let i=this.disabledKey(D(r,t));if(s)await this.redis.set(i,"1");else await this.redis.del(i)}async isSubjectDisabled(e,t){O(t);let s=P(e);if(!s)return!1;return await this.redis.get(this.disabledKey(D(s,t)))!=null}async clear(e,t){if(e===void 0){let i=await this.redis.smembers(this.subjectsKey());for(let a of i)await this.clearSubject(a);await this.redis.del(this.subjectsKey());return}O(t);let s=P(e);if(!s)return;let r=D(s,t);await this.clearSubject(r),await this.redis.srem(this.subjectsKey(),r)}async clearSubject(e){let t=this.subjectKey(e),s=await this.redis.smembers(t);if(s.length===0){await this.redis.del(t);return}if(A(this.redis)){let r=[t];for(let a of s){let{targetType:n,target:o,rToken:d}=j(a);r.push(this.edgeRootsKey(e,n,o,d),this.hasKey(e,n,o,d),this.tripleKey(e,n,o),this.anyKey(e,n,o))}let i=dt(await this.redis.runScript(ut,r,[String(s.length)]));if(i.length>0)await this.redis.runScript(pt,i.map((a)=>this.rootKey(a)),[]);return}for(let r of s){let{targetType:i,target:a,rToken:n}=j(r),o=this.edgeRootsKey(e,i,a,n),d=await this.redis.smembers(o);for(let p of d)await this.redis.srem(this.rootKey(p),r);if(await this.redis.del(o),await this.redis.del(this.hasKey(e,i,a,n)),await this.redis.srem(this.tripleKey(e,i,a),n),(await this.redis.smembers(this.tripleKey(e,i,a))).length===0)await this.redis.del(this.tripleKey(e,i,a)),await this.redis.del(this.anyKey(e,i,a))}await this.redis.del(t)}async dropRootFromEdge(e,t,s,r,i){let a=this.edgeRootsKey(t,s,r,i);if(await this.redis.srem(a,e),(await this.redis.smembers(a)).length>0)return;await this.redis.del(a),await this.redis.del(this.hasKey(t,s,r,i));let o=Z({subject:t,targetType:s,target:r,rToken:i});if(await this.redis.srem(this.subjectKey(t),o),await this.redis.srem(this.tripleKey(t,s,r),i),(await this.redis.smembers(this.tripleKey(t,s,r))).length===0)await this.redis.del(this.tripleKey(t,s,r)),await this.redis.del(this.anyKey(t,s,r))}allow(e,t,s,r,i){return{allow:!0,matched:[{subject:e,subjectType:t,targetType:s,target:r,resources:i?[i]:void 0}]}}warnLargeCheck(e,t){if(t<=Re)return;this.log.warn("Redis access index check received a large bounded target set; issuing per-target reads.",{"ion.operation":e,"ion.outcome":"degraded",count:t,threshold:Re})}}var ht=512;async function yt(e,t,s=512){if(e.length===0)return[];let r=s>0?s:512,i=[];for(let a=0;a<e.length;a+=r){let n=await t(e.slice(a,a+r));for(let o of n)i.push(o??null)}return i}import{list as ft,StoreConflictError as mt}from"@ionite/core";var St="customer:ids",wt="customer:name:",xt="customer:external:";function kt(e){let t=e.createdAt??new Date,s=e.updatedAt??t,r={...e,createdAt:t.toISOString(),updatedAt:s.toISOString()};if(r.ciam&&typeof r.ciam==="object"&&r.ciam!==null){let i=r.ciam;if(i.expires instanceof Date)i.expires=i.expires.toISOString()}return JSON.stringify(r)}function Q(e,t){let s=m(e,{store:"customer",log:t});if(s===void 0)return;if(s.ciam&&typeof s.ciam==="object"&&s.ciam!==null){let r=s.ciam;if(typeof r.expires==="string")r.expires=new Date(r.expires)}return{...s,createdAt:typeof s.createdAt==="string"?new Date(s.createdAt):void 0,updatedAt:typeof s.updatedAt==="string"?new Date(s.updatedAt):void 0}}class Ee{constructor(e){this.redis=e.redis,this.prefix=x(e,"customer-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("customer",h(e))}idsSetKey(){return this.key(St)}nameIndexKey(e){return this.key(wt+h(e))}externalIdIndexKey(e){return this.key(xt+h(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return Q(t,this.log)}async lookup(e){if(e.id){let t=await this.get(e.id);if(t)return t}if(e.userName){let t=await this.redis.get(this.nameIndexKey(e.userName.toLowerCase()));if(t!=null)return this.get(t)}if(e.externalId)return this.getByExternalId(e.externalId);return}async getByExternalId(e){let t=await this.redis.get(this.externalIdIndexKey(e));if(t==null)return;return this.get(t)}async upsert(e){let t=e.id?.trim()||crypto.randomUUID(),s={...e,id:t},r=this.entityKey(t),i=await this.redis.get(r),a=i!=null?Q(i,this.log)??null:null,n=s.userName?.toLowerCase(),o=a?.userName?.toLowerCase(),d=s.externalId,l=a?.externalId,p=new w;if(n)p.claimUnique(this.nameIndexKey(n),t);if(d)p.claimUnique(this.externalIdIndexKey(d),t);if(o&&o!==n)p.del(this.nameIndexKey(o));if(l&&l!==d)p.del(this.externalIdIndexKey(l));if(p.set(r,kt(s)),n)p.set(this.nameIndexKey(n),t);if(d)p.set(this.externalIdIndexKey(d),t);if(p.sadd(this.idsSetKey(),t),await p.exec(this.redis)==="conflict")throw new mt(`userName "${s.userName}" is already in use`,"unique_violation","userName");return s}async delete(e){let t=await this.get(e);if(t==null)return 0;let s=new w;if(s.del(this.entityKey(e)),t.userName)s.del(this.nameIndexKey(t.userName.toLowerCase()));if(t.externalId)s.del(this.externalIdIndexKey(t.externalId));return s.srem(this.idsSetKey(),e),await s.exec(this.redis),1}async list(e){let t=C(e),s=(await this.redis.smembers(this.idsSetKey())).sort();if(s.length===0)return ft(0,[],t.start??0,t.limit);let r=s.map((n)=>this.entityKey(n)),a=(await this.redis.mget(r)).filter((n)=>n!=null).map((n)=>Q(n,this.log)).filter((n)=>n!=null);return R(a,t)}}import{StoreConflictError as Tt}from"@ionite/core";var Rt="delegate:ids";function be(e){let t=e.createdAt??new Date,s=e.updatedAt??t;return JSON.stringify({...e,createdAt:t.toISOString(),updatedAt:s.toISOString(),expiresAt:e.expiresAt?.toISOString(),previousTokenHashExpiresAt:e.previousTokenHashExpiresAt?.toISOString(),lastUsedAt:e.lastUsedAt?.toISOString()})}function ee(e,t){let s=m(e,{store:"delegate",log:t});if(s===void 0)return;let r=(i)=>typeof i==="string"?new Date(i):void 0;return{...s,createdAt:r(s.createdAt),updatedAt:r(s.updatedAt),expiresAt:r(s.expiresAt),previousTokenHashExpiresAt:r(s.previousTokenHashExpiresAt),lastUsedAt:r(s.lastUsedAt)}}class ve{constructor(e){this.redis=e.redis,this.prefix=x(e,"delegate-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("delegate",h(e))}tokenHashKey(e){return this.key("delegate:token",h(e))}externalIdKey(e){return this.key("delegate:external",h(e))}idsSetKey(){return this.key(Rt)}async get(e){let t=await this.redis.get(this.entityKey(e));return t==null?void 0:ee(t,this.log)}async lookup(e){return await this.get(e.id)??(e.externalId?this.getByExternalId(e.externalId):void 0)}async getByTokenHash(e){let t=await this.redis.get(this.tokenHashKey(e));if(!t)return;let s=await this.get(t);if(!s)return;if(s.tokenHash===e)return s;if(s.previousTokenHash===e&&s.previousTokenHashExpiresAt&&s.previousTokenHashExpiresAt.getTime()>Date.now())return s;return}async getByExternalId(e){let t=await this.redis.get(this.externalIdKey(e));return t?this.get(t):void 0}async listByOwner(e,t,s){let r=await this.all();return R(r.filter((i)=>i.owner.id===e&&i.owner.type===t),C(s))}async upsert(e){let t=e.id?.trim()||crypto.randomUUID(),s=await this.get(t),r=new Date,i={...e,id:t,createdAt:s?.createdAt??e.createdAt??r,updatedAt:r},a=new w;if(a.claimUnique(this.tokenHashKey(i.tokenHash),t),i.previousTokenHash)a.claimUnique(this.tokenHashKey(i.previousTokenHash),t);if(i.externalId)a.claimUnique(this.externalIdKey(i.externalId),t);if(s?.tokenHash&&s.tokenHash!==i.tokenHash)a.del(this.tokenHashKey(s.tokenHash));if(s?.previousTokenHash&&s.previousTokenHash!==i.previousTokenHash)a.del(this.tokenHashKey(s.previousTokenHash));if(s?.externalId&&s.externalId!==i.externalId)a.del(this.externalIdKey(s.externalId));if(a.set(this.entityKey(t),be(i)),a.set(this.tokenHashKey(i.tokenHash),t),i.previousTokenHash)a.set(this.tokenHashKey(i.previousTokenHash),t);if(i.externalId)a.set(this.externalIdKey(i.externalId),t);if(a.sadd(this.idsSetKey(),t),await a.exec(this.redis)==="conflict")throw new Tt("Delegate credential or externalId is already in use","unique_violation");return i}async delete(e){let t=await this.get(e);if(!t)return 0;let s=new w;if(s.del(this.entityKey(e)),s.del(this.tokenHashKey(t.tokenHash)),t.previousTokenHash)s.del(this.tokenHashKey(t.previousTokenHash));if(t.externalId)s.del(this.externalIdKey(t.externalId));return s.srem(this.idsSetKey(),e),await s.exec(this.redis),1}async list(e){return R(await this.all(),C(e))}async touch(e,t){let s=this.entityKey(e);for(let r=0;r<3;r+=1){let i=await this.redis.get(s);if(i==null)return;let a=ee(i,this.log);if(!a)return;let n=be({...a,lastUsedAt:t}),o=await G(this.redis,s,i,n);if(o==="ok"||o==="missing")return;if(o==="unsupported"){await this.redis.set(s,n);return}}this.log.warn("Delegate usage timestamp update lost a concurrent race",{"ion.operation":"delegate.touch","ion.outcome":"skipped",delegateId:e})}async all(){let e=(await this.redis.smembers(this.idsSetKey())).sort();if(e.length===0)return[];return(await this.redis.mget(e.map((s)=>this.entityKey(s)))).filter((s)=>s!=null).map((s)=>ee(s,this.log)).filter((s)=>s!==void 0)}}import{createHash as At}from"node:crypto";function Ie(e){return At("sha1").update(e,"utf8").digest("hex")}function Et(e){return(e instanceof Error?e.message:String(e)).includes("NOSCRIPT")}function bt(e){let t=new Map;return async(s,r,i)=>{let a=t.get(s);if(!a)a=Ie(s),t.set(s,a);try{return await e.evalsha(a,r,i)}catch(n){if(Et(n))return e.eval(s,r,i);throw n}}}function Ke(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function vt(e){let t=Ke(e.clientOptions)?{...e.clientOptions}:Ke(e)?{...e}:{};return delete t.redisUrl,delete t.clientOptions,{redisUrl:(typeof e.redisUrl==="string"?e.redisUrl.trim():"")||void 0,clientOptions:t}}var It=500;function Kt(e){return e.replace(/[*?[\]\\]/g,"\\$&")}async function*U(e,t){if(!e.scan)throw Error("Redis adapter does not support scan; keyspace teardown needs an adapter that implements it.");let s=`${Kt(t)}*`,r="0";do{let i=await e.scan(r,s,It);if(r=i.cursor,i.keys.length>0)yield i.keys}while(r!=="0")}async function Pt(e,t){let s=0;for await(let r of U(e,N(t)))await Promise.all(r.map((i)=>e.del(i))),s+=r.length;return s}import{defaultLogger as Lt}from"@ionite/core";function Pe(e,t){return`${e}:${encodeURIComponent(t)}`}function Ct(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let s=e,r=s.headers;return s.kind==="delivery"&&typeof s.key==="string"&&typeof s.rawBody==="string"&&typeof r==="object"&&r!==null&&r.requestId===t&&typeof r.keyId==="string"&&typeof r.signature==="string"}function Dt(e,t={}){if(!e.getdel)throw Error("Redis adapter must implement getdel() for LFV callback coordination");let s=e.getdel.bind(e),r=t.channelPrefix?.trim()||"ionite:lfv:otp",i=t.logger??Lt;return{async put(a,n,o){if(n.kind!=="delivery"||n.headers.requestId!==a)throw Error("LFV callback mailbox only accepts matching delivery envelopes");let d=Math.max(1,Math.ceil(o/1000));await e.setex(Pe(r,a),d,JSON.stringify(n))},async take(a){let n=await s(Pe(r,a));if(n==null)return;let o;try{o=JSON.parse(n)}catch(d){i.warn("Invalid JSON received from LFV Redis callback mailbox",{"ion.operation":"lfv.callback.redis.take","ion.outcome":"rejected",requestId:a,error:d instanceof Error?d.message:String(d)});return}if(!Ct(o,a)){i.warn("Invalid envelope received from LFV Redis callback mailbox",{"ion.operation":"lfv.callback.redis.take","ion.outcome":"rejected",requestId:a});return}return o}}}import{StoreConflictError as Ot}from"@ionite/core";function jt(e){return JSON.stringify({token:e.token,customer:e.customer,createdAt:e.createdAt.toISOString(),expiresAt:e.expiresAt.toISOString()})}function Le(e,t){let s=m(e,{store:"magic-link",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),expiresAt:new Date(s.expiresAt)}}class Ce{constructor(e){this.redis=e.redis,this.prefix=x(e,"magic-link-store"),this.log=S(e)}key(e){return f(this.prefix,"magic",h(e))}async create(e,t,s){let r=this.key(e),i={token:e,customer:t,createdAt:new Date,expiresAt:s},a=Math.max(1,Math.floor((s.getTime()-Date.now())/1000));if(await _(this.redis,r,jt(i),{ttlSeconds:a})==="conflict")throw new Ot(`Magic link with token ${e} already exists`,"already_exists","token")}async get(e){let t=await this.redis.get(this.key(e));if(t==null)return null;return Le(t,this.log)??null}async getAndDelete(e){let t=this.key(e),s;if(typeof this.redis.getdel==="function")s=await this.redis.getdel(t);else if(s=await this.redis.get(t),s!=null)await this.redis.del(t);if(s==null)return null;let r=Le(s,this.log);if(r==null)return null;if(Date.now()>r.expiresAt.getTime())return null;return r}async delete(e){await this.redis.del(this.key(e))}}import{defaultLogger as _t}from"@ionite/core";function Gt(e,t){if(typeof t!=="number"||t<=0)return e;return new Promise((s,r)=>{let i=setTimeout(()=>{r(Error(`Reactive Redis adapter did not become ready within ${t}ms`))},t);e.then(()=>{clearTimeout(i),s()},(a)=>{clearTimeout(i),r(a)})})}function Bt(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}function te(e){return typeof e==="function"}function Nt(e){let t=e.logger??_t,s=e.sourceName?.trim()||"redis",r=e.path.trim(),i,a,n=!1,o,d,l,p=!1,E=!1,y=!1,T=new Map,I=Promise.resolve(),v=Bt();v.promise.catch(()=>{});let b={async get(c){return L((u)=>u.get(c))},async set(c,u){await L((g)=>g.set(c,u))},async setex(c,u,g){await L((k)=>k.setex(c,u,g))},async expire(c,u){await L((g)=>g.expire(c,u))},async del(c){await L((u)=>u.del(c))},async sadd(c,...u){await L((g)=>g.sadd(c,...u))},async srem(c,...u){await L((g)=>g.srem(c,...u))},async smembers(c){return L((u)=>u.smembers(c))},async mget(c){return L((u)=>u.mget(c))},async publish(c,u){await L(async(g)=>{if(!g.publish)throw Error("Active Redis adapter does not support publish (Pub/Sub)");await g.publish(c,u)})},async subscribeChannel(c,u){let g=T.get(c);if(!g){let K=new Set;g={listeners:K,dispatch:($e)=>{for(let ze of Array.from(K))try{ze($e)}catch(W){t.warn("Redis channel listener threw",{"ion.operation":"redis.adapter.subscribe","ion.outcome":"failure",sourceName:s,path:r,channel:c,error:W instanceof Error?W.message:String(W)})}}},T.set(c,g)}let k=g;k.listeners.add(u);try{await qe(c,k)}catch(K){if(k.listeners.delete(u),k.listeners.size===0)T.delete(c);throw K}return async()=>{if(k.listeners.delete(u),k.listeners.size===0){T.delete(c);let K=k.unsubscribe;k.unsubscribe=void 0,await K?.()}}},ready(c){return Gt(v.promise,c)},isReady(){return i!==void 0},async close(){if(p=!0,oe(),!n)n=!0,v.reject(Error(`Reactive Redis adapter for source "${s}" at path "${r}" was closed before becoming ready.`));await I.catch(()=>{}),await Y(i),i=void 0;for(let c of T.values())c.unsubscribe=void 0;T.clear(),z()}};function ne(c){I=I.then(c).catch((u)=>{if(!n)n=!0,v.reject(u);t.warn("Reactive Redis adapter update failed",{"ion.operation":"redis.adapter.update","ion.outcome":"degraded",sourceName:s,path:r,error:u instanceof Error?u.message:String(u)})})}async function ae(){if(p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let c=i?.adapter;if(c)return c;if(await I.catch(()=>{}),p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let u=i?.adapter;if(u)return u;if(await v.promise,p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let g=i?.adapter;if(!g)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" did not become ready.`);return g}async function L(c){let u=await ae();return c(u)}function oe(){a?.(),a=void 0}async function qe(c,u){if(u.unsubscribe)return;if(!u.attaching)u.attaching=(async()=>{let g=await ae();if(!g.subscribeChannel)throw Error("Active Redis adapter does not support subscribeChannel (Pub/Sub)");if(u.listeners.size===0)return;u.unsubscribe=await g.subscribeChannel(c,u.dispatch)})().finally(()=>{u.attaching=void 0});await u.attaching}async function Ue(c){for(let[u,g]of T){if(g.attaching)await g.attaching.catch(()=>{});if(g.unsubscribe=void 0,!c.subscribeChannel){t.warn("Active Redis adapter does not support subscribeChannel; channel subscriptions dropped.",{"ion.operation":"redis.adapter.capabilities","ion.outcome":"degraded",sourceName:s,path:r,capability:"subscribeChannel"});return}try{g.unsubscribe=await c.subscribeChannel(u,g.dispatch)}catch(k){t.warn("Failed to re-subscribe Redis channel after client rotation",{"ion.operation":"redis.adapter.subscribe","ion.outcome":"failure",sourceName:s,path:r,channel:u,error:k instanceof Error?k.message:String(k)})}}}async function Me(c){oe(),a=await c.subscribe(r,(u)=>{ne(async()=>{if(p)return;await Ye(u)})},e.subscription??e.secretOptions)}async function Ye(c){if(p)return;let u=`${s}:${r}:${c.metadata.version}`;if(i!==void 0&&d===u&&o===c.metadata.version)return;let g=e.endpointOf?.(c);if(i!==void 0&&g!=null&&g!==""&&l!=null&&l!==""&&g!==l)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" rejected a rotation that changed the endpoint (${l} -> ${g}); only credentials may rotate under an active adapter.`);let k=await e.createClient(c);if(p){await Y(k);return}let K=i;if(i=k,d=u,o=c.metadata.version,g!=null&&g!=="")l=g;if(z(),K!==void 0)await Ue(k.adapter);if(!n)n=!0,v.resolve();await Y(K)}async function Y(c){if(!c?.dispose)return;await c.dispose()}function z(){let c=i?.adapter;if(c?.runScript&&te(c.runScript))b.runScript=async(u,g,k)=>L(async(K)=>{if(!K.runScript)throw Error("Active Redis adapter does not support runScript");return K.runScript(u,g,k)});else if(delete b.runScript,c!==void 0&&!E)E=!0,t.warn("Active Redis adapter does not support runScript (EVAL); stores fall back to non-isolated writes.",{"ion.operation":"redis.adapter.capabilities","ion.outcome":"degraded",sourceName:s,path:r,capability:"runScript"});if(c?.getdel&&te(c.getdel))b.getdel=async(u)=>L(async(g)=>{if(!g.getdel)return null;return g.getdel(u)});else if(delete b.getdel,c!==void 0&&!y)y=!0,t.warn("Active Redis adapter does not support getdel (GETDEL); single-use consume falls back to get+del.",{"ion.operation":"redis.adapter.capabilities","ion.outcome":"degraded",sourceName:s,path:r,capability:"getdel"});if(c?.scan&&te(c.scan))b.scan=async(u,g,k)=>L(async(K)=>{if(!K.scan)throw Error("Active Redis adapter does not support scan");return K.scan(u,g,k)});else delete b.scan}return z(),ne(async()=>{if(p)return;await Me(e.source)}),b}import{StoreConflictError as Ht}from"@ionite/core";var Vt=5;function qt(e,t){let s;try{s=JSON.parse(e)}catch{return}if(s==null||typeof s!=="object"||Array.isArray(s))return;return JSON.stringify({...s,...t})}function De(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString()})}function B(e,t){let s=m(e,{store:"session",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt)}}function se(e){if(!e)return;let t=e instanceof Date?e.getTime():new Date(e).getTime();if(Number.isNaN(t))return;let s=Math.ceil((t-Date.now())/1000);return s>0?s:1}class Oe{constructor(e){this.capabilities={derivedEntitlements:!0};this.redis=e.redis,this.prefix=x(e,"session-store"),this.log=S(e)}key(e){return f(this.prefix,"session",h(e))}idpSidKey(e){return f(this.prefix,"session-idp-sid",h(e))}async addToIdpIndex(e){if(!e.idpSid)return;let t=this.idpSidKey(e.idpSid);await this.redis.sadd(t,e.sid);let s=se(e.expiresAt);if(s===void 0)return;let r=await this.redis.ttl?.(t)??-1;await this.redis.expire(t,Math.max(s,r>0?r:0))}async removeFromIdpIndex(e){if(!e.idpSid)return;let t=this.idpSidKey(e.idpSid);if(await this.redis.srem(t,e.sid),(await this.redis.smembers(t)).length===0)await this.redis.del(t)}async create(e){let t=this.key(e.sid),s=se(e.expiresAt);if(await _(this.redis,t,De(e),{ttlSeconds:s})==="conflict")throw new Ht(`Session with sid ${e.sid} already exists`,"already_exists","sid");await this.addToIdpIndex(e)}async get(e){let t=await this.redis.get(this.key(e));if(t==null)return null;return B(t,this.log)??null}async update(e,t){let s=this.key(e),r=await this.redis.get(s),i=r==null?void 0:B(r,this.log);if(!i)throw Error(`Session with sid ${e} not found`);let a={...i,...t},n=async()=>{if(i.idpSid!==a.idpSid)await this.removeFromIdpIndex(i);await this.addToIdpIndex(a)},o=JSON.parse(JSON.stringify(t)),d="expiresAt"in o?se(o.expiresAt):void 0;if(A(this.redis))for(let T=0;T<Vt;T++){let I=await this.redis.get(s);if(I==null)throw Error(`Session with sid ${e} not found`);let v=qt(I,o);if(v===void 0)throw Error(`Session with sid ${e} not found`);let b=await G(this.redis,s,I,v,d);if(b==="ok"){await n();return}if(b==="missing")throw Error(`Session with sid ${e} not found`)}let l=await this.redis.get(s);if(l==null)throw Error(`Session with sid ${e} not found`);let p=B(l,this.log);if(p==null)throw Error(`Session with sid ${e} not found`);let E={...p,...t},y=De(E);if(d!=null&&d>0)await this.redis.setex(s,Math.max(1,Math.floor(d)),y);else await this.redis.set(s,y);await n()}async delete(e){let t=await this.redis.get(this.key(e));if(await this.redis.del(this.key(e)),t!=null){let s=B(t,this.log);if(s)await this.removeFromIdpIndex(s)}}async deleteByTenant(e){let t=new Set(typeof e==="string"?[e]:e),s=0;for await(let r of U(this.redis,f(this.prefix,"session","")))for(let i of await this.redis.mget(r)){let a=i==null?void 0:B(i,this.log);if(a?.tenantId===void 0||!t.has(a.tenantId))continue;await this.delete(a.sid),s++}return s}async deleteByIdpSid(e){let t=this.idpSidKey(e),s=await this.redis.smembers(t);for(let r of s)await this.delete(r);await this.redis.del(t)}}var Ut="tenant:ids",Mt=`
|
|
177
177
|
local raw = redis.call('GET', KEYS[1])
|
|
178
178
|
local previous = nil
|
|
179
179
|
if raw then previous = cjson.decode(raw) end
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ionite/redis-core",
|
|
3
|
-
"version": "0.0.27
|
|
3
|
+
"version": "0.0.27",
|
|
4
4
|
"description": "Redis adapter interface and store implementations for ionite. Use with @ionite/redis (node-redis), @ionite/ioredis, or a custom RedisAdapter.",
|
|
5
5
|
"private": false,
|
|
6
6
|
"author": "ionite",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"./package.json": "./package.json"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@ionite/core": "0.0.27
|
|
27
|
+
"@ionite/core": "^0.0.27"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@types/node": "^26.1.0"
|