@enterprisestandard/core 0.0.20-beta.20260701.1 → 0.0.20
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 +2403 -2115
- package/dist/index.js +1 -1
- package/dist/server.d.ts +3538 -3018
- package/dist/server.js +1 -1
- package/dist/shared/core-9dvscte3.js +4 -0
- package/package.json +8 -2
- package/dist/shared/core-jgsxwwpf.js +0 -4
package/package.json
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enterprisestandard/core",
|
|
3
|
-
"version": "0.0.20
|
|
4
|
-
"description": "Enterprise Standard Core (
|
|
3
|
+
"version": "0.0.20",
|
|
4
|
+
"description": "Enterprise Standard Core (client-safe main entry; server handlers under ./server)",
|
|
5
5
|
"private": false,
|
|
6
6
|
"author": "enterprisestandard",
|
|
7
7
|
"license": "proprietary",
|
|
8
8
|
"type": "module",
|
|
9
|
+
"engines": {
|
|
10
|
+
"node": ">=20.6"
|
|
11
|
+
},
|
|
9
12
|
"files": [
|
|
10
13
|
"dist"
|
|
11
14
|
],
|
|
@@ -25,5 +28,8 @@
|
|
|
25
28
|
"default": "./dist/server.js"
|
|
26
29
|
}
|
|
27
30
|
}
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@standard-schema/spec": "^1.1.0"
|
|
28
34
|
}
|
|
29
35
|
}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
function xZ(Z){if(Z===void 0||Z===null)return[];return Array.isArray(Z)?Z:[Z]}function RZ(Z){if(typeof Z!=="string")return;return Z.endsWith("/")?Z.slice(0,-1):Z}function W1(Z,X){if(RZ(X.issuer)!==RZ(Z.claims?.iss))return!1;let $=xZ(X.audience);if($.length>0){let Q=xZ(Z.claims?.aud),W=typeof Z.claims?.azp==="string"?Z.claims.azp:void 0;if(!($.some((N)=>Q.includes(N))||(W?$.includes(W):!1)))return!1}let Y=Z.clientId??Z.workloadId??Z.claims?.sub;return X.clientId===Y}function l1(Z,X){let $=Z?.trustedProvisioningClients;if(!$?.length)return;let Y=new Set;for(let Q of $){if(!W1(X,Q))continue;for(let W of Q.permissions??[])Y.add(W)}return Y.size>0?Y:void 0}function n1(Z){let X=Z?.trustedProvisioningClients;if(!X?.length)return[];let $=[];for(let Y of X)for(let Q of Y.permissions??[])$.push({subject:Y.clientId,subjectType:"workload",targetType:"permission",target:Q,status:"active",provenance:{source:"esi-trusted",actor:Y.clientId}});return $}function n(Z){if(typeof Z==="string")return Z.trim();if(Z&&typeof Z==="object"){let X=Z;for(let $ of["id","value","name","displayName"]){let Y=X[$];if(typeof Y==="string"&&Y.trim())return Y.trim()}}return""}function M1(Z){let X=n(Z.subject),$=n(Z.target);if(!X)throw Error("Access change subject must resolve to a non-empty id.");if(!Z.targetType)throw Error("Access change targetType is required.");if(!$)throw Error("Access change target must resolve to a non-empty id.");let Y=(Z.resources??[]).map((G)=>G.trim()).filter(Boolean),Q=!Z.applyToApplication&&Y.length>0?[...Y].sort().join(","):"app";return`${Z.subjectType??"user"}:${X}:${Z.targetType}:${$}:${Q}`}function N1(Z){let X=(Z.resources??[]).map(($)=>$.trim()).filter(Boolean);if(Z.applyToApplication||X.length===0)return[void 0];return X}class K1{catalog;nodes=new Map;subResources=new Map;constructor(Z){this.catalog=Z}getNode(Z,X){let $=`${Z}:${X}`,Y=this.nodes.get($);if(!Y)Y=(Z==="group"?this.catalog.groups:Z==="role"?this.catalog.roles:Z==="permission"?this.catalog.permissions:this.catalog.resources).get(X),this.nodes.set($,Y);return Y}resourceAndSubResourceIds(Z){let X=this.subResources.get(Z);if(!X)X=wZ(Z,this.catalog,this),this.subResources.set(Z,X);return X}invalidate(Z){this.clear()}clear(){this.nodes.clear(),this.subResources.clear()}}async function J1(Z,X,$){if(typeof Z!=="string")return Z;return $?$.getNode("resource",Z):X.resources.get(Z)}async function wZ(Z,X,$){let Y=[],Q=new Set,W=async(G)=>{let N=n(G);if(!N||Q.has(N))return;Q.add(N),Y.push(N);let E=await J1(G,X,$);for(let V of E?.resources??[])await W(V)};return await W(Z),Y}async function t1(Z,X,$){let Y=Z.id??M1(Z),Q=n(Z.subject);if(!Q)throw Error("Access change subject must resolve to a non-empty id.");let W=Z.subjectType??"user",G=N1(Z),N=[],E=new Set,V=new Set,R=(A,T,x)=>{if(!T)return;let C=`${A}:${T}:${x??""}`;if(E.has(C))return;E.add(C),N.push({subject:Q,subjectType:W,targetType:A,target:T,resource:x,rootId:Y})},S=async(A,T,x)=>{for(let C of G)if(A==="permission"&&x?.applyToSubResources&&C){let c=$?await $.resourceAndSubResourceIds(C):await wZ(C,X);for(let f of c)R("permission",T,f)}else R(A,T,C)},U=async(A,T)=>{let x=n(T);if(!x)return;let C=`${A}:${x}`;if(V.has(C))return;if(V.add(C),A==="group"){let f=typeof T==="string"?await($?$.getNode("group",x):X.groups.get(x)):T;await S("group",x,void 0);for(let v of f?.groups??[])await U("group",v);for(let v of f?.roles??[])await U("role",v);for(let v of f?.permissions??[])await U("permission",v);return}if(A==="role"){let f=typeof T==="string"?await($?$.getNode("role",x):X.roles.get(x)):T;await S("role",x,void 0);for(let v of f?.roles??[])await U("role",v);for(let v of f?.permissions??[])await U("permission",v);return}let c=typeof T==="string"?await($?$.getNode("permission",x):X.permissions.get(x)):T;await S("permission",x,c)};return await U(Z.targetType,Z.target),N}function o1(Z){return{"~standard":{version:1,vendor:Z,validate:(X)=>{if(typeof X!=="object"||X===null)return{issues:[{message:"Expected an object"}]};let $=X,Y=[],Q={};if("code"in $)if(typeof $.code==="string")Q.code=$.code;else Y.push({message:"code must be a string",path:["code"]});else if(!("error"in $))Y.push({message:"code is required",path:["code"]});if("state"in $)if(typeof $.state==="string"||$.state===void 0)Q.state=$.state;else Y.push({message:"state must be a string",path:["state"]});if("session_state"in $)if(typeof $.session_state==="string"||$.session_state===void 0)Q.session_state=$.session_state;else Y.push({message:"session_state must be a string",path:["session_state"]});if("error"in $){if(typeof $.error==="string")Q.error=$.error;else Y.push({message:"error must be a string",path:["error"]});if("error_description"in $)if(typeof $.error_description==="string"||$.error_description===void 0)Q.error_description=$.error_description;else Y.push({message:"error_description must be a string",path:["error_description"]});if("error_uri"in $)if(typeof $.error_uri==="string"||$.error_uri===void 0)Q.error_uri=$.error_uri;else Y.push({message:"error_uri must be a string",path:["error_uri"]})}if("iss"in $)if(typeof $.iss==="string"||$.iss===void 0)Q.iss=$.iss;else Y.push({message:"iss must be a string",path:["iss"]});if(Y.length>0)return{issues:Y};return{value:Q}}}}}function r1(Z){return{"~standard":{version:1,vendor:Z,validate:(X)=>{if(typeof X!=="object"||X===null)return{issues:[{message:"Expected an object"}]};let $=X,Y=[],Q={};if("access_token"in $)if(typeof $.access_token==="string")Q.access_token=$.access_token;else Y.push({message:"access_token must be a string",path:["access_token"]});else Y.push({message:"access_token is required",path:["access_token"]});if("id_token"in $)if(typeof $.id_token==="string")Q.id_token=$.id_token;else Y.push({message:"id_token must be a string",path:["id_token"]});else Y.push({message:"id_token is required",path:["id_token"]});if("token_type"in $)if(typeof $.token_type==="string")Q.token_type=$.token_type;else Y.push({message:"token_type must be a string",path:["token_type"]});else Y.push({message:"token_type is required",path:["token_type"]});if("refresh_token"in $)if(typeof $.refresh_token==="string"||$.refresh_token===void 0)Q.refresh_token=$.refresh_token;else Y.push({message:"refresh_token must be a string",path:["refresh_token"]});if("scope"in $)if(typeof $.scope==="string"||$.scope===void 0)Q.scope=$.scope;else Y.push({message:"scope must be a string",path:["scope"]});if("session_state"in $)if(typeof $.session_state==="string"||$.session_state===void 0)Q.session_state=$.session_state;else Y.push({message:"session_state must be a string",path:["session_state"]});if("expires"in $)if(typeof $.expires==="string"||$.expires===void 0)Q.expires=$.expires;else Y.push({message:"expires must be a string",path:["expires"]});if("expires_in"in $)if(typeof $.expires_in==="number"||$.expires_in===void 0)Q.expires_in=$.expires_in;else Y.push({message:"expires_in must be a number",path:["expires_in"]});if("refresh_expires_in"in $)if(typeof $.refresh_expires_in==="number"||$.refresh_expires_in===void 0)Q.refresh_expires_in=$.refresh_expires_in;else Y.push({message:"refresh_expires_in must be a number",path:["refresh_expires_in"]});if(Y.length>0)return{issues:Y};return{value:Q}}}}}function SZ(Z){return{"~standard":{version:1,vendor:Z,validate:(X)=>{if(typeof X!=="object"||X===null)return{issues:[{message:"Expected an object"}]};let $=X,Y=[],Q={...$},W=["iss","sub"];for(let V of W)if(typeof $[V]!=="string")Y.push({message:`${V} is required and must be a string`,path:[V]});let G=$.aud;if(!(typeof G==="string"||Array.isArray(G)&&G.length>0&&G.every((V)=>typeof V==="string")))Y.push({message:"aud is required and must be a string or a non-empty array of strings",path:["aud"]});if(typeof $.exp!=="number")Y.push({message:"exp is required and must be a number",path:["exp"]});let E=["sid","name","email","preferred_username","picture"];for(let V of E)if(V in $&&$[V]!==void 0){if(typeof $[V]!=="string")Y.push({message:`${V} must be a string`,path:[V]})}if("iat"in $&&$.iat!==void 0&&typeof $.iat!=="number")Y.push({message:"iat must be a number",path:["iat"]});if(Y.length>0)return{issues:Y};return{value:Q}}}}}function qZ(Z){let X=Z["~standard"];return Object.assign(Z,{validate($){return Promise.resolve(X.validate($))}})}function z(Z,X="Assertion failed. Required value is null or undefined."){if(Z===void 0||Z===null)throw Error(X);return Z}function CZ(Z,X){return Response.json({error:"validation_failed",message:X,issues:Z},{status:400,headers:{"Content-Type":"application/json"}})}function e1(Z,X,$=[]){let Y={...Z,...X};for(let Q of $)Y[Q]=Z?.[Q]??X?.[Q];return Y}function H1(Z){let X="",$=0,Y=Z.length;while($<Y){let Q=Z[$];if(Q==='"'||Q==="'"){let W=Q;X+=Q,$++;while($<Y){let G=Z[$];if(G==="\\"){if(X+=G,$+1<Y)X+=Z[$+1],$+=2;else $++;continue}if(G===W){X+=G,$++;break}X+=G,$++}continue}if(Q==="/"&&$+1<Y){let W=Z[$+1];if(W==="/"){$+=2;while($<Y&&Z[$]!==`
|
|
2
|
-
`)$++;if($<Y)X+=`
|
|
3
|
-
`;$++;continue}if(W==="*"){$+=2;while($+1<Y&&!(Z[$]==="*"&&Z[$+1]==="/"))$++;$+=2;continue}}X+=Q,$++}return X}function Z8(Z){let X=H1(Z);return JSON.parse(X)}function X8(Z){return Z==="/"?Z:Z.replace(/\/+$/,"")}function JZ(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return!1;let X=Object.getPrototypeOf(Z);return X===Object.prototype||X===null}function HZ(Z){return Object.keys(Z).filter((X)=>Z[X]!==void 0).sort()}function UZ(Z,X){if(Object.is(Z,X))return!0;if(Z===null||X===null)return Z===X;if(Array.isArray(Z)||Array.isArray(X)){if(!Array.isArray(Z)||!Array.isArray(X)||Z.length!==X.length)return!1;for(let Q=0;Q<Z.length;Q+=1)if(!UZ(Z[Q],X[Q]))return!1;return!0}if(!JZ(Z)||!JZ(X))return!1;let $=HZ(Z),Y=HZ(X);if($.length!==Y.length)return!1;for(let Q=0;Q<$.length;Q+=1)if($[Q]!==Y[Q])return!1;for(let Q of $)if(!UZ(Z[Q],X[Q]))return!1;return!0}function LZ(Z,X){if(Z===null||Z===void 0){X.push("n");return}if(Array.isArray(Z)){X.push("[");for(let $ of Z)LZ($,X);X.push("]");return}if(JZ(Z)){X.push("{");for(let $ of HZ(Z))X.push(JSON.stringify($),":"),LZ(Z[$],X);X.push("}");return}X.push(JSON.stringify(Z))}function $8(Z){let X=[];LZ(Z,X);let $=X.join(""),Y=2166136261;for(let Q=0;Q<$.length;Q+=1)Y^=$.charCodeAt(Q),Y=Y*16777619%9007199254740992;return`${$.length.toString(36)}:${Y.toString(36)}`}async function Q8(Z,X=async(G)=>G.status===200,$=1000,Y=1e4,Q,W){let G=Date.now(),N=`Awaiting Ping (${Z})`;return new Promise((E,V)=>{let R=null,S=null,U=async()=>{try{let A=await fetch(Z);if(A.ok)if(await X(A)){if(R)clearInterval(R);if(S)clearInterval(S);E()}else N=`Response test failed: ${A.status}: ${A.statusText} - ${Z}`;else try{let T=await A.json();N=`Response error: ${A.status}: ${A.statusText} - ${Z}: ${JSON.stringify(T)}`}catch(T){N=`Response error: ${A.status}: ${A.statusText} - ${Z}`}}catch(A){N=`${A instanceof Error?A.message:String(A)} - ${Z}`}};if(U(),R=setInterval(U,$),Y>0)S=setInterval(()=>{W?.warn(`${N}: ${Date.now()-G}ms`)},Y);if(Q)setTimeout(()=>{if(R)clearInterval(R);if(S)clearInterval(S);V(Error(`Timeout: ${Q}ms: ${N}`))},Q)})}var L1="@enterprisestandard/core",P1=qZ(SZ(L1));function _1(Z){let X=Z.exp!=null?new Date(Z.exp*1000):new Date,$=Z.iss??"";return{id:Z.sub??"",userName:Z.preferred_username??"",name:Z.name??"",email:Z.email??"",avatar:Z.picture,sso:{profile:{...Z,iss:Z.iss??$,aud:Z.aud},tenant:{id:Z.idp??$,name:$},tokenType:"Bearer",expires:X}}}function V1(Z){let X=Z.replace(/-/g,"+").replace(/_/g,"/");return atob(X)}async function W8(Z){let X=Z.split(".");if(X.length!==3)throw Error("Invalid JWT");let $=V1(X[1]),Y=JSON.parse($),Q=await P1.validate(Y);if(Q.issues)throw Error(`ID token claims validation failed: ${Q.issues.map((W)=>W.message).join("; ")}`);if(Q.value)return _1(Q.value);throw Error("ID token claims validation failed")}function D1(Z){for(let X=0;X<Z.length;X++){let $=Z.charCodeAt(X);if($<=31||$===127)return!0}return!1}function F1(Z,X){let $=null;try{$=new URL(Z,X)}catch{$=null}let Y="";try{Y=new URL(X).origin}catch{Y=""}return{candidate:Z,url:$,requestOrigin:Y}}function bZ(Z,X,$){let Y=F1(Z,$),Q=!1;for(let W of X){let G=W(Y);if(G==="deny")return!1;if(G==="allow")Q=!0}return Q}function O1(){return({candidate:Z,url:X})=>{if(D1(Z))return"deny";if(Z.includes("\\"))return"deny";if(Z.startsWith("//"))return"deny";if(!X)return"deny";if(X.protocol!=="http:"&&X.protocol!=="https:")return"deny";if(X.username||X.password)return"deny";return"abstain"}}function E1(){return({candidate:Z})=>Z.startsWith("/")&&!Z.startsWith("//")&&!Z.startsWith("/\\")?"allow":"abstain"}function z1(){return({url:Z,requestOrigin:X})=>Z&&X&&Z.origin===X?"allow":"abstain"}function N8(...Z){let X=new Set(Z.map(($)=>{try{return new URL($).origin}catch{return $}}));return({url:$})=>$&&X.has($.origin)?"allow":"abstain"}function K8(...Z){let X=Z.map(($)=>$.toLowerCase());return({url:$})=>{if(!$)return"abstain";let Y=$.hostname.toLowerCase();for(let Q of X)if(Q.startsWith(".")){if(Y===Q.slice(1)||Y.endsWith(Q))return"allow"}else if(Y===Q)return"allow";return"abstain"}}function yZ(){return[O1(),E1(),z1()]}function A1(Z,X,$){if(!Z)return!1;return bZ(Z,X,$)}function vZ(Z,X){if(!Z)return X.fallback;return bZ(Z,X.rules,X.requestUrl)?Z:X.fallback}var J8={rules:yZ(),fallback:"/"};function H8(Z,X,$="redirect"){let Y=new URL(Z.url).searchParams.get($)??void 0;return A1(Y,X.rules,Z.url)?{redirect:Y}:void 0}function L8(Z,X){let $=Z.context;return vZ($?.redirect,{rules:X.rules,fallback:X.fallback,requestUrl:Z.request.url})}function e(Z,X,$){if(Z instanceof Response)return{response:Z};if(typeof Z==="string")return{location:vZ(Z,{rules:yZ(),fallback:X,requestUrl:$})};return{location:X}}function PZ(Z,X){if(X.length===0)return Z;let $=new Headers(Z.headers);for(let Y of X)$.append("Set-Cookie",Y);return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:$})}function j1(Z){let X={};if(!Z)return X;let $=Z.split(";");for(let Y of $){let Q=Y.trim();if(!Q)continue;let W=Q.indexOf("=");if(W===-1)continue;X[Q.slice(0,W).trim()]=Q.slice(W+1).trim()}return X}function hZ(Z){if(!Z.expiresAt)return!1;let X=Z.expiresAt instanceof Date?Z.expiresAt:new Date(Z.expiresAt);return!Number.isNaN(X.getTime())&&Date.now()>X.getTime()}function T1(Z){if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let{access_token:X,id_token:$,refresh_token:Y,tokens:Q,...W}=Z;return W}function k(Z,X){let $=Z[X];return typeof $==="string"?$:""}function I1(Z,X){let $=Z.exp;if(typeof $==="number")return new Date($*1000);if(typeof $==="string"&&$.trim()){let Y=Number($);if(!Number.isNaN(Y))return new Date(Y*1000)}if(X instanceof Date)return X;if(X){let Y=new Date(X);if(!Number.isNaN(Y.getTime()))return Y}return new Date}function x1(Z){let X=Z.claims;if(!X?.sub||typeof X.sub!=="string")return;let $=I1(X,Z.expiresAt);if(Z.authType==="sso")return{id:X.sub,userName:k(X,"preferred_username"),name:k(X,"name"),email:k(X,"email"),avatar:k(X,"picture")||void 0,sso:{profile:X,tenant:{id:k(X,"idp")||k(X,"iss"),name:k(X,"iss")},tokenType:"Bearer",expires:$}};return{id:X.sub,userName:k(X,"preferred_username"),name:k(X,"name"),email:k(X,"email"),avatar:k(X,"picture")||void 0,userType:"customer",ciam:{profile:X,scope:"openid profile email",tokenType:"Bearer",expires:$}}}function R1(Z){if(Z.authType!=="sso"&&Z.authType!=="ciam")return;if(hZ(Z))return;return{sid:Z.sid,authType:Z.authType,tenantId:typeof Z.tenantId==="string"?Z.tenantId:void 0,sub:Z.sub,expiresAt:Z.expiresAt,createdAt:Z.createdAt,lastActivityAt:Z.lastActivityAt,claims:T1(Z.claims)}}function w1(Z,X){if(!Z.endsWith(".session"))return!1;if(!X||X.length===0)return!0;return X.some(($)=>Z===`${$}.session`)}function S1(Z){if(Z===void 0)return;let X=(Array.isArray(Z)?Z:[Z]).map(($)=>$.trim()).filter(($)=>$.length>0);return X.length>0?X:void 0}async function U1(Z,X,$){return(await q1(Z,X,$)).map(R1).filter((Q)=>Boolean(Q))}async function q1(Z,X,$){let Y=j1(Z.headers.get("cookie")),Q=S1($?.cookiesPrefix),W=[],G=new Set;for(let[N,E]of Object.entries(Y)){if(!w1(N,Q)||!E)continue;if(G.has(E))continue;G.add(E);let V=await X.get(E);if(!V)continue;if(V.authType!=="sso"&&V.authType!=="ciam")continue;if(hZ(V))continue;W.push(V)}return W}async function _8(Z,X,$){return(await U1(Z,X,$)).map(x1).filter((Q)=>Boolean(Q))}var m=new Map;function kZ(Z,X){m.delete(Z),m.set(Z,X);while(m.size>256){let $=m.keys().next().value;if($===void 0)break;m.delete($)}}var a=new Map,_Z=()=>Date.now();function D8(Z){_Z=Z??(()=>Date.now())}function C1(Z){if(!Z)return;if(/\bno-store\b/i.test(Z))return 60000;let X=/max-age\s*=\s*(\d+)/i.exec(Z);if(!X)return;let $=Number(X[1]);return Number.isFinite($)?$*1000:void 0}function b1(Z){let $=C1(Z)??600000;return Math.min(Math.max($,60000),86400000)}async function VZ(Z,X=3,$=1000,Y=30000,Q){let W=Error("Placeholder Error");for(let G=0;G<=X;G++)try{return await Z()}catch(N){if(W=N instanceof Error?N:Error(String(N)),N instanceof Error&&N.message.includes("400"))throw N;if(G===X)throw W;let E=Math.min($*2**G,Y),V=Math.random()*0.1*E;await new Promise((R)=>setTimeout(R,E+V)),Q?.warn(`Retry attempt ${G+1} after ${E+V}ms delay`)}throw W}async function ZZ(Z,X,$){let Y=m.get(Z);if(!$?.forceRefresh&&Y&&Y.expiresAt>_Z())return kZ(Z,Y),Y.jwks;let Q=a.get(Z);if(Q)return Q;let W=(async()=>{try{return await VZ(async()=>{let G=await fetch(Z);if(!G.ok)throw Error("Failed to fetch JWKS");let N=await G.json(),E=b1(G.headers.get("cache-control"));return kZ(Z,{jwks:N,expiresAt:_Z()+E}),N},void 0,void 0,void 0,X)}catch(G){let N=m.get(Z);if(N)return X?.warn("JWKS refresh failed; serving last-known-good keys",{"es.operation":"jwks.refresh","es.outcome":"degraded"}),N.jwks;throw G}finally{a.delete(Z)}})();return a.set(Z,W),W}function F8(Z){if(Z){m.delete(Z),a.delete(Z);return}m.clear(),a.clear()}async function DZ(Z,X,$){if(!X?.trim())throw Error("JWT header missing kid");let Y=await ZZ(Z,$),Q=Y.keys.find((W)=>W.kid===X);if(!Q)Y=await ZZ(Z,$,{forceRefresh:!0}),Q=Y.keys.find((W)=>W.kid===X);if(!Q)throw Error("Public key not found");return Q}async function O8(Z,X){let $=Z.keys.find((Y)=>Y.kid===X);if(!$)throw Error("Public key not found");return fZ($)}function fZ(Z){return crypto.subtle.importKey("jwk",{kty:Z.kty,n:Z.n,e:Z.e},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"])}async function E8(Z,X,$){let Y=await DZ(Z,X,$);return fZ(Y)}function QZ(Z=32){let X=new Uint8Array(Z);return crypto.getRandomValues(X),Array.from(X,($)=>$.toString(16).padStart(2,"0")).join("").substring(0,Z)}function XZ(Z){let X="";return Z.forEach(($)=>{X+=String.fromCharCode($)}),btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function gZ(Z){let X=Z.replace(/-/g,"+").replace(/_/g,"/"),$=X.padEnd(X.length+(4-X.length%4)%4,"="),Y=atob($),Q=new Uint8Array(Y.length);for(let W=0;W<Y.length;W++)Q[W]=Y.charCodeAt(W);return Q}function mZ(Z){let X=new TextDecoder().decode(gZ(Z));return JSON.parse(X)}async function pZ(Z){let X=new TextEncoder().encode(Z),$=await crypto.subtle.digest("SHA-256",X);return XZ(new Uint8Array($))}function j8(Z){let X=new URL(Z.authorizationUrl);if(X.searchParams.set("client_id",Z.clientId),X.searchParams.set("redirect_uri",Z.redirectUri),X.searchParams.set("response_type","code"),X.searchParams.set("scope",Z.scope),X.searchParams.set("state",Z.state),Z.codeChallenge)X.searchParams.set("code_challenge",Z.codeChallenge),X.searchParams.set("code_challenge_method","S256");for(let[$,Y]of Object.entries(Z.extraParams??{}))X.searchParams.set($,Y);return X.toString()}async function T8(Z){let X=new URLSearchParams;if(X.append("grant_type","authorization_code"),X.append("code",Z.code),X.append("redirect_uri",Z.redirectUri),X.append("client_id",Z.clientId),Z.clientSecret)X.append("client_secret",Z.clientSecret);if(Z.codeVerifier)X.append("code_verifier",Z.codeVerifier);let $=await fetch(Z.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:X.toString()}),Y=await $.json();if(!$.ok){let Q=Y;throw Z.log?.error("OIDC authorization-code exchange failed",{"es.operation":"token.exchange","es.outcome":"failure","http.status_code":$.status,oidc_error:Q.error}),Error(`Token exchange failed: ${Q.error||$.statusText} - ${Q.error_description||""}`.trim())}if(typeof Y.access_token!=="string")throw Error("Token exchange response missing access_token");return Y}async function y1(Z){if(Z.kty==="EC")return{key:await crypto.subtle.importKey("jwk",{kty:"EC",crv:Z.crv,x:Z.x,y:Z.y},{name:"ECDSA",namedCurve:Z.crv??"P-256"},!1,["verify"]),algorithm:{name:"ECDSA",hash:"SHA-256"}};return{key:await crypto.subtle.importKey("jwk",{kty:Z.kty,n:Z.n,e:Z.e},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]),algorithm:{name:"RSASSA-PKCS1-v1_5"}}}var dZ=60;function $Z(Z){return Z.trim().replace(/\/$/,"")}function v1(Z){let{claims:X,audience:$}=Z,Y=$Z(Z.issuer),Q=Z.nowSec??Math.floor(Date.now()/1000),W=Z.clockSkewSec??dZ,G=X.iss;if(typeof G!=="string"||$Z(G)!==Y)throw Error("ID token issuer mismatch");let N=X.aud,E=Array.isArray(N)?N.includes($):typeof N==="string"&&N===$,V=typeof X.azp==="string"&&X.azp===$;if(!E&&!V)throw Error("ID token audience mismatch");if(typeof X.exp!=="number")throw Error("ID token missing exp");if(X.exp<Q-W)throw Error("ID token expired")}async function uZ(Z,X,$){let Y=Z.split(".");if(Y.length!==3)throw Error("Invalid JWT");let Q=mZ(Y[0]),W=mZ(Y[1]),G=gZ(Y[2]),N=await DZ(X,Q.kid,$),{key:E,algorithm:V}=await y1(N),R=new TextEncoder().encode(`${Y[0]}.${Y[1]}`);if(!await crypto.subtle.verify(V,E,G,R))throw Error("Invalid JWT signature");return{header:Q,payload:W}}async function cZ(Z){let{payload:X}=await uZ(Z.idToken,Z.jwksUri,Z.log);return v1({claims:X,issuer:Z.issuer,audience:Z.audience,clockSkewSec:Z.clockSkewSec}),X}var h1="http://schemas.openid.net/event/backchannel-logout";async function lZ(Z){let{payload:X}=await uZ(Z.logoutToken,Z.jwksUri,Z.log),$=$Z(Z.issuer),Y=X.iss;if(typeof Y!=="string"||$Z(Y)!==$)throw Error("Logout token issuer mismatch");let Q=X.aud,W=Array.isArray(Q)?Q.includes(Z.audience):typeof Q==="string"&&Q===Z.audience,G=typeof X.azp==="string"&&X.azp===Z.audience;if(!W&&!G)throw Error("Logout token audience mismatch");if(X.nonce!=null)throw Error("Logout token must not contain a nonce");let N=X.events;if(!(typeof N==="object"&&N!==null&&!Array.isArray(N)&&Object.hasOwn(N,h1)))throw Error("Logout token missing back-channel logout event");let V=typeof X.sid==="string"&&X.sid.length>0,R=typeof X.sub==="string"&&X.sub.length>0;if(!V&&!R)throw Error("Logout token missing sid and sub");if(typeof X.exp==="number"){let S=Math.floor(Date.now()/1000),U=Z.clockSkewSec??dZ;if(X.exp<S-U)throw Error("Logout token expired")}return X}var k1=3600000,f1=60000,m1=86400000,t=new Map,i=new Map,FZ=()=>Date.now();function I8(Z){FZ=Z??(()=>Date.now())}function x8(Z){if(Z){t.delete(Z),i.delete(Z);return}t.clear(),i.clear()}function g1(Z){let X=Z?/max-age\s*=\s*(\d+)/i.exec(Z):null,$=X?Number(X[1]):Number.NaN,Y=Number.isFinite($)?$*1000:k1;return Math.min(Math.max(Y,f1),m1)}async function R8(Z){let X=t.get(Z);if(X&&X.expiresAt>FZ())return X.endpoints;let $=i.get(Z);if($)return $;let Y=(async()=>{try{let Q=Z.replace(/\/$/,""),W=await fetch(`${Q}/.well-known/openid-configuration`,{headers:{Accept:"application/json"}});if(!W.ok)throw Error(`OIDC discovery failed for ${Z} with status ${W.status}`);let G=await W.json(),N={authorizationUrl:typeof G.authorization_endpoint==="string"?G.authorization_endpoint:void 0,tokenUrl:typeof G.token_endpoint==="string"?G.token_endpoint:void 0,jwksUri:typeof G.jwks_uri==="string"?G.jwks_uri:void 0,userInfoUrl:typeof G.userinfo_endpoint==="string"?G.userinfo_endpoint:void 0};return t.set(Z,{endpoints:N,expiresAt:FZ()+g1(W.headers.get("cache-control"))}),N}catch(Q){let W=t.get(Z);if(W)return W.endpoints;throw Q}finally{i.delete(Z)}})();return i.set(Z,Y),Y}async function w8(Z,X){let $=await fetch(Z,{headers:{Authorization:`Bearer ${X}`,Accept:"application/json","User-Agent":"enterprise-standard-ciam"}});if(!$.ok)throw Error(`UserInfo request failed with status ${$.status}`);return await $.json()}function p1(Z){let X=Z.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,""),$=atob(X),Y=new Uint8Array($.length);for(let Q=0;Q<$.length;Q++)Y[Q]=$.charCodeAt(Q);return Y}async function S8(Z){let X=Math.floor(Date.now()/1000),$={alg:"ES256",kid:Z.keyId,typ:"JWT"},Y={iss:Z.teamId,iat:X,exp:X+(Z.expiresInSeconds??3600),aud:"https://appleid.apple.com",sub:Z.clientId},Q=XZ(new TextEncoder().encode(JSON.stringify($))),W=XZ(new TextEncoder().encode(JSON.stringify(Y))),G=`${Q}.${W}`,N=await crypto.subtle.importKey("pkcs8",p1(Z.privateKey),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),E=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},N,new TextEncoder().encode(G));return`${G}.${XZ(new Uint8Array(E))}`}function w(Z){return Date.now()-Z}function OZ(Z){if(Z instanceof Error)return{"error.name":Z.name,"error.message":Z.message};return{"error.name":typeof Z,"error.message":String(Z)}}function YZ(Z,X){if(!Z)return{};try{let $=new URL(Z);return{[`${X}.origin`]:$.origin,[`${X}.path`]:$.pathname}}catch{return{[`${X}.path`]:Z.startsWith("/")?Z:`/${Z}`}}}function GZ(Z,X=5){if(!Array.isArray(Z))return[String(Z)];return Z.slice(0,X).map(($)=>{if(!$||typeof $!=="object")return String($);let Y=$,Q=Array.isArray(Y.path)?Y.path.join("."):String(Y.path??""),W=typeof Y.message==="string"?Y.message:String(Y.message??"validation failed");return Q?`${Q}: ${W}`:W})}function d1(Z){if(!Z||typeof Z!=="object")return{};let X=Z;return{oidc_error:typeof X.error==="string"?X.error:void 0,oidc_error_description:typeof X.error_description==="string"?X.error_description:void 0,oidc_error_uri:typeof X.error_uri==="string"?X.error_uri:void 0}}function v8(Z,X={}){let $=typeof Z==="string"?Z:Z?.headers.get("cookie")??void 0;if(!$)return[];let Q=`${X.cookiePrefix??"es.sso"}.`,W=new Set;for(let G of Object.keys(u1($))){if(!G.startsWith(Q))continue;let N=G.slice(Q.length),E=N.lastIndexOf(".");if(E<=0)continue;let V=N.slice(0,E).trim();if(V)W.add(V)}return Array.from(W)}function h8(Z,X,$,Y){if(!$&&!Y)return;let Q={...$,...Y},W=!!(Q.authority&&Q.tokenUrl&&Q.authorizationUrl&&Q.clientId&&Q.redirectUri&&Q.scope),G={...Q,authority:W?z(Q.authority,"Missing 'authority' from SSO Config"):Q.authority,tokenUrl:W?z(Q.tokenUrl,"Missing 'tokenUrl' from SSO Config"):Q.tokenUrl,authorizationUrl:W?z(Q.authorizationUrl,"Missing 'authorizationUrl' from SSO Config"):Q.authorizationUrl,clientId:W?z(Q.clientId,"Missing 'clientId' from SSO Config"):Q.clientId,redirectUri:W?z(Q.redirectUri,"Missing 'redirectUri' from SSO Config"):Q.redirectUri,scope:W?z(Q.scope,"Missing 'scope' from SSO Config"):Q.scope,responseType:Q.responseType??"code",cookiesSecure:Q.cookiesSecure!==void 0?Q.cookiesSecure:!0,cookiesSameSite:Q.cookiesSameSite!==void 0?Q.cookiesSameSite:"Strict",cookiesPrefix:Q.cookiesPrefix??(Q.clientId?`es.sso.${Q.clientId}`:"es.sso"),cookiesPath:Q.cookiesPath??"/"};function N(){let B=[];if(!G.authority)B.push("authority");if(!G.tokenUrl)B.push("tokenUrl");if(!G.authorizationUrl)B.push("authorizationUrl");if(!G.clientId)B.push("clientId");if(!G.redirectUri)B.push("redirectUri");if(!G.scope)B.push("scope");if(B.length>0)throw Error(`Missing OIDC configuration fields: ${B.join(", ")}. OIDC configuration is required for SSO operations. Please provide these fields either in your vault configuration or in the SSO config when initializing enterpriseStandard.`)}async function E(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");try{let{tokens:M}=await d(B);if(!M)return{status:"unauthenticated"};return{status:"authenticated",value:await T(M)}}catch(M){if(nZ(M))return{status:"unauthenticated"};return X.error("Error parsing user from cookies",{"es.operation":"cookie.parse","es.outcome":"degraded"},M),{status:"degraded",error:M instanceof Error?M:void 0}}}async function V(B){let M=await E(B);return M.status==="authenticated"?M.value:void 0}async function R(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");N();let M=z(G.redirectUri,"Missing 'redirectUri' from SSO Config"),K=z(G.authorizationUrl,"Missing 'authorizationUrl' from SSO Config"),J=z(G.clientId,"Missing 'clientId' from SSO Config"),O=z(G.scope,"Missing 'scope' from SSO Config"),F=G.cookiesSecure?B.url.replace(/^http:\/\//,"https://"):B.url,L=QZ(),D=QZ(64),_=M;try{new URL(_)}catch{if(F)try{let b=new URL(F),p=_.startsWith("//")?_.slice(1):_.startsWith("/")?_:`/${_}`;_=new URL(p,b.origin).toString()}catch{try{let b=new URL(K),p=_.startsWith("//")?_.slice(1):_.startsWith("/")?_:`/${_}`;_=new URL(p,b.origin).toString()}catch{throw Error(`Invalid redirectUri: "${M}". It must be a valid absolute URL.`)}}}let P=new URL(K);P.searchParams.append("client_id",J),P.searchParams.append("redirect_uri",_),P.searchParams.append("response_type","code"),P.searchParams.append("scope",O),P.searchParams.append("state",L);let I=await pZ(D);P.searchParams.append("code_challenge",I),P.searchParams.append("code_challenge_method","S256");let H=await G.beforeLogin?.({request:B}),j=H===void 0?{state:L,codeVerifier:D}:{state:L,codeVerifier:D,context:H};return new Response("Redirecting to SSO Provider",{status:302,headers:{Location:P.toString(),"Set-Cookie":WZ(r(L),j,G.loginStateTtl??600)}})}async function S(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");let M;try{M=await V(B)}catch{M=void 0}let K=await G.beforeLogout?.({request:B,user:M}),J=o("session",B),O;try{O=await d(B);let H=O.tokens?.refresh_token??o("refresh",B);if(H)await f(H)}catch(H){X.warn("Failed to revoke token",{"es.operation":"token.revoke","es.outcome":"degraded"},H)}if(G.sessionStore)try{let H=O?.sid??J;if(H)await G.sessionStore.delete(H)}catch(H){X.warn("Failed to delete session",{"es.operation":"session.delete","es.outcome":"degraded"},H)}let F=[["Set-Cookie",g("session")]],L=await G.afterLogout?.({request:B,context:K}),D=e(L,"/",B.url);if(D.response){let H=new Headers(D.response.headers);for(let[,j]of F)H.append("Set-Cookie",j);return new Response(D.response.body,{status:D.response.status,statusText:D.response.statusText,headers:H})}let _=D.location??"/",P=B.headers.get("accept");if(P?.includes("application/json")||P?.includes("text/javascript"))return new Response(JSON.stringify({success:!0,message:"Logged out",redirect:_}),{status:200,headers:[["Content-Type","application/json"],...F]});return new Response("Logged out",{status:302,headers:[["Location",_],...F]})}async function U(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");if(!G.sessionStore)throw Error("Back-Channel Logout requires sessionStore configuration");try{if(!B.headers.get("content-type")?.includes("application/x-www-form-urlencoded"))return new Response("Invalid Content-Type, expected application/x-www-form-urlencoded",{status:400});let K=await B.text(),O=new URLSearchParams(K).get("logout_token");if(!O)return new Response("Missing logout_token parameter",{status:400});let F=z(G.authority,"Missing 'authority' from SSO Config. OIDC configuration is required to verify logout tokens."),L=z(G.clientId,"Missing 'clientId' from SSO Config. OIDC configuration is required to verify logout tokens."),D=G.jwksUri||`${F}/protocol/openid-connect/certs`,_=await lZ({logoutToken:O,jwksUri:D,issuer:F,audience:L,log:X}),P=typeof _.sid==="string"?_.sid:void 0;if(!P)return X.warn("Back-Channel Logout: logout_token missing sid claim",{"es.operation":"backchannel_logout","es.outcome":"failure"}),new Response("Invalid logout_token: missing sid claim",{status:400});return await G.sessionStore.delete(P),X.info("Back-Channel Logout: successfully deleted session",{"es.module":"sso",sid:P}),new Response("OK",{status:200})}catch(M){return X.error("Error during back-channel logout",{"es.operation":"backchannel_logout","es.outcome":"failure"},M),new Response("Internal Server Error",{status:500})}}async function A(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");let M=Date.now(),K=new URL(B.url),J=new URLSearchParams(K.search);X.debug("SSO callback received",{"es.event":"es.sso.callback.received","es.module":"sso","es.operation":"sign_in.callback","http.method":B.method,"url.path":K.pathname,hasCode:J.has("code"),hasState:J.has("state"),hasError:J.has("error"),...YZ(J.get("iss")??void 0,"oidc.issuer")});let O=Object.fromEntries(J.entries()),F=await Z.callbackParams.validate(O);if(F.issues)return X.warn("SSO callback parameter validation failed",{"es.event":"es.sso.callback.validation_failed","es.operation":"sign_in.callback","es.outcome":"failure","validation.issues":GZ(F.issues)}),CZ(F.issues,"OIDC callback parameters validation failed");let{code:L,state:D}=F.value,_;try{let P=z(D,'OIDC "state" was not present in the callback parameters'),I=o(r(P),B,!0),{codeVerifier:H,state:j,context:b}=I??{};_=b,X.debug("SSO callback state cookie read",{"es.event":"es.sso.callback.state_cookie_read","es.module":"sso","es.operation":"sign_in.callback",hasStateCookie:Boolean(I),hasCodeVerifier:Boolean(H),hasStateVerifier:Boolean(j),hasContext:b!==void 0});let p=z(H,'OIDC "codeVerifier" was not present in cookies, ensure that the SSO login was initiated correctly');z(j,'OIDC "stateVerifier" was not present in cookies, ensure that the SSO login was initiated correctly');let Q1=z(L,'OIDC "code" was not present in the callback parameters');if(D!==j)throw X.warn("SSO callback state verification failed",{"es.event":"es.sso.callback.state_verification_failed","es.operation":"sign_in.callback","es.outcome":"failure"}),Error('SSO State Verifier failed, the "state" request parameter does not equal the "state" in the SSO cookie');X.debug("SSO callback state verified",{"es.event":"es.sso.callback.state_verified","es.module":"sso","es.operation":"sign_in.callback"});let Y1=G.cookiesSecure?B.url.replace(/^http:\/\//,"https://"):B.url,jZ=await C(Q1,p,Y1),G1=Date.now();X.debug("SSO ID token parsing started",{"es.event":"es.sso.id_token.parse_started","es.module":"sso","es.operation":"id_token.parse"});let h=await T(jZ);X.debug("SSO ID token parsing completed",{"es.event":"es.sso.id_token.parse_completed","es.module":"sso","es.operation":"id_token.parse","duration.ms":w(G1),"user.id":h.id});let MZ,TZ;{let q=AZ("SSO requires sessionStore configuration for opaque session cookies."),u=typeof h.sso.profile.sid==="string"?h.sso.profile.sid:void 0,l=u||QZ(32),y=h.id;if(X.debug("SSO session creation evaluated",{"es.event":"es.sso.session.create_evaluated","es.module":"sso","es.operation":"session.create",hasSid:Boolean(l),hasIdpSid:Boolean(u),hasSub:Boolean(y),"user.id":y}),!y)throw Error("Session creation failed: missing sub in ID token claims");let KZ=Date.now(),s={sid:l,sub:y,idpSid:u,authType:"sso",tenantId:G.tenantId,tokens:jZ,claims:h.sso.profile,expiresAt:h.sso.expires,createdAt:new Date,lastActivityAt:new Date};await rZ(q,s),TZ=s,MZ=["Set-Cookie",WZ("session",l,h.sso.expires)],X.info("SSO session created",{"es.event":"es.sso.session.created","es.operation":"session.create","es.outcome":"success","duration.ms":w(KZ),"user.id":y})}if(G.userStore)try{let q=h.id;if(q){let u=new Date,l=Date.now();X.debug("SSO user store lookup started",{"es.event":"es.sso.user.lookup_started","es.module":"sso","es.operation":"user.lookup","user.id":q});let y=await G.userStore.get(q);if(X.debug("SSO user store lookup completed",{"es.event":"es.sso.user.lookup_completed","es.module":"sso","es.operation":"user.lookup","duration.ms":w(l),"user.id":q,found:Boolean(y)}),y||G.enableJitUserProvisioning){let KZ=Date.now(),s={...y??{},...h,id:q,tenantId:y?.tenantId,createdAt:y?.createdAt??u,updatedAt:u};await G.userStore.upsert(s),X.info("SSO user stored",{"es.event":"es.sso.user.stored","es.operation":"user.store","es.outcome":"success","duration.ms":w(KZ),"user.id":q,existing:Boolean(y),jitProvisioning:Boolean(G.enableJitUserProvisioning)})}else X.warn("JIT user provisioning disabled: user not found in store and will not be created",{"es.event":"es.sso.user.skipped","es.operation":"user.store","es.outcome":"skipped","user.id":q})}else X.warn("User storage skipped: missing sub in ID token claims",{"es.event":"es.sso.user.skipped","es.operation":"user.store","es.outcome":"skipped"})}catch(q){X.warn("Failed to store user",{"es.event":"es.sso.user.store_failed","es.operation":"user.store","es.outcome":"degraded",...OZ(q)})}X.info("SSO sign-in succeeded",{"es.event":"es.sso.sign_in.succeeded","es.operation":"sign_in.callback","es.outcome":"success","duration.ms":w(M),"user.id":h.id});let IZ=[["Set-Cookie",g(r(P))],...MZ?[MZ]:[]],B1=await G.afterLogin?.({ok:!0,request:B,user:h,session:TZ,context:_}),NZ=e(B1,"/",B.url);if(NZ.response)return PZ(NZ.response,IZ.map(([,q])=>q));return new Response("Authentication successful, redirecting",{status:302,headers:[["Location",NZ.location],...IZ]})}catch(P){X.error("Error during sign-in callback",{"es.event":"es.sso.sign_in.callback_failed","es.operation":"sign_in.callback","es.outcome":"failure","duration.ms":w(M),...OZ(P)});let I=D?[["Set-Cookie",g(r(D))]]:[],H=await G.afterLogin?.({ok:!1,request:B,error:P,context:_}),j=e(H,"/",B.url);if(j.response)return PZ(j.response,I.map(([,b])=>b));return new Response("Authentication failed, redirecting",{status:302,headers:[["Location",j.location],...I]})}}async function T(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");let M=Date.now(),K=await oZ(B.id_token),J=Number(B.refresh_expires_in??B.expires_in??3600),O=B.expires?new Date(B.expires):new Date(Date.now()+J*1000);return X.debug("SSO user parsed from ID token",{"es.event":"es.sso.user.parse_completed","es.module":"sso","es.operation":"id_token.parse","duration.ms":w(M),"user.id":K.sub,hasEmail:Boolean(K.email),hasName:Boolean(K.name)}),{id:K.sub,userName:K.preferred_username||"",name:K.name||"",email:K.email||"",emails:[{value:K.email||"",primary:!0}],avatar:K.picture,sso:{profile:{...K},tenant:{id:K.idp||K.iss||"",name:K.iss||""},scope:B.scope,tokenType:B.token_type,sessionState:B.session_state,expires:O}}}async function x(B){if(!G.userStore)return B;let M=await G.userStore.lookup(B);if(!M)return B;return{...B,...M,id:B.id,sso:B.sso}}async function C(B,M,K){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");N();let J=z(G.tokenUrl,"Missing 'tokenUrl' from SSO Config"),O=z(G.redirectUri,"Missing 'redirectUri' from SSO Config"),F=z(G.clientId,"Missing 'clientId' from SSO Config"),L=O;try{new URL(L)}catch{if(K)try{let _=new URL(K),P=L.startsWith("//")?L.slice(1):L.startsWith("/")?L:`/${L}`;L=new URL(P,_.origin).toString()}catch{try{let _=new URL(J),P=L.startsWith("//")?L.slice(1):L.startsWith("/")?L:`/${L}`;L=new URL(P,_.origin).toString()}catch{throw Error(`Invalid redirectUri: "${O}". It must be a valid absolute URL.`)}}}let D=new URLSearchParams;if(D.append("grant_type","authorization_code"),D.append("code",B),D.append("redirect_uri",L),D.append("client_id",F),G.clientSecret)D.append("client_secret",G.clientSecret);D.append("code_verifier",M);try{let _=Date.now();X.debug("SSO token exchange started",{"es.event":"es.sso.token.exchange_started","es.module":"sso","es.operation":"token.exchange",...YZ(J,"oidc.token_url"),...YZ(L,"oidc.redirect_uri"),hasClientSecret:Boolean(G.clientSecret)});let P=await fetch(J,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:D.toString()});X.debug("SSO token exchange response received",{"es.event":"es.sso.token.response_received","es.module":"sso","es.operation":"token.exchange","http.status_code":P.status,"duration.ms":w(_)}),X.debug("SSO token exchange response body read started",{"es.event":"es.sso.token.response_body_read_started","es.module":"sso","es.operation":"token.exchange"});let I=await P.json();if(X.debug("SSO token exchange response body read completed",{"es.event":"es.sso.token.response_body_read_completed","es.module":"sso","es.operation":"token.exchange","duration.ms":w(_)}),!P.ok){X.error("Token exchange error",{"es.event":"es.sso.token.exchange_failed","es.operation":"token.exchange","es.outcome":"failure","http.status_code":P.status,"duration.ms":w(_),...d1(I)});let j=I;throw Error(`Token exchange failed: ${j.error||P.statusText} - ${j.error_description||""}`.trim())}let H=await Z.tokenResponse.validate(I);if(H.issues)throw X.error("Token response validation failed",{"es.event":"es.sso.token.response_validation_failed","es.operation":"token.exchange","es.outcome":"failure","duration.ms":w(_),"validation.issues":GZ(H.issues)}),Error(`Token response validation failed: ${H.issues}`);return X.debug("SSO token exchange completed",{"es.event":"es.sso.token.exchange_completed","es.module":"sso","es.operation":"token.exchange","es.outcome":"success","duration.ms":w(_),tokenType:H.value.token_type,hasAccessToken:Boolean(H.value.access_token),hasIdToken:Boolean(H.value.id_token),hasRefreshToken:Boolean(H.value.refresh_token),expiresIn:H.value.expires_in}),H.value}catch(_){throw X.error("Error during token exchange",{"es.event":"es.sso.token.exchange_failed","es.operation":"token.exchange","es.outcome":"failure",...OZ(_)}),_}}async function c(B){return VZ(async()=>{if(!G)throw Error("Enterprise Standard SSO Manager not initialized");N();let M=z(G.tokenUrl,"Missing 'tokenUrl' from SSO Config"),K=z(G.clientId,"Missing 'clientId' from SSO Config"),J=new URLSearchParams;J.append("grant_type","refresh_token"),J.append("refresh_token",B),J.append("client_id",K);let O=await fetch(M,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:J.toString()}),F=await O.json();if(!O.ok){X.error("Token refresh error",{"es.operation":"token.refresh","es.outcome":"failure",response:F});let D=F;throw Error(`Token refresh failed: ${D.error||O.statusText} - ${D.error_description||""}`.trim())}let L=await Z.tokenResponse.validate(F);if(L.issues)throw X.error("Token refresh response validation failed",{"es.event":"es.sso.token.refresh_validation_failed","es.operation":"token.refresh","es.outcome":"failure","validation.issues":GZ(L.issues)}),Error(`Token refresh response validation failed: ${L.issues}`);return L.value},void 0,void 0,void 0,X)}async function f(B){try{if(!G)throw Error("Enterprise Standard SSO Manager not initialized");if(!G.revocationEndpoint)return;let M=z(G.clientId,"Missing 'clientId' from SSO Config"),K=new URLSearchParams;K.append("token",B),K.append("token_type_hint","refresh_token"),K.append("client_id",M);let J=await fetch(G.revocationEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:K.toString()});if(!J.ok)X.warn("Token revocation failed",{"es.operation":"token.revoke","es.outcome":"degraded",status:J.status,statusText:J.statusText});else X.info("Token revoked successfully",{"es.module":"sso"})}catch(M){X.warn("Error revoking token",{"es.operation":"token.revoke","es.outcome":"degraded"},M)}}async function v(){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");let B=G.authority;if(!G.jwksUri&&!B)throw Error("Missing 'jwksUri' or 'authority' from SSO Config. OIDC configuration is required for this operation.");let M=G.jwksUri||`${B}/protocol/openid-connect/certs`;return ZZ(M,X)}async function oZ(B){let M=Date.now(),K=z(G.authority,"Missing 'authority' from SSO Config. OIDC configuration is required to verify ID tokens."),J=z(G.clientId,"Missing 'clientId' from SSO Config. OIDC configuration is required to verify ID tokens."),O=G.jwksUri||`${K}/protocol/openid-connect/certs`;X.debug("SSO ID token verification started",{"es.event":"es.sso.id_token.verify_started","es.module":"sso","es.operation":"id_token.verify",...YZ(O,"oidc.jwks_uri")});let F;try{F=await cZ({idToken:B,jwksUri:O,issuer:K,audience:J,log:X})}catch(D){throw X.error("SSO ID token verification failed",{"es.event":"es.sso.id_token.verify_failed","es.module":"sso","es.operation":"id_token.verify","es.outcome":"failure","duration.ms":w(M)},D),D}X.debug("SSO ID token signature verified",{"es.event":"es.sso.id_token.signature_verified","es.module":"sso","es.operation":"id_token.verify","duration.ms":w(M)});let L=await Z.idTokenClaims.validate(F);if(L.issues)throw X.error("ID token claims validation failed",{"es.event":"es.sso.id_token.validation_failed","es.operation":"id_token.validate","es.outcome":"failure","duration.ms":w(M),"validation.issues":GZ(L.issues)}),Error(`ID token claims validation failed: ${L.issues}`);return X.debug("SSO ID token claims validated",{"es.event":"es.sso.id_token.claims_validated","es.module":"sso","es.operation":"id_token.validate","es.outcome":"success","duration.ms":w(M),"user.id":L.value.sub,hasIssuer:Boolean(L.value.iss),hasAudience:Boolean(L.value.aud)}),L.value}function AZ(B="SSO sessionStore is required for opaque session cookies."){if(!G.sessionStore)throw Error(B);return G.sessionStore}async function rZ(B,M){try{await B.create(M)}catch(K){if(!await B.get(M.sid))throw K;await B.update(M.sid,M)}}function sZ(B){if(!B)return;if(B instanceof Date)return B;let M=new Date(B);return Number.isNaN(M.getTime())?void 0:M}function eZ(B){let M=B.tokens;if(!M?.access_token||!M.id_token||!M.token_type)return;return M}async function Z1(B,M=!1){let K=AZ(),J=o("session",B);if(!J)return{tokens:void 0,refreshHeaders:[]};let O=await K.get(J);if(O&&G.tenantId&&O.tenantId&&O.tenantId!==G.tenantId)return{tokens:void 0,refreshHeaders:[["Set-Cookie",g("session")]],sid:J};if(O?.authType!=="sso")return{tokens:void 0,refreshHeaders:[["Set-Cookie",g("session")]],sid:J};let F=eZ(O);if(!F)return{tokens:void 0,refreshHeaders:[["Set-Cookie",g("session")]],sid:J};let L=sZ(O.expiresAt),D=L?Date.now()>L.getTime():!1;if((M||D)&&F.refresh_token){let _=await c(F.refresh_token),P=await T(_);return await K.update(J,{tokens:_,claims:P.sso.profile,expiresAt:P.sso.expires,lastActivityAt:new Date}),{tokens:_,sid:J,refreshHeaders:[["Set-Cookie",WZ("session",J,P.sso.expires)]]}}if(D)return await K.delete(J),{tokens:void 0,sid:J,refreshHeaders:[["Set-Cookie",g("session")]]};return await K.update(J,{lastActivityAt:new Date}),{tokens:F,sid:J,refreshHeaders:[]}}async function d(B,M=!1){return Z1(B,M)}async function X1(B){let{tokens:M}=await d(B);if(!M)return;return M.access_token}function WZ(B,M,K){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");if(B=`${G.cookiesPrefix}.${B}`,typeof M!=="string")M=btoa(JSON.stringify(M));let J;if(K instanceof Date)J=`Expires=${K.toUTCString()}`;else if(typeof K==="number")J=`Max-Age=${K}`;else throw Error("Invalid expires type",K);if(M.length>4000)throw Error(`Error setting cookie: ${B}. Cookie length is: ${M.length}`);return`${B}=${M}; ${J}; Path=${G.cookiesPath}; HttpOnly;${G.cookiesSecure?" Secure;":""} SameSite=${G.cookiesSameSite};`}function g(B){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");return`${G.cookiesPrefix}.${B}=; Max-Age=0; Path=${G.cookiesPath}; HttpOnly;${G.cookiesSecure?" Secure;":""} SameSite=${G.cookiesSameSite};`}function o(B,M,K=!1){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");let J=M.headers.get("cookie");if(!J)return null;let O=`${G.cookiesPrefix}.${B}`,F=J.split(";").find((P)=>P.trim().startsWith(`${O}=`));if(!F)return null;let L=F.indexOf("="),D=F.slice(L+1).trim();if(!K)return D;let _=atob(D);return JSON.parse(_)}function r(B){return`state_${B}`}async function $1(B,M){if(!G)throw Error("Enterprise Standard SSO Manager not initialized");let{loginUrl:K,userUrl:J,tokenUrl:O,refreshUrl:F,logoutUrl:L,logoutBackChannelUrl:D,jwksUrl:_,redirectUri:P}={...G,...M},I=new URL(B.url).pathname;if(P){let H;try{H=new URL(P).pathname}catch{try{let j=new URL(B.url),b=P.startsWith("//")?P.slice(1):P;H=new URL(b,j.origin).pathname}catch{H=P.startsWith("/")?P:`/${P}`}}if(H===I)return A(B)}if(K===I)return R(B);if(J===I)try{let{tokens:H,refreshHeaders:j}=await d(B);if(!H)return new Response("User not logged in",{status:401,headers:j});let b=await T(H),p=await x(b);return new Response(JSON.stringify(p),{headers:[["Content-Type","application/json"],...j]})}catch(H){if(nZ(H))return new Response("User not logged in",{status:401});return X.error("Error resolving SSO user",{"es.operation":"sso.user","es.outcome":"degraded"},H),new Response(JSON.stringify({error:"auth_unavailable"}),{status:503,headers:{"Content-Type":"application/json"}})}if(O===I){let{tokens:H,refreshHeaders:j}=await d(B);if(!H)return new Response("User not logged in",{status:401,headers:j});return new Response(JSON.stringify({token:H.access_token,expires:H.expires}),{headers:[["Content-Type","application/json"],...j]})}if(F===I){let{tokens:H,refreshHeaders:j}=await d(B,!0);if(!H)return new Response("User not logged in",{status:401});return new Response("Refresh Complete",{status:200,headers:j})}if(L===I)return S(B);if(D===I)return U(B);if(_===I){let H=await v();return new Response(JSON.stringify(H),{headers:[["Content-Type","application/json"]]})}return new Response("Not Found",{status:404})}return{...G,getUser:V,resolveUser:E,getJwt:X1,initiateLogin:R,logout:S,logoutBackChannel:U,callbackHandler:A,handler:$1}}function u1(Z){let X={},$=Z.split(";");for(let Y of $){let Q=Y.trim();if(!Q)continue;let W=Q.indexOf("=");if(W===-1)continue;let G=Q.slice(0,W).trim(),N=Q.slice(W+1).trim();X[G]=N}return X}function nZ(Z){if(!(Z instanceof Error))return!1;return["Public key not found","Invalid JWT","Invalid JWT signature"].some((X)=>Z.message.includes(X))}function aZ(Z){return Z=Z??"SSO Unavailable",new Response(JSON.stringify({error:Z}),{status:503,statusText:Z,headers:{"Content-Type":"application/json"}})}var BZ="EnterpriseStandard instance is required. Create one with enterpriseStandard(source, config) and pass it to this function.";async function k8(Z,X){return z(X,BZ),X.sso?.getUser(Z)}async function f8(Z,X){return z(X,BZ),await X.sso?.resolveUser(Z)??{status:"unauthenticated"}}async function m8(Z,X){z(X,BZ);let $=X.sso;if(!$)return aZ();return $.initiateLogin(Z)}async function g8(Z,X){z(X,BZ);let $=X.sso;if(!$)return aZ();return $.callbackHandler(Z)}class EZ extends Error{code="conflict";kind;field;constructor(Z,X,$){super(Z);this.name="StoreConflictError",this.kind=X,this.field=$,Object.setPrototypeOf(this,EZ.prototype)}}function d8(Z){return Z instanceof EZ||typeof Z==="object"&&Z!=null&&Z.code==="conflict"}var zZ,tZ;function c8(Z){zZ=Z}function l8(Z){tZ=Z}function c1(Z,X){if(!zZ)throw Error("Tenant config hydration is not registered. Import @enterprisestandard/server before using tenant.config().");return tZ?.({tenantId:Z.id,locator:Z.configLocator}),zZ(Z.configLocator,X,{tenantId:Z.id})}function n8(Z){let X=Z.configLocator;if(!X)return Z;let $=Z.id;return{...Z,config:(Y)=>c1({id:$,configLocator:X},Y)}}var t8="urn:enterprisestandard:params:scim:schemas:extension:authz:2.0:Group",iZ=["user","workload"];function i8(Z){let{assignableSubjectTypes:X,recommendedSubjectTypes:$}=Z,Y=Z.id?` for "${Z.id}"`:"";if(X){let Q=X.filter((W)=>!iZ.includes(W));if(Q.length>0)throw Error(`assignableSubjectTypes${Y} contains values outside the platform ceiling [${iZ.join(", ")}]: ${Q.join(", ")}`)}if($&&X){let Q=$.filter((W)=>!X.includes(W));if(Q.length>0)throw Error(`recommendedSubjectTypes${Y} must be a subset of assignableSubjectTypes; offending values: ${Q.join(", ")}`)}}
|
|
4
|
-
export{l1 as a,n1 as b,n as c,M1 as d,K1 as e,t1 as f,o1 as g,r1 as h,SZ as i,qZ as j,z as k,CZ as l,e1 as m,H1 as n,Z8 as o,X8 as p,UZ as q,$8 as r,Q8 as s,_1 as t,W8 as u,O1 as v,E1 as w,z1 as x,N8 as y,K8 as z,yZ as A,A1 as B,vZ as C,J8 as D,H8 as E,L8 as F,e as G,PZ as H,U1 as I,q1 as J,_8 as K,D8 as L,ZZ as M,F8 as N,DZ as O,O8 as P,E8 as Q,QZ as R,pZ as S,j8 as T,T8 as U,$Z as V,v1 as W,cZ as X,lZ as Y,I8 as Z,x8 as _,R8 as $,w8 as aa,S8 as ba,v8 as ca,h8 as da,k8 as ea,f8 as fa,m8 as ga,g8 as ha,EZ as ia,d8 as ja,c8 as ka,l8 as la,c1 as ma,n8 as na,t8 as oa,iZ as pa,i8 as qa};
|