@ionite/redis-core 0.0.25 → 0.0.27-beta.20261102.1

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 CHANGED
@@ -40,6 +40,15 @@ interface RedisAdapter {
40
40
  */
41
41
  getdel?(key: string): Promise<string | null>;
42
42
  /**
43
+ * Optional: one Redis `SCAN` page over keys matching the glob `match`. Start with cursor `'0'`;
44
+ * iteration is complete when the returned cursor is `'0'`. Required by keyspace teardown
45
+ * (`deleteKeyspace`, `RedisSessionStore.deleteByTenant`); no store calls it on a request path.
46
+ */
47
+ scan?(cursor: string, match: string, count: number): Promise<{
48
+ cursor: string;
49
+ keys: string[];
50
+ }>;
51
+ /**
43
52
  * Optional: run a server-side Lua script atomically (the Redis `EVAL` command — this is NOT the
44
53
  * JavaScript `eval()` sink; nothing in our process is dynamically executed). When implemented, the
45
54
  * stores use it for intra-store atomicity (§5.9) — create-if-absent, unique-index claim-or-fail,
@@ -76,7 +85,9 @@ interface RedisStoreOptions {
76
85
  /**
77
86
  * Key prefix for all keys. REQUIRED: there is no implicit default. In multi-tenant deployments
78
87
  * each tenant MUST use a distinct prefix (e.g. `ion:t:<tenantId>:`) so the global index sets
79
- * (`user:ids`, `tenant:ids`, etc.) auto-namespace and never collide across tenants.
88
+ * (`user:ids`, `tenant:ids`, etc.) auto-namespace and never collide across tenants. A missing
89
+ * trailing `:` is added, so `ion:t:acme` and `ion:t:acme:` name the same keyspace and every key
90
+ * lives under `<keyPrefix>:` (the unit `deleteKeyspace` removes).
80
91
  */
81
92
  keyPrefix: string;
82
93
  /** Logger for version warnings (default defaultLogger from core). */
@@ -92,6 +103,12 @@ interface RedisStoreOptions {
92
103
  * accidental shared keyspace loudly the first time.
93
104
  */
94
105
  declare function getKeyPrefix(options: RedisStoreOptions, storeKind?: string): string;
106
+ /**
107
+ * Validate a store `keyPrefix` and end it with the `:` segment separator. Without the separator,
108
+ * keys of tenant `acme` (`ion:t:acmeuser:...`) would share a textual prefix with tenant `acme-2`, so
109
+ * no prefix sweep could remove one tenant without touching the other.
110
+ */
111
+ declare function normalizeKeyPrefix(keyPrefix: unknown): string;
95
112
  declare function getLogger(options: RedisStoreOptions): Logger;
96
113
  declare function prefixedKey(prefix: string, ...parts: string[]): string;
97
114
  /**
@@ -374,6 +391,18 @@ declare function splitIonRedisSecret(secret: {
374
391
  redisUrl?: string;
375
392
  clientOptions: Record<string, unknown>;
376
393
  };
394
+ /**
395
+ * Yield pages of keys that start with `prefix`. Requires an adapter with `scan`; teardown tooling
396
+ * only, since `SCAN` walks the whole keyspace.
397
+ */
398
+ declare function scanKeysByPrefix(redis: RedisAdapter, prefix: string): AsyncGenerator<string[]>;
399
+ /**
400
+ * Delete every key under a store `keyPrefix`, normalized exactly as the stores normalize it, so
401
+ * passing the prefix a tenant's stores were built with removes that tenant's whole keyspace and
402
+ * nothing else. Use it for tenant teardown before a tenant id can be reused. Returns the number of
403
+ * keys deleted. Never pass a prefix shared by several tenants (such as a shared session store's).
404
+ */
405
+ declare function deleteKeyspace(redis: RedisAdapter, keyPrefix: string): Promise<number>;
377
406
  import { LfvCallbackTransport, Logger as Logger3 } from "@ionite/core";
378
407
  type RedisLfvTransportOptions = {
379
408
  channelPrefix?: string;
@@ -455,6 +484,14 @@ declare class RedisSessionStore<TExtended = object> implements SessionStore<TExt
455
484
  get(sid: string): Promise<Session<TExtended> | null>;
456
485
  update(sid: string, data: Partial<Session<TExtended>>): Promise<void>;
457
486
  delete(sid: string): Promise<void>;
487
+ /**
488
+ * Delete every session whose `tenantId` is one of `tenantIds`, with its idp-sid index entry. For
489
+ * tenant teardown when one store serves many tenants (a per-tenant store goes with
490
+ * `deleteKeyspace`). Pass every id the tenant's runtime may stamp: its `RemoteConfig.id`, which can
491
+ * differ from the App's tenant id. Scans this store's sessions, so it needs an adapter with `scan`
492
+ * and does not belong on a request path. Returns the number of sessions deleted.
493
+ */
494
+ deleteByTenant(tenantIds: string | readonly string[]): Promise<number>;
458
495
  deleteByIdpSid(idpSid: string): Promise<void>;
459
496
  }
460
497
  import { BaseTenant, Ionite, ListOptions as ListOptions6, ListResult as ListResult6, SetTenantIntegrationOptions, StagedRequestRecord, TenantIntegration, TenantIonCache, TenantStore } from "@ionite/core";
@@ -541,4 +578,4 @@ declare class RedisWorkloadTokenStore<TExtended = object> implements WorkloadTok
541
578
  isValid(workload_id: string): Promise<boolean>;
542
579
  cleanup(): Promise<void>;
543
580
  }
544
- export { AtomicCompareAndSetResult, AtomicCreateResult, DEFAULT_LIST_LIMIT, DEFAULT_MGET_CHUNK_SIZE, IonRedisOptions, MAX_LIST_LIMIT, ReactiveRedisAdapter, ReactiveRedisClient, ReactiveRedisOptions, RedisAccessAssignmentStore, RedisAccessCatalogStore, RedisAccessIndex, RedisAdapter, RedisCustomerStore, RedisCustomerStoreOptions, RedisDelegateStore, RedisDelegateStoreOptions, RedisLfvTransportOptions, RedisMagicLinkStore, RedisResourceStore, RedisSessionStore, RedisStoreOptions, RedisTenantStore, RedisTenantStoreOptions, RedisTxn, RedisUserStore, RedisUserStoreOptions, RedisWorkloadIdentityStore, RedisWorkloadIdentityStoreOptions, RedisWorkloadTokenStore, atomicCompareAndSet, atomicCreate, chunkedMget, createEvalshaRunner, createReactiveRedis, createRedisLfvTransport, encodeKeyId, getKeyPrefix, getLogger, prefixedKey, scriptSha1, splitIonRedisSecret, supportsRunScript };
581
+ export { AtomicCompareAndSetResult, AtomicCreateResult, DEFAULT_LIST_LIMIT, DEFAULT_MGET_CHUNK_SIZE, IonRedisOptions, MAX_LIST_LIMIT, ReactiveRedisAdapter, ReactiveRedisClient, ReactiveRedisOptions, RedisAccessAssignmentStore, RedisAccessCatalogStore, RedisAccessIndex, RedisAdapter, RedisCustomerStore, RedisCustomerStoreOptions, RedisDelegateStore, RedisDelegateStoreOptions, RedisLfvTransportOptions, RedisMagicLinkStore, RedisResourceStore, RedisSessionStore, RedisStoreOptions, RedisTenantStore, RedisTenantStoreOptions, RedisTxn, RedisUserStore, RedisUserStoreOptions, RedisWorkloadIdentityStore, RedisWorkloadIdentityStoreOptions, RedisWorkloadTokenStore, atomicCompareAndSet, atomicCreate, chunkedMget, createEvalshaRunner, createReactiveRedis, createRedisLfvTransport, deleteKeyspace, encodeKeyId, getKeyPrefix, getLogger, normalizeKeyPrefix, prefixedKey, scanKeysByPrefix, scriptSha1, splitIonRedisSecret, supportsRunScript };
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{accessRefId as J,accessRootId as et,assertRequiredSubjectType as ue,list as pe}from"@ionite/core";function A(e){return typeof e.runScript==="function"}async function _(e,t,s,r){let i=r?.ttlSeconds;if(A(e)){let o=`local cur=redis.call('GET',KEYS[1])
1
+ import{accessRefId as X,accessRootId as st,assertRequiredSubjectType as he,list as ye}from"@ionite/core";function A(e){return typeof e.runScript==="function"}async function _(e,t,s,r){let i=r?.ttlSeconds;if(A(e)){let o=`local cur=redis.call('GET',KEYS[1])
2
2
  if cur then if cur==ARGV[1] then return 'exists_identical' else return 'conflict' end end
3
3
  ${i!=null?"redis.call('SET',KEYS[1],ARGV[1],'EX',ARGV[2])":"redis.call('SET',KEYS[1],ARGV[1])"}
4
4
  return 'created'`,d=i!=null?[s,String(Math.max(1,Math.floor(i)))]:[s],l=String(await e.runScript(o,[t],d));return l==="exists_identical"||l==="conflict"?l:"created"}let a=await e.get(t);if(a!=null)return a===s?"exists_identical":"conflict";if(i!=null)await e.setex(t,Math.max(1,Math.floor(i)),s);else await e.set(t,s);return"created"}async function G(e,t,s,r,i){if(!A(e))return"unsupported";let a=i!=null&&i>0?Math.max(1,Math.floor(i)):void 0,o=`local cur=redis.call('GET',KEYS[1])
5
5
  if not cur then return 'missing' end
6
6
  if cur~=ARGV[1] then return 'retry' end
7
7
  ${a!=null?"redis.call('SET',KEYS[1],ARGV[2],'EX',ARGV[3])":"redis.call('SET',KEYS[1],ARGV[2],'KEEPTTL')"}
8
- return 'ok'`,d=a!=null?[s,r,String(a)]:[s,r],l=String(await e.runScript(o,[t],d));if(l==="missing"||l==="retry")return l;return"ok"}var z=500,$e=`local ki=1
8
+ return 'ok'`,d=a!=null?[s,r,String(a)]:[s,r],l=String(await e.runScript(o,[t],d));if(l==="missing"||l==="retry")return l;return"ok"}var J=500,We=`local ki=1
9
9
  local ai=1
10
10
  local C=tonumber(ARGV[ai]);ai=ai+1
11
11
  for i=1,C do
@@ -43,11 +43,11 @@ for i=1,W do
43
43
  redis.call('SREM',k,unpack(members))
44
44
  end
45
45
  end
46
- return 'ok'`;class w{constructor(){this.claims=[];this.writes=[]}claimUnique(e,t){return this.claims.push({key:e,owner:t}),this}set(e,t){return this.writes.push({op:"set",key:e,value:t}),this}setex(e,t,s){return this.writes.push({op:"setex",key:e,ttl:Math.max(1,Math.floor(t)),value:s}),this}del(e){return this.writes.push({op:"del",key:e}),this}sadd(e,...t){if(t.length>0)this.writes.push({op:"sadd",key:e,members:t});return this}srem(e,...t){if(t.length>0)this.writes.push({op:"srem",key:e,members:t});return this}async exec(e){if(A(e))return this.execLua(e);return this.execSequential(e)}async execLua(e){if(this.claims.length>0||this.writes.length<=z)return ne(e,this.claims,this.writes);for(let t=0;t<this.writes.length;t+=z)await ne(e,[],this.writes.slice(t,t+z));return"ok"}async execSequential(e){for(let t of this.claims){let s=await e.get(t.key);if(s!=null&&s!==t.owner)return"conflict"}for(let t of this.writes)switch(t.op){case"set":await e.set(t.key,t.value);break;case"setex":await e.setex(t.key,t.ttl,t.value);break;case"del":await e.del(t.key);break;case"sadd":await e.sadd(t.key,...t.members);break;case"srem":await e.srem(t.key,...t.members);break}return"ok"}}async function ne(e,t,s){let r=[],i=[String(t.length)];for(let n of t)r.push(n.key),i.push(n.owner);i.push(String(s.length));for(let n of s)switch(n.op){case"set":i.push("set"),r.push(n.key),i.push(n.value);break;case"setex":i.push("setex"),r.push(n.key),i.push(String(n.ttl),n.value);break;case"del":i.push("del"),r.push(n.key);break;case"sadd":i.push("sadd"),r.push(n.key),i.push(String(n.members.length),...n.members);break;case"srem":i.push("srem"),r.push(n.key),i.push(String(n.members.length),...n.members);break}return String(await e.runScript($e,r,i))==="conflict"?"conflict":"ok"}import{list as ze,matchesListFilter as We}from"@ionite/core";var ae=100,oe=1000;function C(e){let t=e?.limit,s=t==null||!Number.isFinite(t)||t<=0?ae:Math.min(Math.floor(t),oe);return{...e,limit:s}}function R(e,t,s=(r,i)=>r[i]){let r=Math.max(0,t?.start??0),i=t?.limit,a=t?.filter?e.filter((l)=>We({requestable:s(l,"requestable"),userName:s(l,"userName"),clientId:s(l,"clientId"),externalId:s(l,"externalId"),updatedAt:s(l,"updatedAt")},t.filter)):e,n=a.length,o=i!=null?r+i:void 0,d=a.slice(r,o);return ze(n,d,r,i)}import{defaultLogger as Je}from"@ionite/core";function f(e,t){let s=t.log??Je,r={"ion.operation":"redis.revive","ion.outcome":"corrupt",store:t.store,...t.key?{key:t.key}:{}},i;try{i=JSON.parse(e)}catch{s.warn("Redis store: discarded corrupt JSON payload (failed to parse)",r);return}if(i===null||typeof i!=="object"||Array.isArray(i)){s.warn("Redis store: discarded JSON payload that is not a record object",r);return}return i}import{createHash as Fe}from"node:crypto";import{defaultLogger as Xe}from"@ionite/core";var Ze=4096,de=new Set,ce=new Set;function le(e,t){e.delete(t),e.add(t);while(e.size>Ze){let s=e.values().next().value;if(s===void 0)break;e.delete(s)}}function x(e,t){let s=e.keyPrefix;if(typeof s!=="string"||s.length===0)throw Error('Redis store keyPrefix is required and must be a non-empty string. Pass an explicit per-tenant prefix (e.g. "ion:t:<tenantId>:") so tenant keyspaces never collide.');if(t){let r=`${t}\x00${s}`;if(de.has(r)&&!ce.has(r))m(e).warn(`Redis ${t} constructed twice with the same keyPrefix "${s}". Each tenant MUST use a distinct keyPrefix (e.g. "ion:t:<tenantId>:") so tenant keyspaces never collide; sharing a prefix across tenants lets them read/write each other's data.`),le(ce,r);le(de,r)}return s}function m(e){return e.logger??Xe}function S(e,...t){return e+t.join(":")}var Qe=/^[A-Za-z0-9_.@|-]{1,64}$/;function g(e){if(Qe.test(e))return`=${e}`;return`#${Fe("sha256").update(e,"utf8").digest("base64url").slice(0,22)}`}var tt="access:ids",st="access:subject:",it="access:target:";function rt(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()})}function W(e,t){let s=f(e,{store:"access",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt)}}function ge(e){return{id:e.id,subject:e.subject,subjectType:e.subjectType,targetType:e.targetType,target:e.target,resources:e.resources,applyToApplication:e.applyToApplication,provenance:e.provenance,status:e.status,metadata:e.metadata}}function he(e){let t=J(e.subject),s=J(e.target);if(!t)throw Error("Access change subject must resolve to a non-empty id.");if(!e.targetType)throw Error("Access change targetType is required.");if(!s)throw Error("Access change target must resolve to a non-empty id.");return{id:e.id??et(e),subjectId:t,targetId:s}}class ye{constructor(e){this.redis=e.redis,this.prefix=x(e,"access-assignment-store"),this.log=m(e)}key(...e){return S(this.prefix,...e)}idsSetKey(){return this.key(tt)}accessStorageKey(e){return this.key("access",g(e))}subjectIndexKey(e,t){return this.key(`${st}${t}:${g(e)}`)}targetIndexKey(e,t){return this.key(it+e,g(t))}async grant(e){ue(e.subjectType,"Access change subjectType");let t=he(e),s=this.accessStorageKey(t.id),r=await this.redis.get(s),i=r?W(r,this.log):void 0,a=new Date,n={...e,id:t.id,status:e.status??"active",subjectId:t.subjectId,targetId:t.targetId,createdAt:i?.createdAt??a,updatedAt:a},o=new w;o.set(s,rt(n)),o.sadd(this.idsSetKey(),t.id),o.sadd(this.subjectIndexKey(t.subjectId,e.subjectType),t.id),o.sadd(this.targetIndexKey(e.targetType,t.targetId),t.id),await o.exec(this.redis)}async revoke(e){let t=he(e);if(await this.redis.get(this.accessStorageKey(t.id))==null)return;let r=new w;r.del(this.accessStorageKey(t.id)),r.srem(this.idsSetKey(),t.id),r.srem(this.subjectIndexKey(t.subjectId,e.subjectType),t.id),r.srem(this.targetIndexKey(e.targetType,t.targetId),t.id),await r.exec(this.redis)}async get(e){let t=await this.redis.get(this.accessStorageKey(e));if(t==null)return;let s=W(t,this.log);return s?ge(s):void 0}async list(e){return this.listInMemory(C(e))}async listByTarget(e,t,s){let r=await this.redis.smembers(this.targetIndexKey(e,t.trim()));return this.listFromIds(r,s)}async listBySubject(e,t,s){ue(t);let r=J(e);if(!r)return pe(0,[],s?.start??0,s?.limit);let i=await this.redis.smembers(this.subjectIndexKey(r,t));return this.listFromIds(i,s)}async listInMemory(e){let t=await this.redis.smembers(this.idsSetKey());return this.listFromIds(t,e)}async listFromIds(e,t){if(e.length===0)return pe(0,[],t?.start??0,t?.limit);let r=[...e].sort().map((o)=>this.accessStorageKey(o)),a=(await this.redis.mget(r)).filter((o)=>o!=null).map((o)=>W(o,this.log)).filter((o)=>o!=null).filter((o)=>(o.status??"active")==="active"),n=R(a,t);return{...n,items:n.items.map(ge)}}}import{assertValidSubjectTypeScoping as fe,deepEqualPlain as nt,readyCatalogEntry as me}from"@ionite/core";class Se{constructor(e){this.listeners=new Set;let t=e.redis,s=x(e,"access-catalog-store"),r=m(e),i=(a)=>{for(let n of this.listeners)n(a)};this.groups=new B(t,s,"group",i,r),this.roles=new B(t,s,"role",i,r),this.permissions=new B(t,s,"permission",i,r)}afterChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}}class we{constructor(e){this.listeners=new Set;this.redis=e.redis,this.prefix=x(e,"resource-store"),this.log=m(e)}key(...e){return S(this.prefix,"authz","resource",...e)}entityKey(e){return this.key(g(e))}idsSetKey(){return this.key("ids")}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;let s=f(t,{store:"authz:resource",key:e,log:this.log});return s===void 0?void 0:s}async list(e){let t=await this.redis.smembers(this.idsSetKey());if(t.length===0)return R([],e);let r=(await this.redis.mget(t.map((i)=>this.entityKey(i)))).filter((i)=>i!=null).map((i)=>f(i,{store:"authz:resource",log:this.log})).filter((i)=>i!==void 0).map((i)=>i);return R(r,e)}async children(e){return(await this.list()).items.filter((s)=>(typeof s.parent==="string"?s.parent:s.parent?.id)===e)}changed(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async set(e){await new w().set(this.entityKey(e.id),JSON.stringify(e)).sadd(this.idsSetKey(),e.id).exec(this.redis),this.emitChange({id:e.id})}async delete(e){await new w().del(this.entityKey(e)).srem(this.idsSetKey(),e).exec(this.redis),this.emitChange({id:e,deleted:!0})}emitChange(e){for(let t of this.listeners)t(e)}}class B{constructor(e,t,s,r,i){this.redis=e;this.prefix=t;this.kind=s;this.emit=r;this.log=i}key(...e){return S(this.prefix,"authz",this.kind,...e)}idsSetKey(){return this.key("ids")}entityKey(e){return this.key(g(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;let s=f(t,{store:`authz:${this.kind}`,key:e,log:this.log});return s===void 0?void 0:s}set(e){fe(e);let t,s=!0,r=(async()=>{t=await this.get(e.id),s=!t||!nt(t,e);let i=new w;i.set(this.entityKey(e.id),JSON.stringify(e)),i.sadd(this.idsSetKey(),e.id),await i.exec(this.redis)})();return r.then(()=>{if(!s)return;this.emit({op:"set",kind:this.kind,entity:e,previous:t})},(i)=>{this.log?.warn("authz catalog store: background persist failed",{"ion.operation":`authz.catalog.${this.kind}.set`,"ion.outcome":"error",id:e.id,error:i instanceof Error?i.message:String(i)})}),me(e,r)}insertIfAbsent(e){fe(e);let t={...e},s=!1,r=(async()=>{if(!A(this.redis))throw Error("RedisAccessCatalogStore.insertIfAbsent requires a Redis adapter with runScript support.");let i=JSON.stringify(e),a=await this.redis.runScript(`local cur=redis.call('GET',KEYS[1])
46
+ return 'ok'`;class w{constructor(){this.claims=[];this.writes=[]}claimUnique(e,t){return this.claims.push({key:e,owner:t}),this}set(e,t){return this.writes.push({op:"set",key:e,value:t}),this}setex(e,t,s){return this.writes.push({op:"setex",key:e,ttl:Math.max(1,Math.floor(t)),value:s}),this}del(e){return this.writes.push({op:"del",key:e}),this}sadd(e,...t){if(t.length>0)this.writes.push({op:"sadd",key:e,members:t});return this}srem(e,...t){if(t.length>0)this.writes.push({op:"srem",key:e,members:t});return this}async exec(e){if(A(e))return this.execLua(e);return this.execSequential(e)}async execLua(e){if(this.claims.length>0||this.writes.length<=J)return de(e,this.claims,this.writes);for(let t=0;t<this.writes.length;t+=J)await de(e,[],this.writes.slice(t,t+J));return"ok"}async execSequential(e){for(let t of this.claims){let s=await e.get(t.key);if(s!=null&&s!==t.owner)return"conflict"}for(let t of this.writes)switch(t.op){case"set":await e.set(t.key,t.value);break;case"setex":await e.setex(t.key,t.ttl,t.value);break;case"del":await e.del(t.key);break;case"sadd":await e.sadd(t.key,...t.members);break;case"srem":await e.srem(t.key,...t.members);break}return"ok"}}async function de(e,t,s){let r=[],i=[String(t.length)];for(let n of t)r.push(n.key),i.push(n.owner);i.push(String(s.length));for(let n of s)switch(n.op){case"set":i.push("set"),r.push(n.key),i.push(n.value);break;case"setex":i.push("setex"),r.push(n.key),i.push(String(n.ttl),n.value);break;case"del":i.push("del"),r.push(n.key);break;case"sadd":i.push("sadd"),r.push(n.key),i.push(String(n.members.length),...n.members);break;case"srem":i.push("srem"),r.push(n.key),i.push(String(n.members.length),...n.members);break}return String(await e.runScript(We,r,i))==="conflict"?"conflict":"ok"}import{list as Je,matchesListFilter as Fe}from"@ionite/core";var ce=100,le=1000;function C(e){let t=e?.limit,s=t==null||!Number.isFinite(t)||t<=0?ce:Math.min(Math.floor(t),le);return{...e,limit:s}}function R(e,t,s=(r,i)=>r[i]){let r=Math.max(0,t?.start??0),i=t?.limit,a=t?.filter?e.filter((l)=>Fe({requestable:s(l,"requestable"),userName:s(l,"userName"),clientId:s(l,"clientId"),externalId:s(l,"externalId"),updatedAt:s(l,"updatedAt")},t.filter)):e,n=a.length,o=i!=null?r+i:void 0,d=a.slice(r,o);return Je(n,d,r,i)}import{defaultLogger as Xe}from"@ionite/core";function m(e,t){let s=t.log??Xe,r={"ion.operation":"redis.revive","ion.outcome":"corrupt",store:t.store,...t.key?{key:t.key}:{}},i;try{i=JSON.parse(e)}catch{s.warn("Redis store: discarded corrupt JSON payload (failed to parse)",r);return}if(i===null||typeof i!=="object"||Array.isArray(i)){s.warn("Redis store: discarded JSON payload that is not a record object",r);return}return i}import{createHash as Ze}from"node:crypto";import{defaultLogger as Qe}from"@ionite/core";var et=4096,ue=new Set,pe=new Set;function ge(e,t){e.delete(t),e.add(t);while(e.size>et){let s=e.values().next().value;if(s===void 0)break;e.delete(s)}}function x(e,t){let s=N(e.keyPrefix);if(t){let r=`${t}\x00${s}`;if(ue.has(r)&&!pe.has(r))S(e).warn(`Redis ${t} constructed twice with the same keyPrefix "${s}". Each tenant MUST use a distinct keyPrefix (e.g. "ion:t:<tenantId>:") so tenant keyspaces never collide; sharing a prefix across tenants lets them read/write each other's data.`),ge(pe,r);ge(ue,r)}return s}function N(e){if(typeof e!=="string"||e.length===0)throw Error('Redis store keyPrefix is required and must be a non-empty string. Pass an explicit per-tenant prefix (e.g. "ion:t:<tenantId>:") so tenant keyspaces never collide.');return e.endsWith(":")?e:`${e}:`}function S(e){return e.logger??Qe}function f(e,...t){return e+t.join(":")}var tt=/^[A-Za-z0-9_.@|-]{1,64}$/;function h(e){if(tt.test(e))return`=${e}`;return`#${Ze("sha256").update(e,"utf8").digest("base64url").slice(0,22)}`}var it="access:ids",rt="access:subject:",nt="access:target:";function at(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()})}function F(e,t){let s=m(e,{store:"access",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt)}}function fe(e){return{id:e.id,subject:e.subject,subjectType:e.subjectType,targetType:e.targetType,target:e.target,resources:e.resources,applyToApplication:e.applyToApplication,provenance:e.provenance,status:e.status,metadata:e.metadata}}function me(e){let t=X(e.subject),s=X(e.target);if(!t)throw Error("Access change subject must resolve to a non-empty id.");if(!e.targetType)throw Error("Access change targetType is required.");if(!s)throw Error("Access change target must resolve to a non-empty id.");return{id:e.id??st(e),subjectId:t,targetId:s}}class Se{constructor(e){this.redis=e.redis,this.prefix=x(e,"access-assignment-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}idsSetKey(){return this.key(it)}accessStorageKey(e){return this.key("access",h(e))}subjectIndexKey(e,t){return this.key(`${rt}${t}:${h(e)}`)}targetIndexKey(e,t){return this.key(nt+e,h(t))}async grant(e){he(e.subjectType,"Access change subjectType");let t=me(e),s=this.accessStorageKey(t.id),r=await this.redis.get(s),i=r?F(r,this.log):void 0,a=new Date,n={...e,id:t.id,status:e.status??"active",subjectId:t.subjectId,targetId:t.targetId,createdAt:i?.createdAt??a,updatedAt:a},o=new w;o.set(s,at(n)),o.sadd(this.idsSetKey(),t.id),o.sadd(this.subjectIndexKey(t.subjectId,e.subjectType),t.id),o.sadd(this.targetIndexKey(e.targetType,t.targetId),t.id),await o.exec(this.redis)}async revoke(e){let t=me(e);if(await this.redis.get(this.accessStorageKey(t.id))==null)return;let r=new w;r.del(this.accessStorageKey(t.id)),r.srem(this.idsSetKey(),t.id),r.srem(this.subjectIndexKey(t.subjectId,e.subjectType),t.id),r.srem(this.targetIndexKey(e.targetType,t.targetId),t.id),await r.exec(this.redis)}async get(e){let t=await this.redis.get(this.accessStorageKey(e));if(t==null)return;let s=F(t,this.log);return s?fe(s):void 0}async list(e){return this.listInMemory(C(e))}async listByTarget(e,t,s){let r=await this.redis.smembers(this.targetIndexKey(e,t.trim()));return this.listFromIds(r,s)}async listBySubject(e,t,s){he(t);let r=X(e);if(!r)return ye(0,[],s?.start??0,s?.limit);let i=await this.redis.smembers(this.subjectIndexKey(r,t));return this.listFromIds(i,s)}async listInMemory(e){let t=await this.redis.smembers(this.idsSetKey());return this.listFromIds(t,e)}async listFromIds(e,t){if(e.length===0)return ye(0,[],t?.start??0,t?.limit);let r=[...e].sort().map((o)=>this.accessStorageKey(o)),a=(await this.redis.mget(r)).filter((o)=>o!=null).map((o)=>F(o,this.log)).filter((o)=>o!=null).filter((o)=>(o.status??"active")==="active"),n=R(a,t);return{...n,items:n.items.map(fe)}}}import{assertValidSubjectTypeScoping as we,deepEqualPlain as ot,readyCatalogEntry as xe}from"@ionite/core";class ke{constructor(e){this.listeners=new Set;let t=e.redis,s=x(e,"access-catalog-store"),r=S(e),i=(a)=>{for(let n of this.listeners)n(a)};this.groups=new H(t,s,"group",i,r),this.roles=new H(t,s,"role",i,r),this.permissions=new H(t,s,"permission",i,r)}afterChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}}class Te{constructor(e){this.listeners=new Set;this.redis=e.redis,this.prefix=x(e,"resource-store"),this.log=S(e)}key(...e){return f(this.prefix,"authz","resource",...e)}entityKey(e){return this.key(h(e))}idsSetKey(){return this.key("ids")}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;let s=m(t,{store:"authz:resource",key:e,log:this.log});return s===void 0?void 0:s}async list(e){let t=await this.redis.smembers(this.idsSetKey());if(t.length===0)return R([],e);let r=(await this.redis.mget(t.map((i)=>this.entityKey(i)))).filter((i)=>i!=null).map((i)=>m(i,{store:"authz:resource",log:this.log})).filter((i)=>i!==void 0).map((i)=>i);return R(r,e)}async children(e){return(await this.list()).items.filter((s)=>(typeof s.parent==="string"?s.parent:s.parent?.id)===e)}changed(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async set(e){await new w().set(this.entityKey(e.id),JSON.stringify(e)).sadd(this.idsSetKey(),e.id).exec(this.redis),this.emitChange({id:e.id})}async delete(e){await new w().del(this.entityKey(e)).srem(this.idsSetKey(),e).exec(this.redis),this.emitChange({id:e,deleted:!0})}emitChange(e){for(let t of this.listeners)t(e)}}class H{constructor(e,t,s,r,i){this.redis=e;this.prefix=t;this.kind=s;this.emit=r;this.log=i}key(...e){return f(this.prefix,"authz",this.kind,...e)}idsSetKey(){return this.key("ids")}entityKey(e){return this.key(h(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;let s=m(t,{store:`authz:${this.kind}`,key:e,log:this.log});return s===void 0?void 0:s}set(e){we(e);let t,s=!0,r=(async()=>{t=await this.get(e.id),s=!t||!ot(t,e);let i=new w;i.set(this.entityKey(e.id),JSON.stringify(e)),i.sadd(this.idsSetKey(),e.id),await i.exec(this.redis)})();return r.then(()=>{if(!s)return;this.emit({op:"set",kind:this.kind,entity:e,previous:t})},(i)=>{this.log?.warn("authz catalog store: background persist failed",{"ion.operation":`authz.catalog.${this.kind}.set`,"ion.outcome":"error",id:e.id,error:i instanceof Error?i.message:String(i)})}),xe(e,r)}insertIfAbsent(e){we(e);let t={...e},s=!1,r=(async()=>{if(!A(this.redis))throw Error("RedisAccessCatalogStore.insertIfAbsent requires a Redis adapter with runScript support.");let i=JSON.stringify(e),a=await this.redis.runScript(`local cur=redis.call('GET',KEYS[1])
47
47
  if cur then return {0,cur} end
48
48
  redis.call('SET',KEYS[1],ARGV[1])
49
49
  redis.call('SADD',KEYS[2],ARGV[2])
50
- return {1,ARGV[1]}`,[this.entityKey(e.id),this.idsSetKey()],[i,e.id]);if(!Array.isArray(a)||a.length<2)throw Error("RedisAccessCatalogStore.insertIfAbsent received an invalid Redis response.");s=String(a[0])==="1";let n=String(a[1]),o=f(n,{store:`authz:${this.kind}`,key:e.id,log:this.log});if(!o)throw Error("RedisAccessCatalogStore.insertIfAbsent could not parse the winning row.");let d=t;for(let l of Object.keys(d))delete d[l];Object.assign(d,o)})();return r.then(()=>{if(!s)return;this.emit({op:"set",kind:this.kind,entity:t,previous:void 0})},(i)=>{this.log?.warn("authz catalog store: atomic insert-if-absent failed",{"ion.operation":`authz.catalog.${this.kind}.insert_if_absent`,"ion.outcome":"error",id:e.id,error:i instanceof Error?i.message:String(i)})}),me(t,r)}async delete(e){let t=await this.get(e),s=new w;if(s.del(this.entityKey(e)),s.srem(this.idsSetKey(),e),await s.exec(this.redis),!t)return;this.emit({op:"delete",kind:this.kind,entity:t})}async list(e){let t=await this.redis.smembers(this.idsSetKey());if(t.length===0)return R([],e);let r=(await this.redis.mget(t.map((i)=>this.entityKey(i)))).filter((i)=>i!=null).map((i)=>f(i,{store:`authz:${this.kind}`,log:this.log})).filter((i)=>i!==void 0).map((i)=>i);return R(r,e)}}import{accessRefId as K,assertRequiredSubjectType as O}from"@ionite/core";var H="__app__",xe=100;function at(e){if(!Array.isArray(e))return[];return e.map((t)=>t==null?"":String(t)).filter((t)=>t.length>0)}var ot=`local rootId=ARGV[1]
50
+ return {1,ARGV[1]}`,[this.entityKey(e.id),this.idsSetKey()],[i,e.id]);if(!Array.isArray(a)||a.length<2)throw Error("RedisAccessCatalogStore.insertIfAbsent received an invalid Redis response.");s=String(a[0])==="1";let n=String(a[1]),o=m(n,{store:`authz:${this.kind}`,key:e.id,log:this.log});if(!o)throw Error("RedisAccessCatalogStore.insertIfAbsent could not parse the winning row.");let d=t;for(let l of Object.keys(d))delete d[l];Object.assign(d,o)})();return r.then(()=>{if(!s)return;this.emit({op:"set",kind:this.kind,entity:t,previous:void 0})},(i)=>{this.log?.warn("authz catalog store: atomic insert-if-absent failed",{"ion.operation":`authz.catalog.${this.kind}.insert_if_absent`,"ion.outcome":"error",id:e.id,error:i instanceof Error?i.message:String(i)})}),xe(t,r)}async delete(e){let t=await this.get(e),s=new w;if(s.del(this.entityKey(e)),s.srem(this.idsSetKey(),e),await s.exec(this.redis),!t)return;this.emit({op:"delete",kind:this.kind,entity:t})}async list(e){let t=await this.redis.smembers(this.idsSetKey());if(t.length===0)return R([],e);let r=(await this.redis.mget(t.map((i)=>this.entityKey(i)))).filter((i)=>i!=null).map((i)=>m(i,{store:`authz:${this.kind}`,log:this.log})).filter((i)=>i!==void 0).map((i)=>i);return R(r,e)}}import{accessRefId as P,assertRequiredSubjectType as O}from"@ionite/core";var q="__app__",Re=100;function dt(e){if(!Array.isArray(e))return[];return e.map((t)=>t==null?"":String(t)).filter((t)=>t.length>0)}var ct=`local rootId=ARGV[1]
51
51
  local A=tonumber(ARGV[2])
52
52
  local R=tonumber(ARGV[3])
53
53
  local rootKey=KEYS[1]
@@ -96,7 +96,7 @@ for i=0,R-1 do
96
96
  end
97
97
  redis.call('SREM',rootKey,descriptor)
98
98
  end
99
- return 'ok'`,dt=`local rootId=ARGV[1]
99
+ return 'ok'`,lt=`local rootId=ARGV[1]
100
100
  local n=tonumber(ARGV[2])
101
101
  for i=0,n-1 do
102
102
  local kb=1+i*5
@@ -120,7 +120,7 @@ for i=0,n-1 do
120
120
  end
121
121
  end
122
122
  redis.call('DEL',KEYS[1])
123
- return 'ok'`,ct=`local n=tonumber(ARGV[1])
123
+ return 'ok'`,ut=`local n=tonumber(ARGV[1])
124
124
  local roots={}
125
125
  local seen={}
126
126
  for i=0,n-1 do
@@ -139,8 +139,8 @@ for i=0,n-1 do
139
139
  redis.call('DEL',ak)
140
140
  end
141
141
  redis.call('DEL',KEYS[1])
142
- return roots`,lt=`for i=1,#KEYS do redis.call('DEL',KEYS[i]) end
143
- return 'ok'`,ut=`local subjectMember=ARGV[1]
142
+ return roots`,pt=`for i=1,#KEYS do redis.call('DEL',KEYS[i]) end
143
+ return 'ok'`,gt=`local subjectMember=ARGV[1]
144
144
  local C=tonumber(ARGV[2])
145
145
  local R=tonumber(ARGV[3])
146
146
  local D=tonumber(ARGV[4])
@@ -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 N(e){return e&&e.length>0?e:H}function F(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??H}}class ke{constructor(e){this.redis=e.redis,this.prefix=x(e,"access-index"),this.log=m(e)}key(...e){return S(this.prefix,...e)}subjectKeyPart(e){let t=e.indexOf(":");if(t<=0)return g(e);return`${e.slice(0,t)}:${g(e.slice(t+1))}`}hasKey(e,t,s,r){return this.key("idx:has",this.subjectKeyPart(e),t,g(s),g(r))}anyKey(e,t,s){return this.key("idx:any",this.subjectKeyPart(e),t,g(s))}edgeRootsKey(e,t,s,r){return this.key("idx:er",this.subjectKeyPart(e),t,g(s),g(r))}tripleKey(e,t,s){return this.key("idx:tr",this.subjectKeyPart(e),t,g(s))}rootKey(e){return this.key("idx:root",g(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=K(e),n=K(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=K(r),l=await this.redis.mget([this.disabledKey(o),this.hasKey(o,t,n,N(d)),this.hasKey(o,t,n,H)]);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=K(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=K(e);if(!r)return t.map(()=>({allow:!1}));let i=D(r,s),a=[this.disabledKey(i)],n=t.map((d)=>{let l=K(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=K(d.resource),E=a.push(this.hasKey(i,d.targetType,l,N(p)))-1,y=a.push(this.hasKey(i,d.targetType,l,H))-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=K(n.subject),d=K(n.target);if(!o||!d)continue;O(n.subjectType,"Effective edge subjectType");let l=D(o,n.subjectType),p=N(n.resource),E={subject:l,targetType:n.targetType,target:d,rToken:p};s.set(F(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(ot,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=K(e);if(!r)return;let i=D(r,t),a=[];for(let y of s){let T=K(y.subject);O(y.subjectType,"Effective edge subjectType");let v=y.subjectType;if(T!==r||v!==t)throw Error(`AccessIndex.replaceSubject received an edge for ${v}:${T}; expected ${i}.`);let b=K(y.target);if(!b)continue;let I={subject:i,targetType:y.targetType,target:b,rToken:N(y.resource)};a.push({rootId:y.rootId,encoded:F(I),d:I})}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,v,b,I]=this.edgeKeys(y);p.push(T,v,b,I)}for(let y of l)p.push(this.rootKey(y));for(let y of a){let[T,v,b,I]=this.edgeKeys(y.d);p.push(this.rootKey(y.rootId),T,v,b,I)}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(ut,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(dt,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=K(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=K(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=K(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=at(await this.redis.runScript(ct,r,[String(s.length)]));if(i.length>0)await this.redis.runScript(lt,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=F({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<=xe)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:xe})}}var pt=512;async function gt(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 ht,StoreConflictError as yt}from"@ionite/core";var ft="customer:ids",mt="customer:name:",St="customer:external:";function wt(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 X(e,t){let s=f(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 Te{constructor(e){this.redis=e.redis,this.prefix=x(e,"customer-store"),this.log=m(e)}key(...e){return S(this.prefix,...e)}entityKey(e){return this.key("customer",g(e))}idsSetKey(){return this.key(ft)}nameIndexKey(e){return this.key(mt+g(e))}externalIdIndexKey(e){return this.key(St+g(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return X(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?X(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,wt(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 yt(`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 ht(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)=>X(n,this.log)).filter((n)=>n!=null);return R(a,t)}}import{StoreConflictError as xt}from"@ionite/core";var kt="delegate:ids";function Re(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 Z(e,t){let s=f(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 Ae{constructor(e){this.redis=e.redis,this.prefix=x(e,"delegate-store"),this.log=m(e)}key(...e){return S(this.prefix,...e)}entityKey(e){return this.key("delegate",g(e))}tokenHashKey(e){return this.key("delegate:token",g(e))}externalIdKey(e){return this.key("delegate:external",g(e))}idsSetKey(){return this.key(kt)}async get(e){let t=await this.redis.get(this.entityKey(e));return t==null?void 0:Z(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),Re(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 xt("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=Z(i,this.log);if(!a)return;let n=Re({...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)=>Z(s,this.log)).filter((s)=>s!==void 0)}}import{createHash as Tt}from"node:crypto";function Ee(e){return Tt("sha1").update(e,"utf8").digest("hex")}function Rt(e){return(e instanceof Error?e.message:String(e)).includes("NOSCRIPT")}function At(e){let t=new Map;return async(s,r,i)=>{let a=t.get(s);if(!a)a=Ee(s),t.set(s,a);try{return await e.evalsha(a,r,i)}catch(n){if(Rt(n))return e.eval(s,r,i);throw n}}}function be(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Et(e){let t=be(e.clientOptions)?{...e.clientOptions}:be(e)?{...e}:{};return delete t.redisUrl,delete t.clientOptions,{redisUrl:(typeof e.redisUrl==="string"?e.redisUrl.trim():"")||void 0,clientOptions:t}}import{defaultLogger as bt}from"@ionite/core";function ve(e,t){return`${e}:${encodeURIComponent(t)}`}function vt(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 It(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??bt;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(ve(r,a),d,JSON.stringify(n))},async take(a){let n=await s(ve(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(!vt(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 Kt}from"@ionite/core";function Pt(e){return JSON.stringify({token:e.token,customer:e.customer,createdAt:e.createdAt.toISOString(),expiresAt:e.expiresAt.toISOString()})}function Ie(e,t){let s=f(e,{store:"magic-link",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),expiresAt:new Date(s.expiresAt)}}class Ke{constructor(e){this.redis=e.redis,this.prefix=x(e,"magic-link-store"),this.log=m(e)}key(e){return S(this.prefix,"magic",g(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,Pt(i),{ttlSeconds:a})==="conflict")throw new Kt(`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 Ie(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=Ie(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 Lt}from"@ionite/core";function Ct(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 Dt(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}function Pe(e){return typeof e==="function"}function Ot(e){let t=e.logger??Lt,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,v=Promise.resolve(),b=Dt();b.promise.catch(()=>{});let I={async get(c){return P((u)=>u.get(c))},async set(c,u){await P((h)=>h.set(c,u))},async setex(c,u,h){await P((k)=>k.setex(c,u,h))},async expire(c,u){await P((h)=>h.expire(c,u))},async del(c){await P((u)=>u.del(c))},async sadd(c,...u){await P((h)=>h.sadd(c,...u))},async srem(c,...u){await P((h)=>h.srem(c,...u))},async smembers(c){return P((u)=>u.smembers(c))},async mget(c){return P((u)=>u.mget(c))},async publish(c,u){await P(async(h)=>{if(!h.publish)throw Error("Active Redis adapter does not support publish (Pub/Sub)");await h.publish(c,u)})},async subscribeChannel(c,u){let h=T.get(c);if(!h){let L=new Set;h={listeners:L,dispatch:(Me)=>{for(let Ye of Array.from(L))try{Ye(Me)}catch(Y){t.warn("Redis channel listener threw",{"ion.operation":"redis.adapter.subscribe","ion.outcome":"failure",sourceName:s,path:r,channel:c,error:Y instanceof Error?Y.message:String(Y)})}}},T.set(c,h)}let k=h;k.listeners.add(u);try{await He(c,k)}catch(L){if(k.listeners.delete(u),k.listeners.size===0)T.delete(c);throw L}return async()=>{if(k.listeners.delete(u),k.listeners.size===0){T.delete(c);let L=k.unsubscribe;k.unsubscribe=void 0,await L?.()}}},ready(c){return Ct(b.promise,c)},isReady(){return i!==void 0},async close(){if(p=!0,re(),!n)n=!0,b.reject(Error(`Reactive Redis adapter for source "${s}" at path "${r}" was closed before becoming ready.`));await v.catch(()=>{}),await U(i),i=void 0;for(let c of T.values())c.unsubscribe=void 0;T.clear(),M()}};function se(c){v=v.then(c).catch((u)=>{if(!n)n=!0,b.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 ie(){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 v.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 b.promise,p)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" is closed.`);let h=i?.adapter;if(!h)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" did not become ready.`);return h}async function P(c){let u=await ie();return c(u)}function re(){a?.(),a=void 0}async function He(c,u){if(u.unsubscribe)return;if(!u.attaching)u.attaching=(async()=>{let h=await ie();if(!h.subscribeChannel)throw Error("Active Redis adapter does not support subscribeChannel (Pub/Sub)");if(u.listeners.size===0)return;u.unsubscribe=await h.subscribeChannel(c,u.dispatch)})().finally(()=>{u.attaching=void 0});await u.attaching}async function Ve(c){for(let[u,h]of T){if(h.attaching)await h.attaching.catch(()=>{});if(h.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{h.unsubscribe=await c.subscribeChannel(u,h.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 qe(c){re(),a=await c.subscribe(r,(u)=>{se(async()=>{if(p)return;await Ue(u)})},e.subscription??e.secretOptions)}async function Ue(c){if(p)return;let u=`${s}:${r}:${c.metadata.version}`;if(i!==void 0&&d===u&&o===c.metadata.version)return;let h=e.endpointOf?.(c);if(i!==void 0&&h!=null&&h!==""&&l!=null&&l!==""&&h!==l)throw Error(`Reactive Redis adapter for source "${s}" at path "${r}" rejected a rotation that changed the endpoint (${l} -> ${h}); only credentials may rotate under an active adapter.`);let k=await e.createClient(c);if(p){await U(k);return}let L=i;if(i=k,d=u,o=c.metadata.version,h!=null&&h!=="")l=h;if(M(),L!==void 0)await Ve(k.adapter);if(!n)n=!0,b.resolve();await U(L)}async function U(c){if(!c?.dispose)return;await c.dispose()}function M(){let c=i?.adapter;if(c?.runScript&&Pe(c.runScript))I.runScript=async(u,h,k)=>P(async(L)=>{if(!L.runScript)throw Error("Active Redis adapter does not support runScript");return L.runScript(u,h,k)});else if(delete I.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&&Pe(c.getdel))I.getdel=async(u)=>P(async(h)=>{if(!h.getdel)return null;return h.getdel(u)});else if(delete I.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"})}return M(),se(async()=>{if(p)return;await qe(e.source)}),I}import{StoreConflictError as jt}from"@ionite/core";var _t=5;function Gt(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 Le(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString()})}function V(e,t){let s=f(e,{store:"session",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt)}}function Q(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 Ce{constructor(e){this.capabilities={derivedEntitlements:!0};this.redis=e.redis,this.prefix=x(e,"session-store"),this.log=m(e)}key(e){return S(this.prefix,"session",g(e))}idpSidKey(e){return S(this.prefix,"session-idp-sid",g(e))}async addToIdpIndex(e){if(!e.idpSid)return;let t=this.idpSidKey(e.idpSid);await this.redis.sadd(t,e.sid);let s=Q(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=Q(e.expiresAt);if(await _(this.redis,t,Le(e),{ttlSeconds:s})==="conflict")throw new jt(`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 V(t,this.log)??null}async update(e,t){let s=this.key(e),r=await this.redis.get(s),i=r==null?void 0:V(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?Q(o.expiresAt):void 0;if(A(this.redis))for(let T=0;T<_t;T++){let v=await this.redis.get(s);if(v==null)throw Error(`Session with sid ${e} not found`);let b=Gt(v,o);if(b===void 0)throw Error(`Session with sid ${e} not found`);let I=await G(this.redis,s,v,b,d);if(I==="ok"){await n();return}if(I==="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=V(l,this.log);if(p==null)throw Error(`Session with sid ${e} not found`);let E={...p,...t},y=Le(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=V(t,this.log);if(s)await this.removeFromIdpIndex(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 Bt="tenant:ids",Nt=`
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=`
177
177
  local raw = redis.call('GET', KEYS[1])
178
178
  local previous = nil
179
179
  if raw then previous = cjson.decode(raw) end
@@ -201,7 +201,7 @@ if requestHash ~= '' then
201
201
  redis.call('SET', KEYS[4], ARGV[2])
202
202
  end
203
203
  return ARGV[3]
204
- `,Ht=`
204
+ `,Yt=`
205
205
  local owner = redis.call('GET', KEYS[1])
206
206
  if not owner or owner ~= ARGV[1] then return false end
207
207
  local raw = redis.call('GET', KEYS[2])
@@ -220,7 +220,7 @@ redis.call('SET', KEYS[2], ARGV[3])
220
220
  if nextHash ~= ARGV[2] then redis.call('DEL', KEYS[1]) end
221
221
  if nextHash ~= '' then redis.call('SET', KEYS[3], ARGV[1]) end
222
222
  return ARGV[3]
223
- `,Vt=`
223
+ `,$t=`
224
224
  local raw = redis.call('GET', KEYS[1])
225
225
  if not raw then return false end
226
226
  local tenant = cjson.decode(raw)
@@ -257,4 +257,4 @@ redis.call('SET', KEYS[1], updated)
257
257
  if ARGV[4] ~= '' then redis.call('SET', KEYS[2], ARGV[6]) end
258
258
  if ARGV[8] ~= '' then redis.call('SET', KEYS[3], ARGV[6]) end
259
259
  return updated
260
- `;function De(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()})}function q(e,t){let s=f(e,{store:"tenant",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt)}}class Oe{constructor(e){this.redis=e.redis,this.prefix=x(e,"tenant-store"),this.log=m(e)}key(...e){return S(this.prefix,...e)}entityKey(e){return this.key("tenant",g(e))}idsSetKey(){return this.key(Bt)}integrationHandleKey(e){return`${this.key("tenant:integration")}:${e}`}requestTokenKey(e){return`${this.key("tenant:request")}:${e}`}stagedRequestKey(e){return`${this.key("tenant:staged")}:${e}`}ioniteIdKey(e){return`${this.key("tenant:ionite")}:${g(e)}`}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return q(t,this.log)}async upsert(e){if(!A(this.redis))throw Error("RedisTenantStore.upsert requires adapter.runScript for atomic secondary indexes");let t=e.ioniteId??"";return await this.redis.runScript(Nt,[this.entityKey(e.id),t?this.ioniteIdKey(t):this.key("tenant:ionite:none"),this.idsSetKey(),e.requestTokenHash?this.requestTokenKey(e.requestTokenHash):this.key("tenant:request:none")],[t,e.id,De(e),e.requestTokenHash??"",`${this.key("tenant:request")}:`]),e}async list(e){let t=await this.redis.smembers(this.idsSetKey());if(t.length===0)return R([],e);let s=t.map((a)=>this.entityKey(a)),i=(await this.redis.mget(s)).map((a)=>a!=null?q(a,this.log):void 0).filter((a)=>a!=null);return R(i,e)}async delete(e){let t=await this.get(e),s=new w().srem(this.idsSetKey(),e).del(this.entityKey(e));if(t?.integration)s.del(this.integrationHandleKey(t.integration.handleHash));if(t?.requestTokenHash)s.del(this.requestTokenKey(t.requestTokenHash));if(t?.ioniteId)s.del(this.ioniteIdKey(t.ioniteId));return await s.exec(this.redis),t?1:0}async setIntegration(e,t,s){if(!A(this.redis))throw Error("RedisTenantStore.setIntegration requires adapter.runScript for atomic compare-and-set");let r=t?.handleHash??"",i=t?.ioniteId??"",a=await this.redis.runScript(Vt,[this.entityKey(e),r?this.integrationHandleKey(r):this.key("tenant:integration:none"),i?this.ioniteIdKey(i):this.key("tenant:ionite:none")],[s?.expectedHandleHash===null?"-":s?.expectedHandleHash??"",s?.expectedVersion?.toString()??"",t?JSON.stringify(t):"",r,`${this.key("tenant:integration")}:`,e,new Date().toISOString(),i]);return typeof a==="string"?q(a,this.log):void 0}async getByIntegrationHandleHash(e){let t=await this.redis.get(this.integrationHandleKey(e));return t?this.get(t):void 0}async setStagedRequest(e,t){let s=Math.ceil((Date.parse(t.expiresAt)-Date.now())/1000);if(s<=0)return;await this.redis.setex(this.stagedRequestKey(e),s,JSON.stringify(t))}async getStagedRequest(e){let t=await this.redis.get(this.stagedRequestKey(e)),s=t==null?void 0:f(t,{store:"tenant",log:this.log});if(typeof s?.handle!=="string"||typeof s.expiresAt!=="string")return;if(Date.parse(s.expiresAt)<=Date.now())return;return{handle:s.handle,expiresAt:s.expiresAt}}async getByRequestTokenHash(e){let t=await this.redis.get(this.requestTokenKey(e));return t?this.get(t):void 0}async replaceActionRequest(e,t){if(!A(this.redis))throw Error("RedisTenantStore.replaceActionRequest requires adapter.runScript for atomic compare-and-set");let s=await this.redis.runScript(Ht,[this.requestTokenKey(e),this.entityKey(t.id),t.requestTokenHash?this.requestTokenKey(t.requestTokenHash):this.key("tenant:request:none")],[t.id,e,De(t),t.ioniteId??"",t.requestTokenHash??""]);return typeof s==="string"?q(s,this.log):void 0}async getByIoniteId(e){let t=await this.redis.get(this.ioniteIdKey(e));return t?this.get(t):void 0}}class je{constructor(e){this.ionCache=e.ionCache,this.store=new Oe(e)}async get(e){return this.store.get(e)}async upsert(e){let t=await this.store.upsert(e);return this.ionCache?.delete(e.id),t}async list(e){return this.store.list(e)}async delete(e){let t=await this.store.delete(e);return this.ionCache?.delete(e),t}async getIon(e){if(!this.ionCache)throw Error(`${this.constructor.name}.getIon() requires an app-owned ionCache. Pass { ionCache } (an lru-cache instance whose fetchMethod builds the tenant Ionite and whose dispose `+"closes it) — the SDK does not cache tenant runtimes. See the multi-tenant docs.");return this.ionCache.fetch(e)}async setIntegration(e,t,s){return this.store.setIntegration(e,t,s)}async getByIntegrationHandleHash(e){return this.store.getByIntegrationHandleHash(e)}async setStagedRequest(e,t){return this.store.setStagedRequest(e,t)}async getStagedRequest(e){return this.store.getStagedRequest(e)}async getByRequestTokenHash(e){return this.store.getByRequestTokenHash(e)}async replaceActionRequest(e,t){let s=await this.store.replaceActionRequest(e,t);if(s)this.ionCache?.delete(s.id);return s}async getByIoniteId(e){return this.store.getByIoniteId(e)}}import{list as qt,StoreConflictError as _e}from"@ionite/core";var Ut="user:ids",Mt="user:name:",Yt="user:external-id:";function $t(e){let t=e.createdAt??new Date,s=e.updatedAt??t,r={...e,createdAt:t.toISOString(),updatedAt:s.toISOString()};if(r.sso&&typeof r.sso==="object"&&r.sso!==null){let i=r.sso;if(i.expires instanceof Date)i.expires=i.expires.toISOString()}return JSON.stringify(r)}function ee(e,t){let s=f(e,{store:"user",log:t});if(s===void 0)return;if(s.sso&&typeof s.sso==="object"&&s.sso!==null){let r=s.sso;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 Ge{constructor(e){this.redis=e.redis,this.prefix=x(e,"user-store"),this.log=m(e)}key(...e){return S(this.prefix,...e)}entityKey(e){return this.key("user",g(e))}idsSetKey(){return this.key(Ut)}nameIndexKey(e){return this.key(Mt+g(e))}externalIdIndexKey(e){return this.key(Yt+g(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return ee(t,this.log)}async getByExternalId(e){let t=await this.redis.get(this.externalIdIndexKey(e));return t?this.get(t):void 0}async getByUserName(e){let t=await this.redis.get(this.nameIndexKey(e.toLowerCase()));return t?this.get(t):void 0}async lookup(e){return this.get(e.id??"")}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?ee(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,$t(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"){if(d){let E=await this.redis.get(this.externalIdIndexKey(d));if(E&&E!==t)throw new _e(`externalId "${d}" is already in use`,"unique_violation","externalId")}throw new _e(`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 qt(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)=>ee(n,this.log)).filter((n)=>n!=null);return R(a,t)}}import{list as zt,StoreConflictError as Wt}from"@ionite/core";var Jt="workload-identity:ids",Ft="workload-identity:client:",Xt="workload-identity:external:";function Zt(e){let t=e.createdAt??new Date,s=e.updatedAt??t;return JSON.stringify({...e,createdAt:t.toISOString(),updatedAt:s.toISOString()})}function te(e,t){let s=f(e,{store:"workload-identity",log:t});if(s===void 0)return;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 Be{constructor(e){this.redis=e.redis,this.prefix=x(e,"workload-identity-store"),this.log=m(e)}key(...e){return S(this.prefix,...e)}entityKey(e){return this.key("workload-identity",g(e))}idsSetKey(){return this.key(Jt)}clientIndexKey(e){return this.key(Ft+g(e))}externalIdIndexKey(e){return this.key(Xt+g(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return te(t,this.log)}async lookup(e){if(e.id){let t=await this.get(e.id);if(t)return t}if(e.clientId){let t=await this.redis.get(this.clientIndexKey(e.clientId));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=this.entityKey(t),r=await this.redis.get(s),i=null;if(r!=null)i=te(r,this.log)??null;let a=new Date,n={...e,id:t,createdAt:i?.createdAt??e.createdAt??a,updatedAt:a},o=new w;if(n.clientId)o.claimUnique(this.clientIndexKey(n.clientId),t);if(n.externalId)o.claimUnique(this.externalIdIndexKey(n.externalId),t);if(i?.clientId&&i.clientId!==n.clientId)o.del(this.clientIndexKey(i.clientId));if(i?.externalId&&i.externalId!==n.externalId)o.del(this.externalIdIndexKey(i.externalId));if(o.set(s,Zt(n)),n.clientId)o.set(this.clientIndexKey(n.clientId),t);if(n.externalId)o.set(this.externalIdIndexKey(n.externalId),t);if(o.sadd(this.idsSetKey(),t),await o.exec(this.redis)==="conflict")throw new Wt(`clientId "${n.clientId}" is already in use`,"unique_violation","clientId");return n}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.clientId)s.del(this.clientIndexKey(t.clientId));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 zt(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)=>te(n,this.log)).filter((n)=>n!=null);return R(a,t)}}function Qt(e){return JSON.stringify({...e,expires_at:e.expires_at.toISOString(),created_at:e.created_at.toISOString()})}function es(e,t){let s=f(e,{store:"workload-token",log:t});if(s===void 0)return;return{...s,expires_at:new Date(s.expires_at),created_at:new Date(s.created_at)}}class Ne{constructor(e){this.redis=e.redis,this.prefix=x(e,"workload-token-store"),this.log=m(e)}key(e){return S(this.prefix,"workload","token",g(e))}async set(e){let t=this.key(e.workload_id),s=Math.max(1,Math.floor((e.expires_at.getTime()-Date.now())/1000));await this.redis.setex(t,s,Qt(e))}async get(e){let t=await this.redis.get(this.key(e));if(t==null)return null;let s=es(t,this.log);if(s==null)return null;if(Date.now()>s.expires_at.getTime())return await this.redis.del(this.key(e)),null;return s}async delete(e){await this.redis.del(this.key(e))}async isValid(e){return await this.get(e)!==null}async cleanup(){}}export{ae as DEFAULT_LIST_LIMIT,pt as DEFAULT_MGET_CHUNK_SIZE,oe as MAX_LIST_LIMIT,ye as RedisAccessAssignmentStore,Se as RedisAccessCatalogStore,ke as RedisAccessIndex,Te as RedisCustomerStore,Ae as RedisDelegateStore,Ke as RedisMagicLinkStore,we as RedisResourceStore,Ce as RedisSessionStore,je as RedisTenantStore,w as RedisTxn,Ge as RedisUserStore,Be as RedisWorkloadIdentityStore,Ne as RedisWorkloadTokenStore,G as atomicCompareAndSet,_ as atomicCreate,gt as chunkedMget,At as createEvalshaRunner,Ot as createReactiveRedis,It as createRedisLfvTransport,g as encodeKeyId,x as getKeyPrefix,m as getLogger,S as prefixedKey,Ee as scriptSha1,Et as splitIonRedisSecret,A as supportsRunScript};
260
+ `;function je(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()})}function M(e,t){let s=m(e,{store:"tenant",log:t});if(s===void 0)return;return{...s,createdAt:new Date(s.createdAt),updatedAt:new Date(s.updatedAt)}}class _e{constructor(e){this.redis=e.redis,this.prefix=x(e,"tenant-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("tenant",h(e))}idsSetKey(){return this.key(Ut)}integrationHandleKey(e){return`${this.key("tenant:integration")}:${e}`}requestTokenKey(e){return`${this.key("tenant:request")}:${e}`}stagedRequestKey(e){return`${this.key("tenant:staged")}:${e}`}ioniteIdKey(e){return`${this.key("tenant:ionite")}:${h(e)}`}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return M(t,this.log)}async upsert(e){if(!A(this.redis))throw Error("RedisTenantStore.upsert requires adapter.runScript for atomic secondary indexes");let t=e.ioniteId??"";return await this.redis.runScript(Mt,[this.entityKey(e.id),t?this.ioniteIdKey(t):this.key("tenant:ionite:none"),this.idsSetKey(),e.requestTokenHash?this.requestTokenKey(e.requestTokenHash):this.key("tenant:request:none")],[t,e.id,je(e),e.requestTokenHash??"",`${this.key("tenant:request")}:`]),e}async list(e){let t=await this.redis.smembers(this.idsSetKey());if(t.length===0)return R([],e);let s=t.map((a)=>this.entityKey(a)),i=(await this.redis.mget(s)).map((a)=>a!=null?M(a,this.log):void 0).filter((a)=>a!=null);return R(i,e)}async delete(e){let t=await this.get(e),s=new w().srem(this.idsSetKey(),e).del(this.entityKey(e));if(t?.integration)s.del(this.integrationHandleKey(t.integration.handleHash));if(t?.requestTokenHash)s.del(this.requestTokenKey(t.requestTokenHash));if(t?.ioniteId)s.del(this.ioniteIdKey(t.ioniteId));return await s.exec(this.redis),t?1:0}async setIntegration(e,t,s){if(!A(this.redis))throw Error("RedisTenantStore.setIntegration requires adapter.runScript for atomic compare-and-set");let r=t?.handleHash??"",i=t?.ioniteId??"",a=await this.redis.runScript($t,[this.entityKey(e),r?this.integrationHandleKey(r):this.key("tenant:integration:none"),i?this.ioniteIdKey(i):this.key("tenant:ionite:none")],[s?.expectedHandleHash===null?"-":s?.expectedHandleHash??"",s?.expectedVersion?.toString()??"",t?JSON.stringify(t):"",r,`${this.key("tenant:integration")}:`,e,new Date().toISOString(),i]);return typeof a==="string"?M(a,this.log):void 0}async getByIntegrationHandleHash(e){let t=await this.redis.get(this.integrationHandleKey(e));return t?this.get(t):void 0}async setStagedRequest(e,t){let s=Math.ceil((Date.parse(t.expiresAt)-Date.now())/1000);if(s<=0)return;await this.redis.setex(this.stagedRequestKey(e),s,JSON.stringify(t))}async getStagedRequest(e){let t=await this.redis.get(this.stagedRequestKey(e)),s=t==null?void 0:m(t,{store:"tenant",log:this.log});if(typeof s?.handle!=="string"||typeof s.expiresAt!=="string")return;if(Date.parse(s.expiresAt)<=Date.now())return;return{handle:s.handle,expiresAt:s.expiresAt}}async getByRequestTokenHash(e){let t=await this.redis.get(this.requestTokenKey(e));return t?this.get(t):void 0}async replaceActionRequest(e,t){if(!A(this.redis))throw Error("RedisTenantStore.replaceActionRequest requires adapter.runScript for atomic compare-and-set");let s=await this.redis.runScript(Yt,[this.requestTokenKey(e),this.entityKey(t.id),t.requestTokenHash?this.requestTokenKey(t.requestTokenHash):this.key("tenant:request:none")],[t.id,e,je(t),t.ioniteId??"",t.requestTokenHash??""]);return typeof s==="string"?M(s,this.log):void 0}async getByIoniteId(e){let t=await this.redis.get(this.ioniteIdKey(e));return t?this.get(t):void 0}}class Ge{constructor(e){this.ionCache=e.ionCache,this.store=new _e(e)}async get(e){return this.store.get(e)}async upsert(e){let t=await this.store.upsert(e);return this.ionCache?.delete(e.id),t}async list(e){return this.store.list(e)}async delete(e){let t=await this.store.delete(e);return this.ionCache?.delete(e),t}async getIon(e){if(!this.ionCache)throw Error(`${this.constructor.name}.getIon() requires an app-owned ionCache. Pass { ionCache } (an lru-cache instance whose fetchMethod builds the tenant Ionite and whose dispose `+"closes it) — the SDK does not cache tenant runtimes. See the multi-tenant docs.");return this.ionCache.fetch(e)}async setIntegration(e,t,s){return this.store.setIntegration(e,t,s)}async getByIntegrationHandleHash(e){return this.store.getByIntegrationHandleHash(e)}async setStagedRequest(e,t){return this.store.setStagedRequest(e,t)}async getStagedRequest(e){return this.store.getStagedRequest(e)}async getByRequestTokenHash(e){return this.store.getByRequestTokenHash(e)}async replaceActionRequest(e,t){let s=await this.store.replaceActionRequest(e,t);if(s)this.ionCache?.delete(s.id);return s}async getByIoniteId(e){return this.store.getByIoniteId(e)}}import{list as zt,StoreConflictError as Be}from"@ionite/core";var Wt="user:ids",Jt="user:name:",Ft="user:external-id:";function Xt(e){let t=e.createdAt??new Date,s=e.updatedAt??t,r={...e,createdAt:t.toISOString(),updatedAt:s.toISOString()};if(r.sso&&typeof r.sso==="object"&&r.sso!==null){let i=r.sso;if(i.expires instanceof Date)i.expires=i.expires.toISOString()}return JSON.stringify(r)}function ie(e,t){let s=m(e,{store:"user",log:t});if(s===void 0)return;if(s.sso&&typeof s.sso==="object"&&s.sso!==null){let r=s.sso;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 Ne{constructor(e){this.redis=e.redis,this.prefix=x(e,"user-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("user",h(e))}idsSetKey(){return this.key(Wt)}nameIndexKey(e){return this.key(Jt+h(e))}externalIdIndexKey(e){return this.key(Ft+h(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return ie(t,this.log)}async getByExternalId(e){let t=await this.redis.get(this.externalIdIndexKey(e));return t?this.get(t):void 0}async getByUserName(e){let t=await this.redis.get(this.nameIndexKey(e.toLowerCase()));return t?this.get(t):void 0}async lookup(e){return this.get(e.id??"")}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?ie(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,Xt(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"){if(d){let E=await this.redis.get(this.externalIdIndexKey(d));if(E&&E!==t)throw new Be(`externalId "${d}" is already in use`,"unique_violation","externalId")}throw new Be(`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 zt(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)=>ie(n,this.log)).filter((n)=>n!=null);return R(a,t)}}import{list as Zt,StoreConflictError as Qt}from"@ionite/core";var es="workload-identity:ids",ts="workload-identity:client:",ss="workload-identity:external:";function is(e){let t=e.createdAt??new Date,s=e.updatedAt??t;return JSON.stringify({...e,createdAt:t.toISOString(),updatedAt:s.toISOString()})}function re(e,t){let s=m(e,{store:"workload-identity",log:t});if(s===void 0)return;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 He{constructor(e){this.redis=e.redis,this.prefix=x(e,"workload-identity-store"),this.log=S(e)}key(...e){return f(this.prefix,...e)}entityKey(e){return this.key("workload-identity",h(e))}idsSetKey(){return this.key(es)}clientIndexKey(e){return this.key(ts+h(e))}externalIdIndexKey(e){return this.key(ss+h(e))}async get(e){let t=await this.redis.get(this.entityKey(e));if(t==null)return;return re(t,this.log)}async lookup(e){if(e.id){let t=await this.get(e.id);if(t)return t}if(e.clientId){let t=await this.redis.get(this.clientIndexKey(e.clientId));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=this.entityKey(t),r=await this.redis.get(s),i=null;if(r!=null)i=re(r,this.log)??null;let a=new Date,n={...e,id:t,createdAt:i?.createdAt??e.createdAt??a,updatedAt:a},o=new w;if(n.clientId)o.claimUnique(this.clientIndexKey(n.clientId),t);if(n.externalId)o.claimUnique(this.externalIdIndexKey(n.externalId),t);if(i?.clientId&&i.clientId!==n.clientId)o.del(this.clientIndexKey(i.clientId));if(i?.externalId&&i.externalId!==n.externalId)o.del(this.externalIdIndexKey(i.externalId));if(o.set(s,is(n)),n.clientId)o.set(this.clientIndexKey(n.clientId),t);if(n.externalId)o.set(this.externalIdIndexKey(n.externalId),t);if(o.sadd(this.idsSetKey(),t),await o.exec(this.redis)==="conflict")throw new Qt(`clientId "${n.clientId}" is already in use`,"unique_violation","clientId");return n}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.clientId)s.del(this.clientIndexKey(t.clientId));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 Zt(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)=>re(n,this.log)).filter((n)=>n!=null);return R(a,t)}}function rs(e){return JSON.stringify({...e,expires_at:e.expires_at.toISOString(),created_at:e.created_at.toISOString()})}function ns(e,t){let s=m(e,{store:"workload-token",log:t});if(s===void 0)return;return{...s,expires_at:new Date(s.expires_at),created_at:new Date(s.created_at)}}class Ve{constructor(e){this.redis=e.redis,this.prefix=x(e,"workload-token-store"),this.log=S(e)}key(e){return f(this.prefix,"workload","token",h(e))}async set(e){let t=this.key(e.workload_id),s=Math.max(1,Math.floor((e.expires_at.getTime()-Date.now())/1000));await this.redis.setex(t,s,rs(e))}async get(e){let t=await this.redis.get(this.key(e));if(t==null)return null;let s=ns(t,this.log);if(s==null)return null;if(Date.now()>s.expires_at.getTime())return await this.redis.del(this.key(e)),null;return s}async delete(e){await this.redis.del(this.key(e))}async isValid(e){return await this.get(e)!==null}async cleanup(){}}export{ce as DEFAULT_LIST_LIMIT,ht as DEFAULT_MGET_CHUNK_SIZE,le as MAX_LIST_LIMIT,Se as RedisAccessAssignmentStore,ke as RedisAccessCatalogStore,Ae as RedisAccessIndex,Ee as RedisCustomerStore,ve as RedisDelegateStore,Ce as RedisMagicLinkStore,Te as RedisResourceStore,Oe as RedisSessionStore,Ge as RedisTenantStore,w as RedisTxn,Ne as RedisUserStore,He as RedisWorkloadIdentityStore,Ve as RedisWorkloadTokenStore,G as atomicCompareAndSet,_ as atomicCreate,yt as chunkedMget,bt as createEvalshaRunner,Nt as createReactiveRedis,Dt as createRedisLfvTransport,Pt as deleteKeyspace,h as encodeKeyId,x as getKeyPrefix,S as getLogger,N as normalizeKeyPrefix,f as prefixedKey,U as scanKeysByPrefix,Ie as scriptSha1,vt as splitIonRedisSecret,A as supportsRunScript};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ionite/redis-core",
3
- "version": "0.0.25",
3
+ "version": "0.0.27-beta.20261102.1",
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.25"
27
+ "@ionite/core": "0.0.27-beta.20261102.1"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@types/node": "^26.1.0"